class Standard

This abstract class holds generic methods that many energy standards would commonly use. Many of the methods in this class apply efficiency values from the OpenStudio-Standards spreadsheet. If a method in this class is redefined by a subclass, the implementation in the subclass is used. @abstract

Constants

STANDARDS_LIST

A list of available Standards subclasses that can be created using the Standard.build() method.

Attributes

space_multiplier_map[RW]
standards_data[RW]
template[R]

Public Class Methods

build(name) click to toggle source

Create an instance of a Standard by passing it’s name

@param name [String] the name of the Standard to build.

valid choices are: DOE Pre-1980, DOE 1980-2004, 90.1-2004,
90.1-2007, 90.1-2010, 90.1-2013, 90.1-2016, 90.1-2019,
NREL ZNE Ready 2017, NECB2011

@example Create a new Standard object by name

standard = Standard.build('NECB2011')
# File lib/openstudio-standards/standards/standard.rb, line 34
def self.build(name)
  if STANDARDS_LIST[name].nil?
    raise "ERROR: Did not find a class called '#{name}' to create in #{JSON.pretty_generate(STANDARDS_LIST)}"
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.standard', "Using OpenStudio Standards version #{OpenstudioStandards::VERSION} with template #{name}.")
  return STANDARDS_LIST[name].new
end
new() click to toggle source

set up template class variable.

Calls superclass method
# File lib/openstudio-standards/standards/standard.rb, line 44
def initialize
  super()
end
register_standard(name) click to toggle source

Add the standard to the STANDARDS_LIST.

# File lib/openstudio-standards/standards/standard.rb, line 22
def self.register_standard(name)
  STANDARDS_LIST[name] = self
end

Public Instance Methods

adjust_sizing_system(air_loop_hvac, dsgn_temps, type_of_load_sizing: 'Sensible', min_sys_airflow_ratio: 0.3, sizing_option: 'Coincident') click to toggle source

Prototype SizingSystem object

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param dsgn_temps [Hash] a hash of design temperature lookups from standard_design_sizing_temperatures @return [OpenStudio::Model::SizingSystem] sizing system object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.SizingSystem.rb, line 9
def adjust_sizing_system(air_loop_hvac,
                         dsgn_temps,
                         type_of_load_sizing: 'Sensible',
                         min_sys_airflow_ratio: 0.3,
                         sizing_option: 'Coincident')

  # adjust sizing system defaults
  sizing_system = air_loop_hvac.sizingSystem
  sizing_system.setTypeofLoadtoSizeOn(type_of_load_sizing)
  sizing_system.autosizeDesignOutdoorAirFlowRate
  sizing_system.setPreheatDesignTemperature(dsgn_temps['prehtg_dsgn_sup_air_temp_c'])
  sizing_system.setPrecoolDesignTemperature(dsgn_temps['preclg_dsgn_sup_air_temp_c'])
  sizing_system.setCentralCoolingDesignSupplyAirTemperature(dsgn_temps['clg_dsgn_sup_air_temp_c'])
  sizing_system.setCentralHeatingDesignSupplyAirTemperature(dsgn_temps['htg_dsgn_sup_air_temp_c'])
  sizing_system.setPreheatDesignHumidityRatio(0.008)
  sizing_system.setPrecoolDesignHumidityRatio(0.008)
  sizing_system.setCentralCoolingDesignSupplyAirHumidityRatio(0.0085)
  sizing_system.setCentralHeatingDesignSupplyAirHumidityRatio(0.0080)
  if air_loop_hvac.model.version < OpenStudio::VersionString.new('2.7.0')
    sizing_system.setMinimumSystemAirFlowRatio(min_sys_airflow_ratio)
  else
    sizing_system.setCentralHeatingMaximumSystemAirFlowRatio(min_sys_airflow_ratio)
  end
  sizing_system.setSizingOption(sizing_option)
  sizing_system.setAllOutdoorAirinCooling(false)
  sizing_system.setAllOutdoorAirinHeating(false)
  sizing_system.setSystemOutdoorAirMethod('ZoneSum')
  sizing_system.setCoolingDesignAirFlowMethod('DesignDay')
  sizing_system.setHeatingDesignAirFlowMethod('DesignDay')

  return sizing_system
end
afue_to_thermal_eff(afue) click to toggle source

A helper method to convert from AFUE to thermal efficiency @ref [References::USDOEPrototypeBuildings] Boiler Addendum 90.1-04an

@param afue [Double] Annual Fuel Utilization Efficiency @return [Double] Thermal efficiency (%)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 407
def afue_to_thermal_eff(afue)
  return afue
end
air_loop_hvac_add_motorized_oa_damper(air_loop_hvac, min_occ_pct = 0.05, occ_sch = nil) click to toggle source

Add a motorized damper by modifying the OA schedule to require zero OA during unoccupied hours. This means that even during morning warmup or nightcyling, no OA will be brought into the building, lowering heating/cooling load. If no occupancy schedule is supplied, one will be created. In this case, occupied is defined as the total percent occupancy for the loop for all zones served. If the OA schedule is already other than Always On, will assume that this schedule reflects a motorized OA damper and not change.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param min_occ_pct [Double] the fractional value below which the system will be considered unoccupied. @param occ_sch [OpenStudio::Model::Schedule] the occupancy schedule.

If not supplied, one will be created based on the supplied occupancy threshold.

@return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2833
def air_loop_hvac_add_motorized_oa_damper(air_loop_hvac, min_occ_pct = 0.05, occ_sch = nil)
  # Get the OA system and OA controller
  oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
  return false unless oa_sys.is_initialized

  oa_sys = oa_sys.get
  oa_control = oa_sys.getControllerOutdoorAir

  # Get the current min OA schedule and do nothing
  # if it is already set to something other than Always On
  if oa_control.minimumOutdoorAirSchedule.is_initialized
    min_oa_sch = oa_control.minimumOutdoorAirSchedule.get
    unless min_oa_sch == air_loop_hvac.model.alwaysOnDiscreteSchedule
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Min OA damper schedule is already set to #{min_oa_sch.name}, assume this includes correct motorized OA damper control.")
      return true
    end
  end

  # Get the airloop occupancy schedule if none supplied
  # or if the supplied availability schedule is Always On, implying
  # that the availability schedule does not reflect occupancy.
  if occ_sch.nil? || occ_sch == air_loop_hvac.model.alwaysOnDiscreteSchedule
    occ_sch = air_loop_hvac_get_occupancy_schedule(air_loop_hvac, occupied_percentage_threshold: min_occ_pct)
    flh = OpenstudioStandards::Schedules.schedule_get_equivalent_full_load_hours(occ_sch)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Annual occupied hours = #{flh.round} hr/yr, assuming a #{min_occ_pct} occupancy threshold.  This schedule will be used to close OA damper during unoccupied hours.")
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Setting motorized OA damper schedule to #{occ_sch.name}.")
  end

  # Set the minimum OA schedule to follow occupancy
  oa_control.setMinimumOutdoorAirSchedule(occ_sch)

  return true
end
air_loop_hvac_adjust_minimum_vav_damper_positions(air_loop_hvac) click to toggle source

Adjust minimum VAV damper positions and set minimum design system outdoor air flow

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if required, false if not @todo Add exception logic for systems serving parking garage, warehouse, or multifamily

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2001
def air_loop_hvac_adjust_minimum_vav_damper_positions(air_loop_hvac)
  # Do not apply the adjustment to some of the system in
  # the hospital and outpatient which have their minimum
  # damper position determined based on AIA 2001 ventilation
  # requirements
  if (@instvarbuilding_type == 'Hospital' && (air_loop_hvac.name.to_s.include?('VAV_ER') || air_loop_hvac.name.to_s.include?('VAV_ICU') ||
                                              air_loop_hvac.name.to_s.include?('VAV_OR') || air_loop_hvac.name.to_s.include?('VAV_LABS') ||
                                              air_loop_hvac.name.to_s.include?('VAV_PATRMS'))) ||
     (@instvarbuilding_type == 'Outpatient' && air_loop_hvac.name.to_s.include?('Outpatient F1'))

    return true
  end

  # Total uncorrected outdoor airflow rate
  v_ou = 0.0
  air_loop_hvac.thermalZones.each do |zone|
    # Vou is the system uncorrected outdoor airflow:
    # Zone airflow is multiplied by the zone multiplier
    v_ou += OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate(zone) * zone.multiplier.to_f
  end

  v_ou_cfm = OpenStudio.convert(v_ou, 'm^3/s', 'cfm').get

  # System primary airflow rate (whether autosized or hard-sized)
  v_ps = 0.0

  v_ps = if air_loop_hvac.designSupplyAirFlowRate.is_initialized
           air_loop_hvac.designSupplyAirFlowRate.get
         elsif air_loop_hvac.autosizedDesignSupplyAirFlowRate.is_initialized
           air_loop_hvac.autosizedDesignSupplyAirFlowRate.get
         end
  v_ps_cfm = OpenStudio.convert(v_ps, 'm^3/s', 'cfm').get

  # Average outdoor air fraction
  x_s = v_ou / v_ps

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: v_ou = #{v_ou_cfm.round} cfm, v_ps = #{v_ps_cfm.round} cfm, x_s = #{x_s.round(2)}.")

  # Determine the zone ventilation effectiveness
  # for every zone on the system.
  # When ventilation effectiveness is too low,
  # increase the minimum damper position.
  e_vzs = []
  e_vzs_adj = []
  num_zones_adj = 0

  # Retrieve the sum of the zone minimum primary airflow
  if air_loop_hvac.model.version < OpenStudio::VersionString.new('3.6.0')
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', 'Required AirLoopHVAC method .autosizedSumMinimumHeatingAirFlowRates is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
  elsif air_loop_hvac.autosizedSumMinimumHeatingAirFlowRates.is_initialized
    vpz_min_sum = air_loop_hvac.autosizedSumMinimumHeatingAirFlowRates.get
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', "autosizedSumMinimumHeatingAirFlowRates is not available for air loop #{air_loop_hvac}.")
  end

  air_loop_hvac.thermalZones.sort.each do |zone|
    # Breathing zone airflow rate
    v_bz = OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate(zone)

    # Zone air distribution, assumed 1 per PNNL
    e_z = 1.0

    # Zone airflow rate
    v_oz = v_bz / e_z

    # Primary design airflow rate
    # max of heating and cooling
    # design air flow rates
    v_pz = 0.0

    # error if zone autosized methods are not available
    if air_loop_hvac.model.version < OpenStudio::VersionString.new('3.6.0')
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', 'Required ThermalZone method .autosizedCoolingDesignAirFlowRate and .autosizedHeatingDesignAirFlowRate are not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
    end

    clg_dsn_flow = zone.autosizedCoolingDesignAirFlowRate
    if clg_dsn_flow.is_initialized
      clg_dsn_flow = clg_dsn_flow.get
      if clg_dsn_flow > v_pz
        v_pz = clg_dsn_flow
      end
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: #{zone.name} clg_dsn_flow could not be found.")
    end
    htg_dsn_flow = zone.autosizedHeatingDesignAirFlowRate
    if htg_dsn_flow.is_initialized
      htg_dsn_flow = htg_dsn_flow.get
      if htg_dsn_flow > v_pz
        v_pz = htg_dsn_flow
      end
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: #{zone.name} htg_dsn_flow could not be found.")
    end

    # Get the minimum damper position
    mdp_term = 1.0
    min_zn_flow = 0.0
    zone.equipment.each do |equip|
      if equip.to_AirTerminalSingleDuctVAVHeatAndCoolNoReheat.is_initialized
        term = equip.to_AirTerminalSingleDuctVAVHeatAndCoolNoReheat.get
        mdp_term = term.zoneMinimumAirFlowFraction
      elsif equip.to_AirTerminalSingleDuctVAVHeatAndCoolReheat.is_initialized
        term = equip.to_AirTerminalSingleDuctVAVHeatAndCoolReheat.get
        mdp_term = term.zoneMinimumAirFlowFraction
      elsif equip.to_AirTerminalSingleDuctVAVNoReheat.is_initialized
        term = equip.to_AirTerminalSingleDuctVAVNoReheat.get
        if term.constantMinimumAirFlowFraction.is_initialized
          mdp_term = term.constantMinimumAirFlowFraction.get
        end
      elsif equip.to_AirTerminalSingleDuctVAVReheat.is_initialized
        term = equip.to_AirTerminalSingleDuctVAVReheat.get
        if term.constantMinimumAirFlowFraction.is_initialized
          mdp_term = term.constantMinimumAirFlowFraction.get
        end
        if term.fixedMinimumAirFlowRate.is_initialized
          min_zn_flow = term.fixedMinimumAirFlowRate.get
        end
      end
    end

    # Zone ventilation efficiency calculation is computed
    # on a per zone basis, the zone primary airflow is
    # adjusted to removed the zone multiplier
    v_pz /= zone.multiplier.to_f

    # For VAV Reheat terminals, min flow is greater of mdp
    # and min flow rate / design flow rate.
    mdp = mdp_term
    mdp_oa = min_zn_flow / v_pz
    if min_zn_flow > 0.0
      mdp = [mdp_term, mdp_oa].max.round(2)
    end

    # Zone minimum discharge airflow rate
    v_dz = v_pz * mdp

    # Zone discharge air fraction
    z_d = v_oz / v_dz

    # Zone ventilation effectiveness
    e_vz = 1.0 + x_s - z_d

    # Store the ventilation effectiveness
    e_vzs << e_vz

    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Zone #{zone.name} v_oz = #{v_oz.round(2)} m^3/s, v_pz = #{v_pz.round(2)} m^3/s, v_dz = #{v_dz.round(2)}, z_d = #{z_d.round(2)}.")

    # Check the ventilation effectiveness against
    # the minimum limit per PNNL and increase
    # as necessary.
    if e_vz < 0.6

      # Adjusted discharge air fraction
      z_d_adj = 1.0 + x_s - 0.6

      # Adjusted min discharge airflow rate
      v_dz_adj = v_oz / z_d_adj

      # Adjusted minimum damper position
      mdp_adj = v_dz_adj / v_pz

      # Don't allow values > 1
      if mdp_adj > 1.0
        mdp_adj = 1.0
      end

      # Zone ventilation effectiveness
      e_vz_adj = 1.0 + x_s - z_d_adj

      # Store the ventilation effectiveness
      e_vzs_adj << e_vz_adj
      # Round the minimum damper position to avoid nondeterministic results
      # at the ~13th decimal place, which can cause regression errors
      mdp_adj = mdp_adj.round(11)

      # Set the adjusted minimum damper position
      air_loop_hvac_set_minimum_damper_position(zone, mdp_adj)

      num_zones_adj += 1

      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Zone #{zone.name} has a ventilation effectiveness of #{e_vz.round(2)}.  Increasing to #{e_vz_adj.round(2)} by increasing minimum damper position from #{mdp.round(2)} to #{mdp_adj.round(2)}.")

    else
      # Store the unadjusted value
      e_vzs_adj << e_vz
    end
  end

  # Min system zone ventilation effectiveness
  e_v = e_vzs.min

  # Total system outdoor intake flow rate
  v_ot = v_ou / e_v
  v_ot_cfm = OpenStudio.convert(v_ot, 'm^3/s', 'cfm').get

  # Min system zone ventilation effectiveness
  e_v_adj = e_vzs_adj.min

  # Total system outdoor intake flow rate
  v_ot_adj = v_ou / e_v_adj
  v_ot_adj_cfm = OpenStudio.convert(v_ot_adj, 'm^3/s', 'cfm').get

  # Adjust minimum damper position if the sum of maximum
  # zone airflow are lower than the calculated system
  # outdoor air intake
  if v_ot_adj > vpz_min_sum && v_ot_adj > 0

    # Retrieve the sum of the zone maximum air flow rates
    if air_loop_hvac.model.version < OpenStudio::VersionString.new('3.6.0')
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', 'Required AirLoopHVAC method .autosizedSumAirTerminalMaxAirFlowRate is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
    elsif air_loop_hvac.autosizedSumAirTerminalMaxAirFlowRate.is_initialized
      v_max = air_loop_hvac.autosizedSumAirTerminalMaxAirFlowRate.get
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', "autosizedSumAirTerminalMaxAirFlowRate is not available for air loop #{air_loop_hvac}.")
    end

    mdp_adj = [v_ot_adj / v_max, 1].min
    air_loop_hvac.thermalZones.sort.each do |zone|
      air_loop_hvac_set_minimum_damper_position(zone, mdp_adj)
    end
  end

  # Report out the results of the multizone calculations
  if num_zones_adj > 0
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: the multizone outdoor air calculation method was applied.  A simple summation of the zone outdoor air requirements gives a value of #{v_ou_cfm.round} cfm.  Applying the multizone method gives a value of #{v_ot_cfm.round} cfm, with an original system ventilation effectiveness of #{e_v.round(2)}.  After increasing the minimum damper position in #{num_zones_adj} critical zones, the resulting requirement is #{v_ot_adj_cfm.round} cfm with a system ventilation effectiveness of #{e_v_adj.round(2)}.")
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: the multizone outdoor air calculation method was applied.  A simple summation of the zone requirements gives a value of #{v_ou_cfm.round} cfm.  However, applying the multizone method requires #{v_ot_adj_cfm.round} cfm based on the ventilation effectiveness of the system.")
  end

  # Hard-size the sizing:system
  # object with the calculated min OA flow rate
  sizing_system = air_loop_hvac.sizingSystem
  sizing_system.setDesignOutdoorAirFlowRate(v_ot_adj)
  sizing_system.setSystemOutdoorAirMethod('ZoneSum')

  return true
end
air_loop_hvac_adjust_minimum_vav_damper_positions_outpatient(air_loop_hvac) click to toggle source

For critical zones of Outpatient, if the minimum airflow rate required by the accreditation standard (AIA 2001) is significantly less than the autosized peak design airflow in any of the three climate zones (Houston, Baltimore and Burlington), the minimum airflow fraction of the terminal units is reduced to the value: “required minimum airflow rate / autosized peak design flow” Reference: <Achieving the 30% Goal: Energy and Cost Savings Analysis of ASHRAE Standard 90.1-2010> Page109-111 For implementation purpose, since it is time-consuming to perform autosizing in three climate zones, just use the results of the current climate zone

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2273
def air_loop_hvac_adjust_minimum_vav_damper_positions_outpatient(air_loop_hvac)
  air_loop_hvac.model.getSpaces.sort.each do |space|
    zone = space.thermalZone.get
    sizing_zone = zone.sizingZone
    space_area = space.floorArea
    next if sizing_zone.coolingDesignAirFlowMethod == 'DesignDay'

    if sizing_zone.coolingDesignAirFlowMethod == 'DesignDayWithLimit'
      minimum_airflow_per_zone_floor_area = sizing_zone.coolingMinimumAirFlowperZoneFloorArea
      minimum_airflow_per_zone = minimum_airflow_per_zone_floor_area * space_area
      # get the autosized maximum air flow of the VAV terminal
      zone.equipment.each do |equip|
        if equip.to_AirTerminalSingleDuctVAVReheat.is_initialized
          vav_terminal = equip.to_AirTerminalSingleDuctVAVReheat.get
          rated_maximum_flow_rate = vav_terminal.autosizedMaximumAirFlowRate.get
          # compare the VAV autosized maximum airflow with the minimum airflow rate required by the accreditation standard
          ratio = minimum_airflow_per_zone / rated_maximum_flow_rate

          # round to avoid results variances in sizing runs
          ratio = ratio.round(11)

          if ratio >= 0.95
            vav_terminal.setConstantMinimumAirFlowFraction(1)
          elsif ratio < 0.95
            vav_terminal.setConstantMinimumAirFlowFraction(ratio)
          end
        end
      end
    end
  end
  return true
end
air_loop_hvac_allowable_system_brake_horsepower(air_loop_hvac) click to toggle source

Determine the allowable fan system brake horsepower Per Table 6.5.3.1.1A

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Double] allowable fan system brake horsepower, in units of horsepower

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 491
def air_loop_hvac_allowable_system_brake_horsepower(air_loop_hvac)
  # Get design supply air flow rate (whether autosized or hard-sized)
  dsn_air_flow_m3_per_s = 0
  dsn_air_flow_cfm = 0
  if air_loop_hvac.designSupplyAirFlowRate.is_initialized
    dsn_air_flow_m3_per_s = air_loop_hvac.designSupplyAirFlowRate.get
    dsn_air_flow_cfm = OpenStudio.convert(dsn_air_flow_m3_per_s, 'm^3/s', 'cfm').get
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "* #{dsn_air_flow_cfm.round} cfm = Hard sized Design Supply Air Flow Rate.")
  elsif air_loop_hvac.autosizedDesignSupplyAirFlowRate.is_initialized
    dsn_air_flow_m3_per_s = air_loop_hvac.autosizedDesignSupplyAirFlowRate.get
    dsn_air_flow_cfm = OpenStudio.convert(dsn_air_flow_m3_per_s, 'm^3/s', 'cfm').get
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "* #{dsn_air_flow_cfm.round} cfm = Autosized Design Supply Air Flow Rate.")
  end

  # Get the fan limitation pressure drop adjustment bhp
  fan_pwr_adjustment_bhp = air_loop_hvac_fan_power_limitation_pressure_drop_adjustment_brake_horsepower(air_loop_hvac)

  # Determine the number of zones the system serves
  num_zones_served = air_loop_hvac.thermalZones.size

  # Get the supply air fan and determine whether VAV or CAV system.
  # Assume that supply air fan is fan closest to the demand outlet node.
  # The fan may be inside of a piece of unitary equipment.
  fan_pwr_limit_type = nil
  air_loop_hvac.supplyComponents.reverse.each do |comp|
    if comp.to_FanConstantVolume.is_initialized || comp.to_FanOnOff.is_initialized
      fan_pwr_limit_type = 'constant volume'
    elsif comp.to_FanVariableVolume.is_initialized
      fan_pwr_limit_type = 'variable volume'
    elsif comp.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.is_initialized
      fan = comp.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.get.supplyAirFan
      if fan.to_FanConstantVolume.is_initialized || fan.to_FanOnOff.is_initialized
        fan_pwr_limit_type = 'constant volume'
      elsif fan.to_FanVariableVolume.is_initialized
        fan_pwr_limit_type = 'variable volume'
      end
    elsif comp.to_AirLoopHVACUnitarySystem.is_initialized
      fan = comp.to_AirLoopHVACUnitarySystem.get.supplyFan.get
      if fan.to_FanConstantVolume.is_initialized || fan.to_FanOnOff.is_initialized
        fan_pwr_limit_type = 'constant volume'
      elsif fan.to_FanVariableVolume.is_initialized
        fan_pwr_limit_type = 'variable volume'
      end
    end
  end

  # For 90.1-2010, single-zone VAV systems use the
  # constant volume limitation per 6.5.3.1.1
  if template == 'ASHRAE 90.1-2010' && fan_pwr_limit_type == 'variable volume' && num_zones_served == 1
    fan_pwr_limit_type = 'constant volume'
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Using the constant volume limitation because single-zone VAV system.")
  end

  # Calculate the Allowable Fan System brake horsepower per Table G3.1.2.9
  allowable_fan_bhp = 0
  if fan_pwr_limit_type == 'constant volume'
    if dsn_air_flow_cfm > 0
      allowable_fan_bhp = dsn_air_flow_cfm * 0.00094 + fan_pwr_adjustment_bhp
    else
      allowable_fan_bhp = 0.00094
    end
  elsif fan_pwr_limit_type == 'variable volume'
    if dsn_air_flow_cfm > 0
      allowable_fan_bhp = dsn_air_flow_cfm * 0.0013 + fan_pwr_adjustment_bhp
    else
      allowable_fan_bhp = 0.0013
    end
  end
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Allowable brake horsepower = #{allowable_fan_bhp.round(2)}HP based on #{dsn_air_flow_cfm.round} cfm and #{fan_pwr_adjustment_bhp.round(2)} bhp of adjustment.")

  # Calculate and report the total area for debugging/testing
  floor_area_served_m2 = air_loop_hvac_floor_area_served(air_loop_hvac)

  if floor_area_served_m2.zero?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "AirLoopHVAC #{air_loop_hvac.name} serves zero floor area. Check that it has thermal zones attached to it, and that they have non-zero floor area'.")
    return allowable_fan_bhp
  end

  floor_area_served_ft2 = OpenStudio.convert(floor_area_served_m2, 'm^2', 'ft^2').get
  cfm_per_ft2 = dsn_air_flow_cfm / floor_area_served_ft2

  if allowable_fan_bhp.zero?
    cfm_per_hp = 0
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "AirLoopHVAC #{air_loop_hvac.name} has zero allowable fan bhp, probably due to zero design air flow cfm'.")
  else
    cfm_per_hp = dsn_air_flow_cfm / allowable_fan_bhp
  end
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: area served = #{floor_area_served_ft2.round} ft^2.")
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: flow per area = #{cfm_per_ft2.round} cfm/ft^2.")
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: flow per hp = #{cfm_per_hp.round} cfm/hp.")

  return allowable_fan_bhp
end
air_loop_hvac_apply_baseline_fan_pressure_rise(air_loop_hvac) click to toggle source

Set the fan pressure rises that will result in the system hitting the baseline allowable fan power

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 672
def air_loop_hvac_apply_baseline_fan_pressure_rise(air_loop_hvac)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name}-Setting #{template} baseline fan power.")

  # Get the total system bhp from the proposed system, including terminal fans
  proposed_sys_bhp = air_loop_hvac_system_fan_brake_horsepower(air_loop_hvac, true)

  # Get the allowable fan brake horsepower
  allowable_fan_bhp = air_loop_hvac_allowable_system_brake_horsepower(air_loop_hvac)

  # Get the fan power limitation from proposed system
  fan_pwr_adjustment_bhp = air_loop_hvac_fan_power_limitation_pressure_drop_adjustment_brake_horsepower(air_loop_hvac)

  # Subtract the fan power adjustment
  allowable_fan_bhp -= fan_pwr_adjustment_bhp

  # Get all fans
  fans = air_loop_hvac_supply_return_exhaust_relief_fans(air_loop_hvac)

  # @todo improve description
  # Loop through the fans, changing the pressure rise
  # until the fan bhp is the same percentage of the baseline allowable bhp
  # as it was on the proposed system.
  fans.each do |fan|
    # @todo Yixing Check the model of the Fan Coil Unit
    next if fan.name.to_s.include?('Fan Coil fan')
    next if fan.name.to_s.include?('UnitHeater Fan')

    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', fan.name.to_s)

    # Get the bhp of the fan on the proposed system
    proposed_fan_bhp = fan_brake_horsepower(fan)

    # Get the bhp of the fan on the proposed system
    proposed_fan_bhp_frac = proposed_fan_bhp / proposed_sys_bhp

    # Determine the target bhp of the fan on the baseline system
    baseline_fan_bhp = proposed_fan_bhp_frac * allowable_fan_bhp
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "* #{baseline_fan_bhp.round(1)} bhp = Baseline fan brake horsepower.")

    # Set the baseline impeller eff of the fan,
    # preserving the proposed motor eff.
    baseline_impeller_eff = fan_baseline_impeller_efficiency(fan)
    fan_change_impeller_efficiency(fan, baseline_impeller_eff)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "* #{(baseline_impeller_eff * 100).round(1)}% = Baseline fan impeller efficiency.")

    # Set the baseline motor efficiency for the specified bhp
    baseline_motor_eff = fan.standardMinimumMotorEfficiency(standards, allowable_fan_bhp)
    fan_change_motor_efficiency(fan, baseline_motor_eff)

    # Get design supply air flow rate (whether autosized or hard-sized)
    dsn_air_flow_m3_per_s = 0
    if fan.designSupplyAirFlowRate.is_initialized
      dsn_air_flow_m3_per_s = fan.designSupplyAirFlowRate.get
      dsn_air_flow_cfm = OpenStudio.convert(dsn_air_flow_m3_per_s, 'm^3/s', 'cfm').get
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "* #{dsn_air_flow_cfm.round} cfm = User entered Design Supply Air Flow Rate.")
    elsif fan.autosizedDesignSupplyAirFlowRate.is_initialized
      dsn_air_flow_m3_per_s = fan.autosizedDesignSupplyAirFlowRate.get
      dsn_air_flow_cfm = OpenStudio.convert(dsn_air_flow_m3_per_s, 'm^3/s', 'cfm').get
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "* #{dsn_air_flow_cfm.round} cfm = Autosized Design Supply Air Flow Rate.")
    end

    # Determine the fan pressure rise that will result in the target bhp
    # pressure_rise_pa = fan_bhp*746 / fan_motor_eff*fan_total_eff / dsn_air_flow_m3_per_s
    baseline_pressure_rise_pa = baseline_fan_bhp * 746 / fan.motorEfficiency * fan.fanEfficiency / dsn_air_flow_m3_per_s
    baseline_pressure_rise_in_wc = OpenStudio.convert(fan_pressure_rise_pa, 'Pa', 'inH_{2}O').get
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "* #{fan_pressure_rise_in_wc.round(2)} in w.c. = Pressure drop to achieve allowable fan power.")

    # Calculate the bhp of the fan to make sure it matches
    calc_bhp = fan_brake_horsepower(fan)
    if ((calc_bhp - baseline_fan_bhp) / baseline_fan_bhp).abs > 0.02
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', "#{fan.name} baseline fan bhp supposed to be #{baseline_fan_bhp}, but is #{calc_bhp}.")
    end
  end

  # Calculate the total bhp of the system to make sure it matches the goal
  calc_sys_bhp = air_loop_hvac_system_fan_brake_horsepower(air_loop_hvac, false)
  return true unless ((calc_sys_bhp - allowable_fan_bhp) / allowable_fan_bhp).abs > 0.02

  OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name} baseline system bhp supposed to be #{allowable_fan_bhp}, but is #{calc_sys_bhp}.")
  return false
end
air_loop_hvac_apply_economizer_integration(air_loop_hvac, climate_zone) click to toggle source

For systems required to have an economizer, set the economizer to integrated on non-integrated per the standard. @note this method assumes you previously checked that an economizer is required at all via economizer_required?

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1145
def air_loop_hvac_apply_economizer_integration(air_loop_hvac, climate_zone)
  # Determine if an integrated economizer is required
  integrated_economizer_required = air_loop_hvac_integrated_economizer_required?(air_loop_hvac, climate_zone)

  # Get the OA system and OA controller
  oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem

  return false unless oa_sys.is_initialized

  oa_sys = oa_sys.get
  oa_control = oa_sys.getControllerOutdoorAir
  # Apply integrated or non-integrated economizer
  if integrated_economizer_required
    oa_control.setLockoutType('LockoutWithHeating')
  else
    # If the airloop include hyrdronic cooling coils,
    # prevent economizer from operating at and above SAT,
    # similar to a non-integrated economizer. This is done
    # because LockoutWithCompressor doesn't work with hydronic
    # coils
    if air_loop_hvac_include_hydronic_cooling_coil?(air_loop_hvac)
      oa_control.setLockoutType('LockoutWithHeating')
      oa_control.setEconomizerMaximumLimitDryBulbTemperature(standard_design_sizing_temperatures['clg_dsgn_sup_air_temp_c'])
    else
      oa_control.setLockoutType('LockoutWithCompressor')
    end
  end

  return true
end
air_loop_hvac_apply_economizer_limits(air_loop_hvac, climate_zone) click to toggle source

Set the economizer limits per the standard. Limits are based on the economizer type currently specified in the ControllerOutdoorAir object on this air loop.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1029
def air_loop_hvac_apply_economizer_limits(air_loop_hvac, climate_zone)
  # EnergyPlus economizer types
  # 'NoEconomizer'
  # 'FixedDryBulb'
  # 'FixedEnthalpy'
  # 'DifferentialDryBulb'
  # 'DifferentialEnthalpy'
  # 'FixedDewPointAndDryBulb'
  # 'ElectronicEnthalpy'
  # 'DifferentialDryBulbAndEnthalpy'

  # Get the OA system and OA controller
  oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
  return false unless oa_sys.is_initialized

  oa_sys = oa_sys.get
  oa_control = oa_sys.getControllerOutdoorAir
  economizer_type = oa_control.getEconomizerControlType

  # Return false if no economizer is present
  if economizer_type == 'NoEconomizer'
    return false
  end

  # Reset the limits
  oa_control.resetEconomizerMaximumLimitDryBulbTemperature
  oa_control.resetEconomizerMaximumLimitEnthalpy
  oa_control.resetEconomizerMaximumLimitDewpointTemperature
  oa_control.resetEconomizerMinimumLimitDryBulbTemperature

  # Determine the limits
  drybulb_limit_f, enthalpy_limit_btu_per_lb, dewpoint_limit_f = air_loop_hvac_economizer_limits(air_loop_hvac, climate_zone)

  # Do nothing if no limits were specified
  if drybulb_limit_f.nil? && enthalpy_limit_btu_per_lb.nil? && dewpoint_limit_f.nil?
    return false
  end

  # Set the limits
  case economizer_type
  when 'FixedDryBulb'
    if drybulb_limit_f
      drybulb_limit_c = OpenStudio.convert(drybulb_limit_f, 'F', 'C').get
      oa_control.setEconomizerMaximumLimitDryBulbTemperature(drybulb_limit_c)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Economizer type = #{economizer_type}, dry bulb limit = #{drybulb_limit_f}F")
    end
    # Some templates include fixed enthalpy limits in addition to fixed dry bulb limits
    if enthalpy_limit_btu_per_lb
      enthalpy_limit_j_per_kg = OpenStudio.convert(enthalpy_limit_btu_per_lb, 'Btu/lb', 'J/kg').get
      oa_control.setEconomizerMaximumLimitEnthalpy(enthalpy_limit_j_per_kg)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: additional economizer enthalpy limit = #{enthalpy_limit_btu_per_lb}Btu/lb")
    end
  when 'FixedEnthalpy'
    if enthalpy_limit_btu_per_lb
      enthalpy_limit_j_per_kg = OpenStudio.convert(enthalpy_limit_btu_per_lb, 'Btu/lb', 'J/kg').get
      oa_control.setEconomizerMaximumLimitEnthalpy(enthalpy_limit_j_per_kg)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Economizer type = #{economizer_type}, enthalpy limit = #{enthalpy_limit_btu_per_lb}Btu/lb")
    end
  when 'FixedDewPointAndDryBulb'
    if drybulb_limit_f && dewpoint_limit_f
      drybulb_limit_c = OpenStudio.convert(drybulb_limit_f, 'F', 'C').get
      dewpoint_limit_c = OpenStudio.convert(dewpoint_limit_f, 'F', 'C').get
      oa_control.setEconomizerMaximumLimitDryBulbTemperature(drybulb_limit_c)
      oa_control.setEconomizerMaximumLimitDewpointTemperature(dewpoint_limit_c)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Economizer type = #{economizer_type}, dry bulb limit = #{drybulb_limit_f}F, dew-point limit = #{dewpoint_limit_f}F")
    end
  end

  return true
end
air_loop_hvac_apply_energy_recovery_ventilator(air_loop_hvac, climate_zone) click to toggle source

Add an ERV to this airloop

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if required, false if not @todo Add exception logic for systems serving parking garage, warehouse, or multifamily

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1803
def air_loop_hvac_apply_energy_recovery_ventilator(air_loop_hvac, climate_zone)
  # Get the OA system
  oa_system = nil
  if air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized
    oa_system = air_loop_hvac.airLoopHVACOutdoorAirSystem.get
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, ERV cannot be added because the system has no OA intake.")
    return false
  end

  # Get the existing ERV or create an ERV and add it to the OA system
  erv = nil
  air_loop_hvac.supplyComponents.each do |supply_comp|
    if supply_comp.to_HeatExchangerAirToAirSensibleAndLatent.is_initialized
      erv = supply_comp.to_HeatExchangerAirToAirSensibleAndLatent.get
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, adjusting properties for existing ERV #{erv.name} instead of adding another one.")
    end
  end
  if erv.nil?
    erv = OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent.new(air_loop_hvac.model)
    erv.addToNode(oa_system.outboardOANode.get)
  end

  # Determine whether to use an ERV and HRV and heat exchanger style
  erv_type = air_loop_hvac_energy_recovery_ventilator_type(air_loop_hvac, climate_zone)
  heat_exchanger_type = air_loop_hvac_energy_recovery_ventilator_heat_exchanger_type(air_loop_hvac)
  erv.setName("#{air_loop_hvac.name} #{erv_type}")
  erv.setHeatExchangerType(heat_exchanger_type)

  # apply heat exchanger efficiencies
  air_loop_hvac_apply_energy_recovery_ventilator_efficiency(erv, erv_type: erv_type, heat_exchanger_type: heat_exchanger_type)

  # Apply the prototype heat exchanger power assumptions for rotary style heat exchangers
  heat_exchanger_air_to_air_sensible_and_latent_apply_prototype_nominal_electric_power(erv)

  # add economizer lockout
  erv.setSupplyAirOutletTemperatureControl(true)
  erv.setEconomizerLockout(true)

  # add defrost
  erv.setFrostControlType('ExhaustOnly')
  erv.setThresholdTemperature(-23.3) # -10F
  erv.setInitialDefrostTimeFraction(0.167)
  erv.setRateofDefrostTimeFractionIncrease(1.44)

  # Add a setpoint manager OA pretreat to control the ERV
  spm_oa_pretreat = OpenStudio::Model::SetpointManagerOutdoorAirPretreat.new(air_loop_hvac.model)
  spm_oa_pretreat.setMinimumSetpointTemperature(-99.0)
  spm_oa_pretreat.setMaximumSetpointTemperature(99.0)
  spm_oa_pretreat.setMinimumSetpointHumidityRatio(0.00001)
  spm_oa_pretreat.setMaximumSetpointHumidityRatio(1.0)
  # Reference setpoint node and mixed air stream node are outlet node of the OA system
  mixed_air_node = oa_system.mixedAirModelObject.get.to_Node.get
  spm_oa_pretreat.setReferenceSetpointNode(mixed_air_node)
  spm_oa_pretreat.setMixedAirStreamNode(mixed_air_node)
  # Outdoor air node is the outboard OA node of the OA system
  spm_oa_pretreat.setOutdoorAirStreamNode(oa_system.outboardOANode.get)
  # Return air node is the inlet node of the OA system
  return_air_node = oa_system.returnAirModelObject.get.to_Node.get
  spm_oa_pretreat.setReturnAirStreamNode(return_air_node)
  # Attach to the outlet of the ERV
  erv_outlet = erv.primaryAirOutletModelObject.get.to_Node.get
  spm_oa_pretreat.addToNode(erv_outlet)

  # Determine if the system is a DOAS based on whether there is 100% OA in heating and cooling sizing.
  is_doas = false
  sizing_system = air_loop_hvac.sizingSystem
  if sizing_system.allOutdoorAirinCooling && sizing_system.allOutdoorAirinHeating
    is_doas = true
  end

  # Set the bypass control type
  # If DOAS system, BypassWhenWithinEconomizerLimits
  # to disable ERV during economizing.
  # Otherwise, BypassWhenOAFlowGreaterThanMinimum
  # to disable ERV during economizing and when OA
  # is also greater than minimum.
  bypass_ctrl_type = if is_doas
                       'BypassWhenWithinEconomizerLimits'
                     else
                       'BypassWhenOAFlowGreaterThanMinimum'
                     end
  oa_system.getControllerOutdoorAir.setHeatRecoveryBypassControlType(bypass_ctrl_type)

  return true
end
air_loop_hvac_apply_energy_recovery_ventilator_efficiency(erv, erv_type: 'ERV', heat_exchanger_type: 'Rotary') click to toggle source

Apply efficiency values to the erv

@param erv [OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent] erv to apply efficiency values @param erv_type [String] erv type ERV or HRV @param heat_exchanger_type [String] heat exchanger type Rotary or Plate @return [OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent] erv to apply efficiency values

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1896
def air_loop_hvac_apply_energy_recovery_ventilator_efficiency(erv, erv_type: 'ERV', heat_exchanger_type: 'Rotary')
  erv.setSensibleEffectivenessat100HeatingAirFlow(0.7)
  erv.setLatentEffectivenessat100HeatingAirFlow(0.6)
  erv.setSensibleEffectivenessat75HeatingAirFlow(0.7)
  erv.setLatentEffectivenessat75HeatingAirFlow(0.6)
  erv.setSensibleEffectivenessat100CoolingAirFlow(0.75)
  erv.setLatentEffectivenessat100CoolingAirFlow(0.6)
  erv.setSensibleEffectivenessat75CoolingAirFlow(0.75)
  erv.setLatentEffectivenessat75CoolingAirFlow(0.6)
  return erv
end
air_loop_hvac_apply_maximum_reheat_temperature(air_loop_hvac, max_reheat_c) click to toggle source

Sets the maximum reheat temperature to the specified value for all reheat terminals (of any type) on the loop.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param max_reheat_c [Double] the maximum reheat temperature, in degrees Celsius @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3554
def air_loop_hvac_apply_maximum_reheat_temperature(air_loop_hvac, max_reheat_c)
  air_loop_hvac.demandComponents.each do |sc|
    if sc.to_AirTerminalSingleDuctConstantVolumeReheat.is_initialized
      term = sc.to_AirTerminalSingleDuctConstantVolumeReheat.get
      term.setMaximumReheatAirTemperature(max_reheat_c)
    elsif sc.to_AirTerminalSingleDuctParallelPIUReheat.is_initialized
      # No control option available
    elsif sc.to_AirTerminalSingleDuctSeriesPIUReheat.is_initialized
      # No control option available
    elsif sc.to_AirTerminalSingleDuctVAVHeatAndCoolReheat.is_initialized
      term = sc.to_AirTerminalSingleDuctVAVHeatAndCoolReheat.get
      term.setMaximumReheatAirTemperature(max_reheat_c)
    elsif sc.to_AirTerminalSingleDuctVAVReheat.is_initialized
      term = sc.to_AirTerminalSingleDuctVAVReheat.get
      term.setMaximumReheatAirTemperature(max_reheat_c)
    end
  end

  max_reheat_f = OpenStudio.convert(max_reheat_c, 'C', 'F').get
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: reheat terminal maximum set to #{max_reheat_f.round} F.")

  return true
end
air_loop_hvac_apply_minimum_vav_damper_positions(air_loop_hvac, has_ddc = true) click to toggle source

Set the minimum VAV damper positions.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param has_ddc [Boolean] if true, will assume that there is DDC control of vav terminals.

If false, assumes otherwise.

@return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1981
def air_loop_hvac_apply_minimum_vav_damper_positions(air_loop_hvac, has_ddc = true)
  air_loop_hvac.thermalZones.each do |zone|
    zone.equipment.each do |equip|
      if equip.to_AirTerminalSingleDuctVAVReheat.is_initialized
        zone_oa = OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate(zone)
        vav_terminal = equip.to_AirTerminalSingleDuctVAVReheat.get
        air_terminal_single_duct_vav_reheat_apply_minimum_damper_position(vav_terminal, zone_oa, has_ddc)
      end
    end
  end

  return true
end
air_loop_hvac_apply_multizone_vav_outdoor_air_sizing(air_loop_hvac) click to toggle source

Apply multizone vav outdoor air method and adjust multizone VAV damper positions to achieve a system minimum ventilation effectiveness of 0.6 per PNNL. Hard-size the resulting min OA into the sizing:system object.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop return [Boolean] returns true if successful, false if not @todo move building-type-specific code to Prototype classes

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 11
def air_loop_hvac_apply_multizone_vav_outdoor_air_sizing(air_loop_hvac)
  # First time adjustment:
  # Only applies to multi-zone vav systems
  # exclusion: for Outpatient: (1) both AHU1 and AHU2 in 'DOE Ref Pre-1980' and 'DOE Ref 1980-2004'
  # (2) AHU1 in 2004-2019
  # @todo refactor: move building-type-specific code to Prototype classes
  if air_loop_hvac_multizone_vav_system?(air_loop_hvac) && !(air_loop_hvac.name.to_s.include? 'Outpatient F1')
    air_loop_hvac_adjust_minimum_vav_damper_positions(air_loop_hvac)
  end

  return true
end
air_loop_hvac_apply_prm_baseline_controls(air_loop_hvac, climate_zone) click to toggle source

Apply all PRM baseline required controls to the airloop. Only applies those controls that differ from the normal prescriptive controls, which are added via air_loop_hvac_apply_standard_controls(air_loop_hvac, climate_zone)

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 194
def air_loop_hvac_apply_prm_baseline_controls(air_loop_hvac, climate_zone)
  # Economizers
  if air_loop_hvac_prm_baseline_economizer_required?(air_loop_hvac, climate_zone)
    air_loop_hvac_apply_prm_baseline_economizer(air_loop_hvac, climate_zone)
  else
    # Make sure if economizer is not required then the OA controller should have No Economizer
    oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
    if oa_sys.is_initialized
      oa_sys.get.getControllerOutdoorAir.setEconomizerControlType('NoEconomizer')
    end
  end

  # Multizone VAV Systems
  if air_loop_hvac_multizone_vav_system?(air_loop_hvac)

    # VSD no Static Pressure Reset on all VAV systems
    # per G3.1.3.15
    air_loop_hvac_supply_return_exhaust_relief_fans(air_loop_hvac).each do |fan|
      if fan.to_FanVariableVolume.is_initialized
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Setting fan part load curve per G3.1.3.15.")
        fan_variable_volume_set_control_type(fan, 'Multi Zone VAV with VSD and Fixed SP Setpoint')
      end
    end

    # SAT Reset
    # G3.1.3.12 SAT reset required for all Multizone VAV systems,
    # even if not required by prescriptive section.
    air_loop_hvac_enable_supply_air_temperature_reset_warmest_zone(air_loop_hvac)

  end

  # Unoccupied shutdown
  occ_threshold = air_loop_hvac_unoccupied_threshold
  air_loop_hvac_enable_unoccupied_fan_shutoff(air_loop_hvac, occ_threshold)

  return true
end
air_loop_hvac_apply_prm_baseline_economizer(air_loop_hvac, climate_zone) click to toggle source

Apply the PRM economizer type and set temperature limits

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1437
def air_loop_hvac_apply_prm_baseline_economizer(air_loop_hvac, climate_zone)
  # EnergyPlus economizer types
  # 'NoEconomizer'
  # 'FixedDryBulb'
  # 'FixedEnthalpy'
  # 'DifferentialDryBulb'
  # 'DifferentialEnthalpy'
  # 'FixedDewPointAndDryBulb'
  # 'ElectronicEnthalpy'
  # 'DifferentialDryBulbAndEnthalpy'

  # Determine the type and limits
  economizer_type, drybulb_limit_f, enthalpy_limit_btu_per_lb, dewpoint_limit_f = air_loop_hvac_prm_economizer_type_and_limits(air_loop_hvac, climate_zone)

  # Get the OA system and OA controller
  oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
  return false unless oa_sys.is_initialized

  oa_sys = oa_sys.get
  oa_control = oa_sys.getControllerOutdoorAir

  # Set the economizer type
  oa_control.setEconomizerControlType(economizer_type)

  # Reset the limits
  oa_control.resetEconomizerMaximumLimitDryBulbTemperature
  oa_control.resetEconomizerMaximumLimitEnthalpy
  oa_control.resetEconomizerMaximumLimitDewpointTemperature
  oa_control.resetEconomizerMinimumLimitDryBulbTemperature

  # Set the limits
  case economizer_type
  when 'FixedDryBulb'
    if drybulb_limit_f
      drybulb_limit_c = OpenStudio.convert(drybulb_limit_f, 'F', 'C').get
      oa_control.setEconomizerMaximumLimitDryBulbTemperature(drybulb_limit_c)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Economizer type = #{economizer_type}, dry bulb limit = #{drybulb_limit_f}F")
    end
  when 'FixedEnthalpy'
    if enthalpy_limit_btu_per_lb
      enthalpy_limit_j_per_kg = OpenStudio.convert(enthalpy_limit_btu_per_lb, 'Btu/lb', 'J/kg').get
      oa_control.setEconomizerMaximumLimitEnthalpy(enthalpy_limit_j_per_kg)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Economizer type = #{economizer_type}, enthalpy limit = #{enthalpy_limit_btu_per_lb}Btu/lb")
    end
  when 'FixedDewPointAndDryBulb'
    if drybulb_limit_f && dewpoint_limit_f
      drybulb_limit_c = OpenStudio.convert(drybulb_limit_f, 'F', 'C').get
      dewpoint_limit_c = OpenStudio.convert(dewpoint_limit_f, 'F', 'C').get
      oa_control.setEconomizerMaximumLimitDryBulbTemperature(drybulb_limit_c)
      oa_control.setEconomizerMaximumLimitDewpointTemperature(dewpoint_limit_c)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Economizer type = #{economizer_type}, dry bulb limit = #{drybulb_limit_f}F, dew-point limit = #{dewpoint_limit_f}F")
    end
  end

  return true
end
air_loop_hvac_apply_prm_baseline_fan_power(air_loop_hvac) click to toggle source

Calculate and apply the performance rating method baseline fan power to this air loop. Fan motor efficiency will be set, and then fan pressure rise adjusted so that the fan power is the maximum allowable. Also adjusts the fan power and flow rates of any parallel PIU terminals on the system. @todo Figure out how to split fan power between multiple fans

if the proposed model had multiple fans (supply, return, exhaust, etc.)

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop return [Boolean] true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 391
def air_loop_hvac_apply_prm_baseline_fan_power(air_loop_hvac)
  # Main AHU fans

  # Calculate the allowable fan motor bhp
  # for the entire airloop.
  allowable_fan_bhp = air_loop_hvac_allowable_system_brake_horsepower(air_loop_hvac)

  # Divide the allowable power evenly between the fans
  # on this airloop.
  all_fans = air_loop_hvac_supply_return_exhaust_relief_fans(air_loop_hvac)
  allowable_fan_bhp /= all_fans.size

  # Set the motor efficiencies
  # for all fans based on the calculated
  # allowed brake hp.  Then calculate the allowable
  # fan power for each fan and adjust
  # the fan pressure rise accordingly
  all_fans.each do |fan|
    fan_apply_standard_minimum_motor_efficiency(fan, allowable_fan_bhp)
    allowable_power_w = allowable_fan_bhp * 746 / fan.motorEfficiency
    fan_adjust_pressure_rise_to_meet_fan_power(fan, allowable_power_w)
  end

  # Fan powered terminal fans

  # Adjust each terminal fan
  air_loop_hvac.demandComponents.each do |dc|
    next if dc.to_AirTerminalSingleDuctParallelPIUReheat.empty?

    pfp_term = dc.to_AirTerminalSingleDuctParallelPIUReheat.get
    air_terminal_single_duct_parallel_piu_reheat_apply_prm_baseline_fan_power(pfp_term)
  end

  return true
end
air_loop_hvac_apply_prm_sizing_temperatures(air_loop_hvac) click to toggle source

Set the system sizing properties based on the zone sizing information

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3582
def air_loop_hvac_apply_prm_sizing_temperatures(air_loop_hvac)
  # Get the design heating and cooling SAT information
  # for all zones served by the system.
  htg_setpts_c = []
  clg_setpts_c = []
  air_loop_hvac.thermalZones.each do |zone|
    sizing_zone = zone.sizingZone
    htg_setpts_c << sizing_zone.zoneHeatingDesignSupplyAirTemperature
    clg_setpts_c << sizing_zone.zoneCoolingDesignSupplyAirTemperature
  end

  # Cooling SAT set to minimum zone cooling design SAT
  clg_sat_c = clg_setpts_c.min

  # If the system has terminal reheat,
  # heating SAT is set to the same value as cooling SAT
  # and the terminals are expected to do the heating.
  # If not, heating SAT set to maximum zone heating design SAT.
  has_term_rht = air_loop_hvac_terminal_reheat?(air_loop_hvac)
  htg_sat_c = if has_term_rht
                clg_sat_c
              else
                htg_setpts_c.max
              end

  # Set the central SAT values
  sizing_system = air_loop_hvac.sizingSystem
  sizing_system.setCentralCoolingDesignSupplyAirTemperature(clg_sat_c)
  sizing_system.setCentralHeatingDesignSupplyAirTemperature(htg_sat_c)

  clg_sat_f = OpenStudio.convert(clg_sat_c, 'C', 'F').get
  htg_sat_f = OpenStudio.convert(htg_sat_c, 'C', 'F').get
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: central heating SAT set to #{htg_sat_f.round} F, cooling SAT set to #{clg_sat_f.round} F.")

  # If it's a terminal reheat system, set the reheat terminal setpoints too
  if has_term_rht
    rht_c = htg_setpts_c.max
    air_loop_hvac_apply_maximum_reheat_temperature(air_loop_hvac, rht_c)
  end

  return true
end
air_loop_hvac_apply_single_zone_controls(air_loop_hvac, climate_zone) click to toggle source

Generate the EMS used to implement the economizer and staging controls for packaged single zone units.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2914
  def air_loop_hvac_apply_single_zone_controls(air_loop_hvac, climate_zone)
    # These controls only apply to systems with DX cooling
    unless air_loop_hvac_dx_cooling?(air_loop_hvac)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Single zone controls not applicable because no DX cooling.")
      return true
    end

    # Number of stages is determined by the template
    num_stages = air_loop_hvac_single_zone_controls_num_stages(air_loop_hvac, climate_zone)

    # If zero stages, no special control is required
    if num_stages.zero?
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: No special economizer controls were modeled.")
      return true
    end

    # Fan control program only used for systems with two-stage DX coils
    fan_control = if air_loop_hvac_multi_stage_dx_cooling?(air_loop_hvac)
                    true
                  else
                    false
                  end

    # Scrub special characters from the system name
    sn = air_loop_hvac.name.get.to_s
    snc = sn.gsub(/\W/, '').delete('_')
    # If the name starts with a number, prepend with a letter
    if snc[0] =~ /[0-9]/
      snc = "SYS#{snc}"
    end

    # Get the zone name
    zone = air_loop_hvac.thermalZones[0]
    zone_name = zone.name.get.to_s
    zn_name_clean = zone_name.gsub(/\W/, '_')

    # Zone air node
    zone_air_node = zone.zoneAirNode

    # Get the OA system and OA controller
    oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
    return false unless oa_sys.is_initialized

    oa_sys = oa_sys.get
    oa_control = oa_sys.getControllerOutdoorAir
    oa_node = oa_sys.outboardOANode.get

    # Get the name of the min oa schedule
    min_oa_sch = if oa_control.minimumOutdoorAirSchedule.is_initialized
                   oa_control.minimumOutdoorAirSchedule.get
                 else
                   air_loop_hvac.model.alwaysOnDiscreteSchedule
                 end

    # Create an economizer maximum OA fraction schedule with
    # a maximum of 70% to reflect damper leakage per PNNL
    max_oa_sch = set_maximum_fraction_outdoor_air_schedule(air_loop_hvac, oa_control, snc) unless air_loop_hvac_has_simple_transfer_air?(air_loop_hvac)

    # Get the supply fan
    if air_loop_hvac.supplyFan.empty?
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: No supply fan found, cannot apply DX fan/economizer control.")
      return false
    end
    fan = air_loop_hvac.supplyFan.get

    # Supply outlet node
    sup_out_node = air_loop_hvac.supplyOutletNode

    # DX Cooling Coil
    dx_coil = nil
    air_loop_hvac.supplyComponents.each do |equip|
      if equip.to_CoilCoolingDXSingleSpeed.is_initialized
        dx_coil = equip.to_CoilCoolingDXSingleSpeed.get
      elsif equip.to_CoilCoolingDXTwoSpeed.is_initialized
        dx_coil = equip.to_CoilCoolingDXTwoSpeed.get
      end
    end
    if dx_coil.nil?
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: No DX cooling coil found, cannot apply DX fan/economizer control.")
      return false
    end

    # Heating Coil
    htg_coil = nil
    air_loop_hvac.supplyComponents.each do |equip|
      if equip.to_CoilHeatingGas.is_initialized
        htg_coil = equip.to_CoilHeatingGas.get
      elsif equip.to_CoilHeatingElectric.is_initialized
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: electric heating coil was found, cannot apply DX fan/economizer control.")
        return false
      elsif equip.to_CoilHeatingWater.is_initialized
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: hot water heating coil was found found, cannot apply DX fan/economizer control.")
        return false
      end
    end
    if htg_coil.nil?
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: No heating coil found, cannot apply DX fan/economizer control.")
      return false
    end

    ### EMS shared by both programs ###
    # Sensors
    oat_db_c_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'Site Outdoor Air Drybulb Temperature')
    oat_db_c_sen.setName('OATF')
    oat_db_c_sen.setKeyName('Environment')

    oat_wb_c_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'Site Outdoor Air Wetbulb Temperature')
    oat_wb_c_sen.setName('OAWBC')
    oat_wb_c_sen.setKeyName('Environment')

    oa_sch_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'Schedule Value')
    oa_sch_sen.setName("#{snc}OASch")
    oa_sch_sen.setKeyName(min_oa_sch.handle.to_s)

    oa_flow_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'System Node Mass Flow Rate')
    oa_flow_sen.setName("#{snc}OAFlowMass")
    oa_flow_sen.setKeyName(oa_node.handle.to_s)

    dat_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'System Node Setpoint Temperature')
    dat_sen.setName("#{snc}DATRqd")
    dat_sen.setKeyName(sup_out_node.handle.to_s)

    # Internal Variables
    oa_flow_var = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(air_loop_hvac.model, 'Outdoor Air Controller Minimum Mass Flow Rate')
    oa_flow_var.setName("#{snc}OADesignMass")
    oa_flow_var.setInternalDataIndexKeyName(oa_control.handle.to_s)

    # Global Variables
    gvar = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(air_loop_hvac.model, "#{snc}NumberofStages")

    # Programs
    num_stg_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(air_loop_hvac.model)
    num_stg_prg.setName("#{snc}SetNumberofStages")
    num_stg_prg_body = <<-EMS
      SET #{snc}NumberofStages = #{num_stages}
    EMS
    num_stg_prg.setBody(num_stg_prg_body)

    # Program Calling Managers
    setup_mgr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(air_loop_hvac.model)
    setup_mgr.setName("#{snc}SetNumberofStagesCallingManager")
    setup_mgr.setCallingPoint('BeginNewEnvironment')
    setup_mgr.addProgram(num_stg_prg)

    ### Fan Control ###
    if fan_control

      ### Economizer Control ###
      # Actuators
      econ_eff_act = OpenStudio::Model::EnergyManagementSystemActuator.new(max_oa_sch, 'Schedule:Year', 'Schedule Value')
      econ_eff_act.setName("#{snc}TimestepEconEff")

      # Programs
      econ_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(air_loop_hvac.model)
      econ_prg.setName("#{snc}EconomizerCTRLProg")
      econ_prg_body = <<-EMS
        SET #{econ_eff_act.handle} = 0.7
        SET MaxE = 0.7
        SET #{dat_sen.handle} = (#{dat_sen.handle}*1.8)+32
        SET OATF = (#{oat_db_c_sen.handle}*1.8)+32
        SET OAwbF = (#{oat_wb_c_sen.handle}*1.8)+32
        IF #{oa_flow_sen.handle} > (#{oa_flow_var.handle}*#{oa_sch_sen.handle})
          SET EconoActive = 1
        ELSE
          SET EconoActive = 0
        ENDIF
        SET dTNeeded = 75-#{dat_sen.handle}
        SET CoolDesdT = ((98*0.15)+(75*(1-0.15)))-55
        SET CoolLoad = dTNeeded/ CoolDesdT
        IF CoolLoad > 1
          SET CoolLoad = 1
        ELSEIF CoolLoad < 0
          SET CoolLoad = 0
        ENDIF
        IF EconoActive == 1
          SET Stage = #{snc}NumberofStages
          IF Stage == 2
            IF CoolLoad < 0.6
              SET #{econ_eff_act.handle} = MaxE
            ELSE
              SET ECOEff = 0-2.18919863612305
              SET ECOEff = ECOEff+(0-0.674461284910428*CoolLoad)
              SET ECOEff = ECOEff+(0.000459106275872404*(OATF^2))
              SET ECOEff = ECOEff+(0-0.00000484778537945252*(OATF^3))
              SET ECOEff = ECOEff+(0.182915713033586*OAwbF)
              SET ECOEff = ECOEff+(0-0.00382838660261133*(OAwbF^2))
              SET ECOEff = ECOEff+(0.0000255567460240583*(OAwbF^3))
              SET #{econ_eff_act.handle} = ECOEff
            ENDIF
          ELSE
            SET ECOEff = 2.36337942464462
            SET ECOEff = ECOEff+(0-0.409939515512619*CoolLoad)
            SET ECOEff = ECOEff+(0-0.0565205596792225*OAwbF)
            SET ECOEff = ECOEff+(0-0.0000632612294169389*(OATF^2))
            SET #{econ_eff_act.handle} = ECOEff+(0.000571724868775081*(OAwbF^2))
          ENDIF
          IF #{econ_eff_act.handle} > MaxE
            SET #{econ_eff_act.handle} = MaxE
          ELSEIF #{econ_eff_act.handle} < (#{oa_flow_var.handle}*#{oa_sch_sen.handle})
            SET #{econ_eff_act.handle} = (#{oa_flow_var.handle}*#{oa_sch_sen.handle})
          ENDIF
        ENDIF
      EMS
      econ_prg.setBody(econ_prg_body)

      # Program Calling Managers
      econ_mgr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(air_loop_hvac.model)
      econ_mgr.setName("#{snc}EcoManager")
      econ_mgr.setCallingPoint('InsideHVACSystemIterationLoop')
      econ_mgr.addProgram(econ_prg)

      # Sensors
      zn_temp_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'System Node Temperature')
      zn_temp_sen.setName("#{zn_name_clean}Temp")
      zn_temp_sen.setKeyName(zone_air_node.handle.to_s)

      htg_rtf_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'Heating Coil Runtime Fraction')
      htg_rtf_sen.setName("#{snc}HeatingRTF")
      htg_rtf_sen.setKeyName(htg_coil.handle.to_s)

      clg_rtf_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'Cooling Coil Runtime Fraction')
      clg_rtf_sen.setName("#{snc}RTF")
      clg_rtf_sen.setKeyName(dx_coil.handle.to_s)

      spd_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'Coil System Compressor Speed Ratio')
      spd_sen.setName("#{snc}SpeedRatio")
      spd_sen.setKeyName("#{dx_coil.handle} CoilSystem")

      # Internal Variables
      fan_pres_var = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(air_loop_hvac.model, 'Fan Nominal Pressure Rise')
      fan_pres_var.setName("#{snc}FanDesignPressure")
      fan_pres_var.setInternalDataIndexKeyName(fan.handle.to_s)

      dsn_flow_var = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(air_loop_hvac.model, 'Outdoor Air Controller Maximum Mass Flow Rate')
      dsn_flow_var.setName("#{snc}DesignFlowMass")
      dsn_flow_var.setInternalDataIndexKeyName(oa_control.handle.to_s)

      # Actuators
      fan_pres_act = OpenStudio::Model::EnergyManagementSystemActuator.new(fan, 'Fan', 'Fan Pressure Rise')
      fan_pres_act.setName("#{snc}FanPressure")

      # Global Variables
      gvar = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(air_loop_hvac.model, "#{snc}FanPwrExp")
      gvar = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(air_loop_hvac.model, "#{snc}Stg1Spd")
      gvar = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(air_loop_hvac.model, "#{snc}Stg2Spd")
      gvar = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(air_loop_hvac.model, "#{snc}HeatSpeed")
      gvar = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(air_loop_hvac.model, "#{snc}VenSpeed")

      # Programs
      fan_par_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(air_loop_hvac.model)
      fan_par_prg.setName("#{snc}SetFanPar")
      fan_par_prg_body = <<-EMS
        IF #{snc}NumberofStages == 1
          Return
        ENDIF
        SET #{snc}FanPwrExp = 2.2
        SET OAFrac = #{oa_flow_sen.handle}/#{dsn_flow_var.handle}
        IF  OAFrac < 0.66
          SET #{snc}VenSpeed = 0.66
          SET #{snc}Stg1Spd = 0.66
        ELSE
          SET #{snc}VenSpeed = OAFrac
          SET #{snc}Stg1Spd = OAFrac
        ENDIF
        SET #{snc}Stg2Spd = 1.0
        SET #{snc}HeatSpeed = 1.0
      EMS
      fan_par_prg.setBody(fan_par_prg_body)

      fan_ctrl_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(air_loop_hvac.model)
      fan_ctrl_prg.setName("#{snc}FanControl")
      fan_ctrl_prg_body = <<-EMS
        IF #{snc}NumberofStages == 1
          Return
        ENDIF
        IF #{htg_rtf_sen.handle} > 0
          SET Heating = #{htg_rtf_sen.handle}
          SET Ven = 1-#{htg_rtf_sen.handle}
          SET Eco = 0
          SET Stage1 = 0
          SET Stage2 = 0
        ELSE
          SET Heating = 0
          SET EcoSpeed = #{snc}VenSpeed
          IF #{spd_sen.handle} == 0
            IF #{clg_rtf_sen.handle} > 0
              SET Stage1 = #{clg_rtf_sen.handle}
              SET Stage2 = 0
              SET Ven = 1-#{clg_rtf_sen.handle}
              SET Eco = 0
              IF #{oa_flow_sen.handle} > (#{oa_flow_var.handle}*#{oa_sch_sen.handle})
                SET #{snc}Stg1Spd = 1.0
              ENDIF
            ELSE
              SET Stage1 = 0
              SET Stage2 = 0
              IF #{oa_flow_sen.handle} > (#{oa_flow_var.handle}*#{oa_sch_sen.handle})
                SET Eco = 1.0
                SET Ven = 0
                !Calculate the expected discharge air temperature if the system runs at its low speed
                SET ExpDAT = #{dat_sen.handle}-(1-#{snc}VenSpeed)*#{zn_temp_sen.handle}
                SET ExpDAT = ExpDAT/#{snc}VenSpeed
                IF #{oat_db_c_sen.handle} > ExpDAT
                  SET EcoSpeed = #{snc}Stg2Spd
                ENDIF
              ELSE
                SET Eco = 0
                SET Ven = 1.0
              ENDIF
            ENDIF
          ELSE
            SET Stage1 = 1-#{spd_sen.handle}
            SET Stage2 = #{spd_sen.handle}
            SET Ven = 0
            SET Eco = 0
            IF #{oa_flow_sen.handle} > (#{oa_flow_var.handle}*#{oa_sch_sen.handle})
              SET #{snc}Stg1Spd = 1.0
            ENDIF
          ENDIF
        ENDIF
        ! For each mode (percent time in mode)*(fanSpeer^PwrExp) is the contribution to weighted fan power over time step
        SET FPR = Ven*(#{snc}VenSpeed ^ #{snc}FanPwrExp)
        SET FPR = FPR+Eco*(EcoSpeed^#{snc}FanPwrExp)
        SET FPR1 = Stage1*(#{snc}Stg1Spd^#{snc}FanPwrExp)
        SET FPR = FPR+FPR1
        SET FPR2 = Stage2*(#{snc}Stg2Spd^#{snc}FanPwrExp)
        SET FPR = FPR+FPR2
        SET FPR3 = Heating*(#{snc}HeatSpeed^#{snc}FanPwrExp)
        SET FanPwrRatio = FPR+ FPR3
        ! system fan power is directly proportional to static pressure so this change linearly adjusts fan energy for speed control
        SET #{fan_pres_act.handle} = #{fan_pres_var.handle}*FanPwrRatio
      EMS
      fan_ctrl_prg.setBody(fan_ctrl_prg_body)

      # Program Calling Managers
      # Note that num_stg_prg must be listed before fan_par_prg
      # because it initializes a variable used by fan_par_prg.
      setup_mgr.addProgram(fan_par_prg)

      fan_ctrl_mgr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(air_loop_hvac.model)
      fan_ctrl_mgr.setName("#{snc}FanMainManager")
      fan_ctrl_mgr.setCallingPoint('BeginTimestepBeforePredictor')
      fan_ctrl_mgr.addProgram(fan_ctrl_prg)

    end

    return true
  end
air_loop_hvac_apply_standard_controls(air_loop_hvac, climate_zone) click to toggle source

Apply all standard required controls to the airloop

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not @todo optimum start @todo night damper shutoff @todo nightcycle control @todo night fan shutoff

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 33
def air_loop_hvac_apply_standard_controls(air_loop_hvac, climate_zone)
  # Unoccupied shutdown
  # Apply this before ERV because it modifies annual hours of operation which can impact ERV requirements
  if air_loop_hvac_unoccupied_fan_shutoff_required?(air_loop_hvac)
    occ_threshold = air_loop_hvac_unoccupied_threshold
    air_loop_hvac_enable_unoccupied_fan_shutoff(air_loop_hvac, min_occ_pct = occ_threshold)
  else
    air_loop_hvac.setAvailabilitySchedule(air_loop_hvac.model.alwaysOnDiscreteSchedule)
  end

  # Energy Recovery Ventilation
  if air_loop_hvac_energy_recovery_ventilator_required?(air_loop_hvac, climate_zone)
    air_loop_hvac_apply_energy_recovery_ventilator(air_loop_hvac, climate_zone)
  end

  # Economizers
  air_loop_hvac_apply_economizer_limits(air_loop_hvac, climate_zone)
  air_loop_hvac_apply_economizer_integration(air_loop_hvac, climate_zone)

  # Multizone VAV Systems
  if air_loop_hvac_multizone_vav_system?(air_loop_hvac)

    # VAV Reheat Control
    air_loop_hvac_apply_vav_damper_action(air_loop_hvac)

    # Multizone VAV Optimization
    # This rule does not apply to two hospital and one outpatient systems
    unless (@instvarbuilding_type == 'Hospital' && (air_loop_hvac.name.to_s.include?('VAV_ER') || air_loop_hvac.name.to_s.include?('VAV_ICU') ||
           air_loop_hvac.name.to_s.include?('VAV_OR') || air_loop_hvac.name.to_s.include?('VAV_LABS') ||
           air_loop_hvac.name.to_s.include?('VAV_PATRMS'))) ||
           (@instvarbuilding_type == 'Outpatient' && air_loop_hvac.name.to_s.include?('Outpatient F1'))
      if air_loop_hvac_multizone_vav_optimization_required?(air_loop_hvac, climate_zone)
        air_loop_hvac_enable_multizone_vav_optimization(air_loop_hvac)
      else
        air_loop_hvac_disable_multizone_vav_optimization(air_loop_hvac)
      end
    end

    # Static Pressure Reset
    # Per 5.2.2.16 (Halverson et al 2014), all multiple zone VAV systems are assumed to have DDC for all years of DOE 90.1 prototypes, so the has_ddc is not used any more.
    air_loop_hvac_supply_return_exhaust_relief_fans(air_loop_hvac).each do |fan|
      if fan.to_FanVariableVolume.is_initialized
        plr_req = fan_variable_volume_part_load_fan_power_limitation?(fan)
        # Part Load Fan Pressure Control
        if plr_req
          vsd_curve_type = air_loop_hvac_set_vsd_curve_type
          fan_variable_volume_set_control_type(fan, vsd_curve_type)
        # No Part Load Fan Pressure Control
        else
          fan_variable_volume_set_control_type(fan, 'Multi Zone VAV with discharge dampers')
        end
      else
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{fan}: This is not a multizone VAV fan system.")
      end
    end

    ## # Static Pressure Reset
    ## # assume no systems have DDC control of VAV terminals
    ## has_ddc = false
    ## spr_req = air_loop_hvac_static_pressure_reset_required?(air_loop_hvac, template, has_ddc)
    ## air_loop_hvac_supply_return_exhaust_relief_fans(air_loop_hvac).each do |fan|
    ##   if fan.to_FanVariableVolume.is_initialized
    ##     plr_req = fan_variable_volume_part_load_fan_power_limitation?(fan, template)
    ##     # Part Load Fan Pressure Control & Static Pressure Reset
    ##     if plr_req && spr_req
    ##       fan_variable_volume_set_control_type(fan, 'Multi Zone VAV with VSD and Static Pressure Reset')
    ##     # Part Load Fan Pressure Control only
    ##     elsif plr_req && !spr_req
    ##       fan_variable_volume_set_control_type(fan, 'Multi Zone VAV with VSD and Fixed SP Setpoint')
    ##     # Static Pressure Reset only
    ##     elsif !plr_req && spr_req
    ##       fan_variable_volume_set_control_type(fan, 'Multi Zone VAV with VSD and Fixed SP Setpoint')
    ##     # No Control Required
    ##     else
    ##       fan_variable_volume_set_control_type(fan, 'Multi Zone VAV with AF or BI Riding Curve')
    ##     end
    ##   else
    ##     OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', "For #{name}: there is a constant volume fan on a multizone vav system.  Cannot apply static pressure reset controls.")
    ##   end
    ## end
  end

  # DCV
  if air_loop_hvac_demand_control_ventilation_required?(air_loop_hvac, climate_zone)
    air_loop_hvac_enable_demand_control_ventilation(air_loop_hvac, climate_zone)
    # For systems that require DCV,
    # all individual zones that require DCV preserve
    # both per-area and per-person OA requirements.
    # Other zones have OA requirements converted
    # to per-area values only so DCV performance is only
    # based on the subset of zones that required DCV.
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Converting ventilation requirements to per-area for all zones served that do not require DCV.")
    air_loop_hvac.thermalZones.sort.each do |zone|
      unless thermal_zone_demand_control_ventilation_required?(zone, climate_zone)
        OpenstudioStandards::ThermalZone.thermal_zone_convert_outdoor_air_to_per_area(zone)
      end
    end
  end

  # SAT reset
  if air_loop_hvac_supply_air_temperature_reset_required?(air_loop_hvac, climate_zone)
    reset_type = air_loop_hvac_supply_air_temperature_reset_type(air_loop_hvac)
    case reset_type
      when 'warmest_zone'
        air_loop_hvac_enable_supply_air_temperature_reset_warmest_zone(air_loop_hvac)
      when 'oa'
        air_loop_hvac_enable_supply_air_temperature_reset_outdoor_temperature(air_loop_hvac)
      else
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "No SAT reset for #{air_loop_hvac.name}.")
    end
  end

  # Motorized OA damper
  if air_loop_hvac_motorized_oa_damper_required?(air_loop_hvac, climate_zone)
    # Assume that the availability schedule has already been
    # set to reflect occupancy and use this for the OA damper.
    occ_threshold = air_loop_hvac_unoccupied_threshold
    air_loop_hvac_add_motorized_oa_damper(air_loop_hvac, occ_threshold, air_loop_hvac.availabilitySchedule)
  else
    air_loop_hvac_remove_motorized_oa_damper(air_loop_hvac)
  end

  # Optimum Start
  air_loop_hvac_enable_optimum_start(air_loop_hvac) if air_loop_hvac_optimum_start_required?(air_loop_hvac)

  # Single zone systems
  if air_loop_hvac.thermalZones.size == 1
    air_loop_hvac_supply_return_exhaust_relief_fans(air_loop_hvac).each do |fan|
      if fan.to_FanVariableVolume.is_initialized
        fan_variable_volume_set_control_type(fan, 'Single Zone VAV Fan')
      end
    end
    air_loop_hvac_apply_single_zone_controls(air_loop_hvac, climate_zone)
  end

  # Standby mode occupancy control
  unless air_loop_hvac.thermalZones.empty?
    thermal_zones = air_loop_hvac.thermalZones

    standby_mode_spaces = []
    thermal_zones.sort.each do |thermal_zone|
      thermal_zone.spaces.sort.each do |space|
        if space_occupancy_standby_mode_required?(space)
          standby_mode_spaces << space
        end
      end
    end

    if !standby_mode_spaces.empty?
      air_loop_hvac_standby_mode_occupancy_control(air_loop_hvac, standby_mode_spaces)
    end
  end
end
air_loop_hvac_apply_vav_damper_action(air_loop_hvac) click to toggle source

Set the VAV damper control to single maximum or dual maximum control depending on the standard.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if successful, false if not @todo see if this impacts the sizing run.

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2679
def air_loop_hvac_apply_vav_damper_action(air_loop_hvac)
  damper_action = air_loop_hvac_vav_damper_action(air_loop_hvac)

  # Interpret this as an EnergyPlus input
  damper_action_eplus = nil
  if damper_action == 'Single Maximum'
    damper_action_eplus = 'Normal'
  elsif damper_action == 'Dual Maximum'
    # EnergyPlus 8.7 changed the meaning of 'Reverse'.
    # For versions of OpenStudio using E+ 8.6 or lower
    damper_action_eplus = if air_loop_hvac.model.version < OpenStudio::VersionString.new('2.0.5')
                            'Reverse'
                          # For versions of OpenStudio using E+ 8.7 or higher
                          else
                            'ReverseWithLimits'
                          end
  end

  # Set the control for any VAV reheat terminals on this airloop.
  control_type_set = false
  air_loop_hvac.demandComponents.each do |equip|
    if equip.to_AirTerminalSingleDuctVAVReheat.is_initialized
      term = equip.to_AirTerminalSingleDuctVAVReheat.get
      # Dual maximum only applies to terminals with HW reheat coils
      if damper_action == 'Dual Maximum'
        if term.reheatCoil.to_CoilHeatingWater.is_initialized
          term.setDamperHeatingAction(damper_action_eplus)
          control_type_set = true
          term.setMaximumFlowFractionDuringReheat(0.5)
        end
      else
        term.setDamperHeatingAction(damper_action_eplus)
        control_type_set = true
      end
    end
  end

  if control_type_set
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: VAV damper action was set to #{damper_action} control.")
  end

  return true
end
air_loop_hvac_data_center_area_served(air_loop_hvac) click to toggle source

Determine how much data center area the airloop serves.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Double] the area of data center is served in m^2. @todo Add an is_data_center field to the standards space type spreadsheet instead

of relying on the standards space type name to identify a data center.
# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3507
def air_loop_hvac_data_center_area_served(air_loop_hvac)
  dc_area_m2 = 0.0

  air_loop_hvac.thermalZones.each do |zone|
    zone.spaces.each do |space|
      # Skip spaces with no space type
      next if space.spaceType.empty?

      space_type = space.spaceType.get

      # Skip spaces with no standards space type
      next if space_type.standardsSpaceType.empty?

      standards_space_type = space_type.standardsSpaceType.get
      # Counts as a data center if the name includes 'data'
      if standards_space_type.downcase.include?('data center') || standards_space_type.downcase.include?('datacenter')
        dc_area_m2 += space.floorArea
      end
      std_bldg_type = space.spaceType.get.standardsBuildingType.get
      if std_bldg_type.downcase.include?('datacenter') && standards_space_type.downcase.include?('computerroom')
        dc_area_m2 += space.floorArea
      end
    end
  end

  return dc_area_m2
end
air_loop_hvac_dcv_required_when_erv(air_loop_hvac) click to toggle source

Determine if the standard has an exception for demand control ventilation when an energy recovery device is present. Defaults to true.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2406
def air_loop_hvac_dcv_required_when_erv(air_loop_hvac)
  dcv_required_when_erv_present = false
  return dcv_required_when_erv_present
end
air_loop_hvac_demand_control_ventilation_limits(air_loop_hvac) click to toggle source

Determines the OA flow rates above which an economizer is required. Two separate rates, one for systems with an economizer and another for systems without. Defaults to pre-1980 logic, where the limits are zero for both types.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Array<Double>] [min_oa_without_economizer_cfm, min_oa_with_economizer_cfm]

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2395
def air_loop_hvac_demand_control_ventilation_limits(air_loop_hvac)
  min_oa_without_economizer_cfm = 0
  min_oa_with_economizer_cfm = 0
  return [min_oa_without_economizer_cfm, min_oa_with_economizer_cfm]
end
air_loop_hvac_demand_control_ventilation_required?(air_loop_hvac, climate_zone) click to toggle source

Determine if demand control ventilation (DCV) is required for this air loop.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if required, false if not @todo Add exception logic for systems that serve multifamily, parking garage, warehouse

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2312
def air_loop_hvac_demand_control_ventilation_required?(air_loop_hvac, climate_zone)
  dcv_required = false

  # OA flow limits
  min_oa_without_economizer_cfm, min_oa_with_economizer_cfm = air_loop_hvac_demand_control_ventilation_limits(air_loop_hvac)

  # If the limits are zero for both, DCV not required
  if min_oa_without_economizer_cfm.zero? && min_oa_with_economizer_cfm.zero?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{template} #{climate_zone}:  #{air_loop_hvac.name}: DCV is not required for any system.")
    return dcv_required
  end

  # Check if the system has an ERV
  if air_loop_hvac_energy_recovery?(air_loop_hvac)
    # May or may not be required for systems that have an ERV
    if air_loop_hvac_dcv_required_when_erv(air_loop_hvac)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: DCV may be required although the system has Energy Recovery.")
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: DCV is not required since the system has Energy Recovery.")
      return dcv_required
    end
  end

  # Get the min OA flow rate
  oa_flow_m3_per_s = 0
  if air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized
    oa_system = air_loop_hvac.airLoopHVACOutdoorAirSystem.get
    controller_oa = oa_system.getControllerOutdoorAir
    if controller_oa.minimumOutdoorAirFlowRate.is_initialized
      oa_flow_m3_per_s = controller_oa.minimumOutdoorAirFlowRate.get
    elsif controller_oa.autosizedMinimumOutdoorAirFlowRate.is_initialized
      oa_flow_m3_per_s = controller_oa.autosizedMinimumOutdoorAirFlowRate.get
    end
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, DCV not applicable because it has no OA intake.")
    return dcv_required
  end
  oa_flow_cfm = OpenStudio.convert(oa_flow_m3_per_s, 'm^3/s', 'cfm').get

  # Check for min OA without an economizer OR has economizer
  if oa_flow_cfm < min_oa_without_economizer_cfm && air_loop_hvac_economizer?(air_loop_hvac) == false
    # Message if doesn't pass OA limit
    if oa_flow_cfm < min_oa_without_economizer_cfm
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: DCV is not required since the system min oa flow is #{oa_flow_cfm.round} cfm, less than the minimum of #{min_oa_without_economizer_cfm.round} cfm.")
    end
    # Message if doesn't have economizer
    if air_loop_hvac_economizer?(air_loop_hvac) == false
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: DCV is not required since the system does not have an economizer.")
    end
    return dcv_required
  end

  # If has economizer, cfm limit is lower
  if oa_flow_cfm < min_oa_with_economizer_cfm && air_loop_hvac_economizer?(air_loop_hvac)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: DCV is not required since the system has an economizer, but the min oa flow is #{oa_flow_cfm.round} cfm, less than the minimum of #{min_oa_with_economizer_cfm.round} cfm for systems with an economizer.")
    return dcv_required
  end

  # Check area and density limits
  # for all of zones on the loop
  any_zones_req_dcv = false
  air_loop_hvac.thermalZones.sort.each do |zone|
    if thermal_zone_demand_control_ventilation_required?(zone, climate_zone)
      any_zones_req_dcv = true
      break
    end
  end
  unless any_zones_req_dcv
    return dcv_required
  end

  # If here, DCV is required
  dcv_required = true

  return dcv_required
end
air_loop_hvac_disable_multizone_vav_optimization(air_loop_hvac) click to toggle source

Disable multizone vav optimization by changing the Outdoor Air Method in the Controller:MechanicalVentilation object to ‘ZoneSum’

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1950
def air_loop_hvac_disable_multizone_vav_optimization(air_loop_hvac)
  # Disable multizone vav optimization
  # at each timestep.
  if air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized
    oa_system = air_loop_hvac.airLoopHVACOutdoorAirSystem.get
    controller_oa = oa_system.getControllerOutdoorAir
    controller_mv = controller_oa.controllerMechanicalVentilation
    controller_mv.setSystemOutdoorAirMethod('ZoneSum')
    controller_oa.autosizeMinimumOutdoorAirFlowRate
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, cannot disable multizone vav optimization because the system has no OA intake.")
    return false
  end
end
air_loop_hvac_dx_cooling?(air_loop_hvac) click to toggle source

Determine if this Air Loop uses DX cooling.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if uses DX cooling, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3654
def air_loop_hvac_dx_cooling?(air_loop_hvac)
  dx_clg = false

  # Check for all DX coil types
  dx_types = [
    'OS_Coil_Cooling_DX_MultiSpeed',
    'OS_Coil_Cooling_DX_SingleSpeed',
    'OS_Coil_Cooling_DX_TwoSpeed',
    'OS_Coil_Cooling_DX_TwoStageWithHumidityControlMode',
    'OS_Coil_Cooling_DX_VariableRefrigerantFlow',
    'OS_Coil_Cooling_DX_VariableSpeed',
    'OS_CoilSystem_Cooling_DX_HeatExchangerAssisted'
  ]

  air_loop_hvac.supplyComponents.each do |component|
    # Get the object type, getting the internal coil
    # type if inside a unitary system.
    obj_type = component.iddObjectType.valueName.to_s
    case obj_type
    when 'OS_AirLoopHVAC_UnitaryHeatCool_VAVChangeoverBypass'
      component = component.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.get
      obj_type = component.coolingCoil.iddObjectType.valueName.to_s
    when 'OS_AirLoopHVAC_UnitaryHeatPump_AirToAir'
      component = component.to_AirLoopHVACUnitaryHeatPumpAirToAir.get
      obj_type = component.coolingCoil.iddObjectType.valueName.to_s
    when 'OS_AirLoopHVAC_UnitaryHeatPump_AirToAir_MultiSpeed'
      component = component.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.get
      obj_type = component.coolingCoil.iddObjectType.valueName.to_s
    when 'OS_AirLoopHVAC_UnitarySystem'
      component = component.to_AirLoopHVACUnitarySystem.get
      if component.coolingCoil.is_initialized
        obj_type = component.coolingCoil.get.iddObjectType.valueName.to_s
      end
    end
    # See if the object type is a DX coil
    if dx_types.include?(obj_type)
      dx_clg = true
      break # Stop if find a DX coil
    end
  end

  return dx_clg
end
air_loop_hvac_economizer?(air_loop_hvac) click to toggle source

Determine if the system has an economizer

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2550
def air_loop_hvac_economizer?(air_loop_hvac)
  # Get the OA system and OA controller
  oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
  return false unless oa_sys.is_initialized

  oa_sys = oa_sys.get
  oa_control = oa_sys.getControllerOutdoorAir
  economizer_type = oa_control.getEconomizerControlType

  # Return false if no economizer is present
  return false if economizer_type == 'NoEconomizer'

  return true
end
air_loop_hvac_economizer_limits(air_loop_hvac, climate_zone) click to toggle source

Determine the limits for the type of economizer present on the AirLoopHVAC, if any.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Array<Double>] [drybulb_limit_f, enthalpy_limit_btu_per_lb, dewpoint_limit_f]

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1105
def air_loop_hvac_economizer_limits(air_loop_hvac, climate_zone)
  drybulb_limit_f = nil
  enthalpy_limit_btu_per_lb = nil
  dewpoint_limit_f = nil

  # Get the OA system and OA controller
  oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
  return [nil, nil, nil] unless oa_sys.is_initialized

  oa_sys = oa_sys.get
  oa_control = oa_sys.getControllerOutdoorAir
  economizer_type = oa_control.getEconomizerControlType

  case economizer_type
  when 'NoEconomizer'
    return [nil, nil, nil]
  when 'FixedDryBulb'
    search_criteria = {
      'template' => template,
      'climate_zone' => climate_zone
    }
    econ_limits = model_find_object(standards_data['economizers'], search_criteria)
    drybulb_limit_f = econ_limits['fixed_dry_bulb_high_limit_shutoff_temp']
  when 'FixedEnthalpy'
    enthalpy_limit_btu_per_lb = 28
  when 'FixedDewPointAndDryBulb'
    drybulb_limit_f = 75
    dewpoint_limit_f = 55
  end

  return [drybulb_limit_f, enthalpy_limit_btu_per_lb, dewpoint_limit_f]
end
air_loop_hvac_economizer_required?(air_loop_hvac, climate_zone) click to toggle source

Determine whether or not this system is required to have an economizer.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if an economizer is required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 953
def air_loop_hvac_economizer_required?(air_loop_hvac, climate_zone)
  economizer_required = false

  # skip systems without outdoor air
  return economizer_required unless air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized

  # Determine if the system serves residential spaces
  is_res = false
  if air_loop_hvac_residential_area_served(air_loop_hvac) > 0
    is_res = true
  end

  # Determine if the airloop serves any computer rooms
  # / data centers, which changes the economizer.
  is_dc = false
  if air_loop_hvac_data_center_area_served(air_loop_hvac) > 0
    is_dc = true
  end

  # Retrieve economizer limits from JSON
  search_criteria = {
    'template' => template,
    'climate_zone' => climate_zone,
    'data_center' => is_dc
  }
  econ_limits = model_find_object(standards_data['economizers'], search_criteria)
  if econ_limits.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "Cannot find economizer limits for template '#{template}' and climate zone '#{climate_zone}', assuming no economizer required.")
    return economizer_required
  end

  # Determine the minimum capacity and whether or not it is a data center
  minimum_capacity_btu_per_hr = econ_limits['capacity_limit']

  # A big number of btu per hr as the minimum requirement if nil in spreadsheet
  infinity_btu_per_hr = 999_999_999_999
  minimum_capacity_btu_per_hr = infinity_btu_per_hr if minimum_capacity_btu_per_hr.nil?

  # Exception valid for 90.1-2004 (6.5.1.(e)) through 90.1-2019 (6.5.1.4)
  if is_res
    minimum_capacity_btu_per_hr *= 5
  end

  # Check whether the system requires an economizer by comparing
  # the system capacity to the minimum capacity.
  total_cooling_capacity_w = air_loop_hvac_total_cooling_capacity(air_loop_hvac)
  total_cooling_capacity_btu_per_hr = OpenStudio.convert(total_cooling_capacity_w, 'W', 'Btu/hr').get

  if total_cooling_capacity_btu_per_hr >= minimum_capacity_btu_per_hr
    if is_dc
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name} requires an economizer because the total cooling capacity of #{total_cooling_capacity_btu_per_hr.round} Btu/hr exceeds the minimum capacity of #{minimum_capacity_btu_per_hr.round} Btu/hr for data centers.")
    elsif is_res
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name} requires an economizer because the total cooling capacity of #{total_cooling_capacity_btu_per_hr.round} Btu/hr exceeds the minimum capacity of #{minimum_capacity_btu_per_hr.round} Btu/hr for residential spaces.")
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name} requires an economizer because the total cooling capacity of #{total_cooling_capacity_btu_per_hr.round} Btu/hr exceeds the minimum capacity of #{minimum_capacity_btu_per_hr.round} Btu/hr.")
    end
    economizer_required = true
  else
    if is_dc
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name} does not require an economizer because the total cooling capacity of #{total_cooling_capacity_btu_per_hr.round} Btu/hr is less than the minimum capacity of #{minimum_capacity_btu_per_hr.round} Btu/hr for data centers.")
    elsif is_res
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name} requires an economizer because the total cooling capacity of #{total_cooling_capacity_btu_per_hr.round} Btu/hr exceeds the minimum capacity of #{minimum_capacity_btu_per_hr.round} Btu/hr for residential spaces.")
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name} does not require an economizer because the total cooling capacity of #{total_cooling_capacity_btu_per_hr.round} Btu/hr is less than the minimum capacity of #{minimum_capacity_btu_per_hr.round} Btu/hr.")
    end
  end

  return economizer_required
end
air_loop_hvac_economizer_type_allowable?(air_loop_hvac, climate_zone) click to toggle source

Check the economizer type currently specified in the ControllerOutdoorAir object on this air loop is acceptable per the standard. Defaults to 90.1-2007 logic.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if allowable, if the system has no economizer or no OA system

Returns false if the economizer type is not allowable.
# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1558
def air_loop_hvac_economizer_type_allowable?(air_loop_hvac, climate_zone)
  # EnergyPlus economizer types
  # 'NoEconomizer'
  # 'FixedDryBulb'
  # 'FixedEnthalpy'
  # 'DifferentialDryBulb'
  # 'DifferentialEnthalpy'
  # 'FixedDewPointAndDryBulb'
  # 'ElectronicEnthalpy'
  # 'DifferentialDryBulbAndEnthalpy'

  # Get the OA system and OA controller
  oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
  return true unless oa_sys.is_initialized

  oa_sys = oa_sys.get
  oa_control = oa_sys.getControllerOutdoorAir
  economizer_type = oa_control.getEconomizerControlType

  # Return true if no economizer is present
  return true if economizer_type == 'NoEconomizer'

  # Determine the prohibited types
  prohibited_types = []
  case climate_zone
  when 'ASHRAE 169-2006-0B',
       'ASHRAE 169-2006-1B',
       'ASHRAE 169-2006-2B',
       'ASHRAE 169-2006-3B',
       'ASHRAE 169-2006-3C',
       'ASHRAE 169-2006-4B',
       'ASHRAE 169-2006-4C',
       'ASHRAE 169-2006-5B',
       'ASHRAE 169-2006-6B',
       'ASHRAE 169-2006-7A',
       'ASHRAE 169-2006-7B',
       'ASHRAE 169-2006-8A',
       'ASHRAE 169-2006-8B',
       'ASHRAE 169-2013-0B',
       'ASHRAE 169-2013-1B',
       'ASHRAE 169-2013-2B',
       'ASHRAE 169-2013-3B',
       'ASHRAE 169-2013-3C',
       'ASHRAE 169-2013-4B',
       'ASHRAE 169-2013-4C',
       'ASHRAE 169-2013-5B',
       'ASHRAE 169-2013-6B',
       'ASHRAE 169-2013-7A',
       'ASHRAE 169-2013-7B',
       'ASHRAE 169-2013-8A',
       'ASHRAE 169-2013-8B'
    prohibited_types = ['FixedEnthalpy']
  when 'ASHRAE 169-2006-0A',
       'ASHRAE 169-2006-1A',
       'ASHRAE 169-2006-2A',
       'ASHRAE 169-2006-3A',
       'ASHRAE 169-2006-4A',
       'ASHRAE 169-2013-0A',
       'ASHRAE 169-2013-1A',
       'ASHRAE 169-2013-2A',
       'ASHRAE 169-2013-3A',
       'ASHRAE 169-2013-4A'
    prohibited_types = ['DifferentialDryBulb']
  when 'ASHRAE 169-2006-5A',
       'ASHRAE 169-2006-6A',
       'ASHRAE 169-2013-5A',
       'ASHRAE 169-2013-6A'
    prohibited_types = []
  end

  # Check if the specified type is allowed
  economizer_type_allowed = true
  if prohibited_types.include?(economizer_type)
    economizer_type_allowed = false
  end

  return economizer_type_allowed
end
air_loop_hvac_enable_demand_control_ventilation(air_loop_hvac, climate_zone) click to toggle source

Enable demand control ventilation (DCV) for this air loop. Zones on this loop that require DCV preserve both per-area and per-person OA reqs. Other zones have OA reqs converted to per-area values only so that DCV won’t impact these zones.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2418
def air_loop_hvac_enable_demand_control_ventilation(air_loop_hvac, climate_zone)
  # Get the OA intake
  controller_oa = nil
  controller_mv = nil
  if air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized
    oa_system = air_loop_hvac.airLoopHVACOutdoorAirSystem.get
    controller_oa = oa_system.getControllerOutdoorAir
    controller_mv = controller_oa.controllerMechanicalVentilation
    if controller_mv.demandControlledVentilation == true
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: DCV was already enabled.")
      return true
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Could not enable DCV since the system has no OA intake.")
    return false
  end

  # Change the min flow rate in the controller outdoor air
  controller_oa.setMinimumOutdoorAirFlowRate(0.0)

  # Enable DCV in the controller mechanical ventilation
  controller_mv.setDemandControlledVentilation(true)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Enabled DCV.")

  return true
end
air_loop_hvac_enable_multizone_vav_optimization(air_loop_hvac) click to toggle source

Enable multizone vav optimization by changing the Outdoor Air Method in the Controller:MechanicalVentilation object to ‘VentilationRateProcedure’

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1925
def air_loop_hvac_enable_multizone_vav_optimization(air_loop_hvac)
  # Enable multizone vav optimization
  # at each timestep.
  if air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized
    oa_system = air_loop_hvac.airLoopHVACOutdoorAirSystem.get
    controller_oa = oa_system.getControllerOutdoorAir
    controller_mv = controller_oa.controllerMechanicalVentilation
    if air_loop_hvac.model.version < OpenStudio::VersionString.new('3.3.0')
      controller_mv.setSystemOutdoorAirMethod('VentilationRateProcedure')
    else
      controller_mv.setSystemOutdoorAirMethod('Standard62.1VentilationRateProcedureWithLimit')
    end
    # Change the min flow rate in the controller outdoor air
    controller_oa.setMinimumOutdoorAirFlowRate(0.0)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, cannot enable multizone vav optimization because the system has no OA intake.")
    return false
  end
end
air_loop_hvac_enable_optimum_start(air_loop_hvac) click to toggle source

Adds optimum start control to the airloop.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 272
  def air_loop_hvac_enable_optimum_start(air_loop_hvac)
    # Get the heating and cooling setpoint schedules
    # for all zones on this airloop.
    htg_clg_schs = []
    air_loop_hvac.thermalZones.each do |zone|
      # Skip zones with no thermostat
      next if zone.thermostatSetpointDualSetpoint.empty?

      # Get the heating and cooling setpoint schedules
      tstat = zone.thermostatSetpointDualSetpoint.get
      htg_sch = nil
      if tstat.heatingSetpointTemperatureSchedule.is_initialized
        htg_sch = tstat.heatingSetpointTemperatureSchedule.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{zone.name}: Cannot find a heating setpoint schedule for this zone, cannot apply optimum start control.")
        next
      end
      clg_sch = nil
      if tstat.coolingSetpointTemperatureSchedule.is_initialized
        clg_sch = tstat.coolingSetpointTemperatureSchedule.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{zone.name}: Cannot find a cooling setpoint schedule for this zone, cannot apply optimum start control.")
        next
      end
      htg_clg_schs << [htg_sch, clg_sch]
    end

    # Clean name of airloop
    loop_name_clean = air_loop_hvac.name.get.to_s.gsub(/\W/, '').delete('_')
    # If the name starts with a number, prepend with a letter
    if loop_name_clean[0] =~ /[0-9]/
      loop_name_clean = "SYS#{loop_name_clean}"
    end

    # Sensors
    oat_db_c_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(air_loop_hvac.model, 'Site Outdoor Air Drybulb Temperature')
    oat_db_c_sen.setName('OAT')
    oat_db_c_sen.setKeyName('Environment')

    # Make a program for each unique set of schedules.
    # For most air loops, all zones will have the same
    # pair of schedules.
    htg_clg_schs.uniq.each_with_index do |htg_clg_sch, i|
      htg_sch = htg_clg_sch[0]
      clg_sch = htg_clg_sch[1]

      if htg_sch.to_ScheduleConstant.is_initialized
        htg_sch_type = 'Schedule:Constant'
      elsif htg_sch.to_ScheduleCompact.is_initialized
        htg_sch_type = 'Schedule:Compact'
      else
        htg_sch_type = 'Schedule:Year'
      end

      if clg_sch.to_ScheduleCompact.is_initialized
        clg_sch_type = 'Schedule:Constant'
      elsif clg_sch.to_ScheduleCompact.is_initialized
        clg_sch_type = 'Schedule:Compact'
      else
        clg_sch_type = 'Schedule:Year'
      end

      # Actuators
      htg_sch_act = OpenStudio::Model::EnergyManagementSystemActuator.new(htg_sch, htg_sch_type, 'Schedule Value')
      htg_sch_act.setName("#{loop_name_clean}HtgSch#{i}")

      clg_sch_act = OpenStudio::Model::EnergyManagementSystemActuator.new(clg_sch, clg_sch_type, 'Schedule Value')
      clg_sch_act.setName("#{loop_name_clean}ClgSch#{i}")

      # Programs
      optstart_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(air_loop_hvac.model)
      optstart_prg.setName("#{loop_name_clean}OptimumStartProg#{i}")
      optstart_prg_body = <<-EMS
      IF DaylightSavings==0 && DayOfWeek>1 && Hour==5 && #{oat_db_c_sen.handle}<23.9 && #{oat_db_c_sen.handle}>1.7
        SET #{clg_sch_act.handle} = 29.4
        SET #{htg_sch_act.handle} = 15.6
      ELSEIF DaylightSavings==0 && DayOfWeek==1 && Hour==7 && #{oat_db_c_sen.handle}<23.9 && #{oat_db_c_sen.handle}>1.7
        SET #{clg_sch_act.handle} = 29.4
        SET #{htg_sch_act.handle} = 15.6
      ELSEIF DaylightSavings==1 && DayOfWeek>1 && Hour==4 && #{oat_db_c_sen.handle}<23.9 && #{oat_db_c_sen.handle}>1.7
        SET #{clg_sch_act.handle} = 29.4
        SET #{htg_sch_act.handle} = 15.6
      ELSEIF DaylightSavings==1 && DayOfWeek==1 && Hour==6 && #{oat_db_c_sen.handle}<23.9 && #{oat_db_c_sen.handle}>1.7
        SET #{clg_sch_act.handle} = 29.4
        SET #{htg_sch_act.handle} = 15.6
      ELSE
        SET #{clg_sch_act.handle} = NULL
        SET #{htg_sch_act.handle} = NULL
      ENDIF
      EMS
      optstart_prg.setBody(optstart_prg_body)

      # Program Calling Managers
      setup_mgr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(air_loop_hvac.model)
      setup_mgr.setName("#{loop_name_clean}OptimumStartCallingManager#{i}")
      setup_mgr.setCallingPoint('BeginTimestepBeforePredictor')
      setup_mgr.addProgram(optstart_prg)
    end

    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Optimum start control enabled.")

    return true
  end
air_loop_hvac_enable_supply_air_temperature_reset_delta(air_loop_hvac) click to toggle source

Determines supply air temperature (SAT) temperature. Defaults to 90.1-2007, 5 delta-F ®

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Double] the SAT reset amount in degrees Rankine

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2495
def air_loop_hvac_enable_supply_air_temperature_reset_delta(air_loop_hvac)
  sat_reset_r = 5.0
  return sat_reset_r
end
air_loop_hvac_enable_supply_air_temperature_reset_outdoor_temperature(air_loop_hvac) click to toggle source

Enable supply air temperature (SAT) reset based on outdoor air conditions. SAT will be kept at the current design temperature when outdoor air is above 70F, increased by 5F when outdoor air is below 50F, and reset linearly when outdoor air is between 50F and 70F.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2507
def air_loop_hvac_enable_supply_air_temperature_reset_outdoor_temperature(air_loop_hvac)
  # for AHU1 in Outpatient, SAT is 52F constant, no reset
  return true if air_loop_hvac.name.get == 'PVAV Outpatient F1'

  # Get the current setpoint and calculate
  # the new setpoint.
  sizing_system = air_loop_hvac.sizingSystem
  sat_at_hi_oat_c = sizing_system.centralCoolingDesignSupplyAirTemperature
  sat_at_hi_oat_f = OpenStudio.convert(sat_at_hi_oat_c, 'C', 'F').get
  # 5F increase when it's cold outside,
  # and therefore less cooling capacity is likely required.
  increase_f = air_loop_hvac_enable_supply_air_temperature_reset_delta(air_loop_hvac)
  sat_at_lo_oat_f = sat_at_hi_oat_f + increase_f
  sat_at_lo_oat_c = OpenStudio.convert(sat_at_lo_oat_f, 'F', 'C').get

  # Define the high and low outdoor air temperatures
  lo_oat_f = 50
  lo_oat_c = OpenStudio.convert(lo_oat_f, 'F', 'C').get
  hi_oat_f = 70
  hi_oat_c = OpenStudio.convert(hi_oat_f, 'F', 'C').get

  # Create a setpoint manager
  sat_oa_reset = OpenStudio::Model::SetpointManagerOutdoorAirReset.new(air_loop_hvac.model)
  sat_oa_reset.setName("#{air_loop_hvac.name} SAT Reset")
  sat_oa_reset.setControlVariable('Temperature')
  sat_oa_reset.setSetpointatOutdoorLowTemperature(sat_at_lo_oat_c)
  sat_oa_reset.setOutdoorLowTemperature(lo_oat_c)
  sat_oa_reset.setSetpointatOutdoorHighTemperature(sat_at_hi_oat_c)
  sat_oa_reset.setOutdoorHighTemperature(hi_oat_c)

  # Attach the setpoint manager to the
  # supply outlet node of the system.
  sat_oa_reset.addToNode(air_loop_hvac.supplyOutletNode)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Supply air temperature reset was enabled.  When OAT is greater than #{hi_oat_f.round}F, SAT is #{sat_at_hi_oat_f.round}F.  When OAT is less than #{lo_oat_f.round}F, SAT is #{sat_at_lo_oat_f.round}F.  It varies linearly in between these points.")

  return true
end
air_loop_hvac_enable_supply_air_temperature_reset_warmest_zone(air_loop_hvac) click to toggle source

Enable supply air temperature (SAT) reset based on the cooling demand of the warmest zone.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2460
def air_loop_hvac_enable_supply_air_temperature_reset_warmest_zone(air_loop_hvac)
  # Get the current setpoint and calculate
  # the new setpoint.
  sizing_system = air_loop_hvac.sizingSystem
  design_sat_c = sizing_system.centralCoolingDesignSupplyAirTemperature
  design_sat_f = OpenStudio.convert(design_sat_c, 'C', 'F').get

  # Get the SAT reset delta
  sat_reset_r = air_loop_hvac_enable_supply_air_temperature_reset_delta(air_loop_hvac)
  sat_reset_k = OpenStudio.convert(sat_reset_r, 'R', 'K').get

  max_sat_f = design_sat_f + sat_reset_r
  max_sat_c = design_sat_c + sat_reset_k

  # Create a setpoint manager
  sat_warmest_reset = OpenStudio::Model::SetpointManagerWarmest.new(air_loop_hvac.model)
  sat_warmest_reset.setName("#{air_loop_hvac.name} SAT Warmest Reset")
  sat_warmest_reset.setStrategy('MaximumTemperature')
  sat_warmest_reset.setMinimumSetpointTemperature(design_sat_c)
  sat_warmest_reset.setMaximumSetpointTemperature(max_sat_c)

  # Attach the setpoint manager to the
  # supply outlet node of the system.
  sat_warmest_reset.addToNode(air_loop_hvac.supplyOutletNode)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Supply air temperature reset was enabled using a SPM Warmest with a min SAT of #{design_sat_f.round}F and a max SAT of #{max_sat_f.round}F.")

  return true
end
air_loop_hvac_enable_unoccupied_fan_shutoff(air_loop_hvac, min_occ_pct = 0.05) click to toggle source

Shut off the system during unoccupied periods. During these times, systems will cycle on briefly if temperature drifts below setpoint. If the system already has a schedule other than Always-On, no change will be made. If the system has an Always-On schedule assigned, a new schedule will be created. In this case, occupied is defined as the total percent occupancy for the loop for all zones served.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param min_occ_pct [Double] the fractional value below which the system will be considered unoccupied. @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3349
def air_loop_hvac_enable_unoccupied_fan_shutoff(air_loop_hvac, min_occ_pct = 0.05)
  # Set the system to night cycle
  # The fan of a parallel PIU terminal are set to only cycle during heating operation
  # This is achieved using the CycleOnAnyCoolingOrHeatingZone; During cooling operation
  # the load is met by running the central system which stays off during heating
  # operation
  air_loop_hvac.setNightCycleControlType('CycleOnAny')
  if air_loop_hvac_has_parallel_piu_air_terminals?(air_loop_hvac)
    avail_mgrs = air_loop_hvac.availabilityManagers
    if !avail_mgrs.nil?
      avail_mgrs.each do |avail_mgr|
        if avail_mgr.to_AvailabilityManagerNightCycle.is_initialized
          avail_mgr_nc = avail_mgr.to_AvailabilityManagerNightCycle.get
          avail_mgr_nc.setControlType('CycleOnAnyCoolingOrHeatingZone')
          zones = air_loop_hvac.thermalZones
          avail_mgr_nc.setCoolingControlThermalZones(zones)
          avail_mgr_nc.setHeatingZoneFansOnlyThermalZones(zones)
        end
      end
    end
  end

  model = air_loop_hvac.model
  # Check if schedule was stored in an additionalProperties field of the air loop
  air_loop_name = air_loop_hvac.name
  if air_loop_hvac.hasAdditionalProperties
    if air_loop_hvac.additionalProperties.hasFeature('fan_sched_name')
      fan_sched_name = air_loop_hvac.additionalProperties.getFeatureAsString('fan_sched_name').get
      fan_sched = model.getScheduleRulesetByName(fan_sched_name).get
      air_loop_hvac.setAvailabilitySchedule(fan_sched)
      return true
    end
  end

  # Check if already using a schedule other than always on
  avail_sch = air_loop_hvac.availabilitySchedule
  unless avail_sch == air_loop_hvac.model.alwaysOnDiscreteSchedule
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Availability schedule is already set to #{avail_sch.name}.  Will assume this includes unoccupied shut down; no changes will be made.")
    return true
  end

  # Get the airloop occupancy schedule
  loop_occ_sch = air_loop_hvac_get_occupancy_schedule(air_loop_hvac, occupied_percentage_threshold: min_occ_pct)
  flh = OpenstudioStandards::Schedules.schedule_get_equivalent_full_load_hours(loop_occ_sch)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Annual occupied hours = #{flh.round} hr/yr, assuming a #{min_occ_pct} occupancy threshold.  This schedule will be used as the HVAC operation schedule.")

  # Set HVAC availability schedule to follow occupancy
  air_loop_hvac.setAvailabilitySchedule(loop_occ_sch)
  air_loop_hvac.supplyComponents.each do |comp|
    if comp.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.is_initialized
      comp.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.get.setSupplyAirFanOperatingModeSchedule(loop_occ_sch)
    elsif comp.to_AirLoopHVACUnitarySystem.is_initialized
      comp.to_AirLoopHVACUnitarySystem.get.setSupplyAirFanOperatingModeSchedule(loop_occ_sch)
    end
  end

  return true
end
air_loop_hvac_energy_recovery?(air_loop_hvac) click to toggle source

Determine if the system has energy recovery already

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if an ERV is present, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2640
def air_loop_hvac_energy_recovery?(air_loop_hvac)
  has_erv = false

  # Get the OA system
  oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
  return false unless oa_sys.is_initialized

  # Find any ERV on the OA system
  oa_sys = oa_sys.get
  oa_sys.oaComponents.each do |oa_comp|
    if oa_comp.to_HeatExchangerAirToAirSensibleAndLatent.is_initialized
      has_erv = true
    end
  end

  return has_erv
end
air_loop_hvac_energy_recovery_ventilator_flow_limit(air_loop_hvac, climate_zone, pct_oa) click to toggle source

Determine the airflow limits that govern whether or not an ERV is required. Based on climate zone and % OA. Defaults to DOE Ref Pre-1980, not required.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param pct_oa [Double] percentage of outdoor air @return [Double] the flow rate above which an ERV is required. if nil, ERV is never required.

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1749
def air_loop_hvac_energy_recovery_ventilator_flow_limit(air_loop_hvac, climate_zone, pct_oa)
  erv_cfm = nil # Not required
  return erv_cfm
end
air_loop_hvac_energy_recovery_ventilator_heat_exchanger_type(air_loop_hvac) click to toggle source

Determine whether to use a Plate-Frame or Rotary Wheel style ERV depending on air loop outdoor air flow rate Defaults to Rotary.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [String] the erv type

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1771
def air_loop_hvac_energy_recovery_ventilator_heat_exchanger_type(air_loop_hvac)
  heat_exchanger_type = 'Rotary'
  return heat_exchanger_type
end
air_loop_hvac_energy_recovery_ventilator_required?(air_loop_hvac, climate_zone) click to toggle source

Check if ERV is required on this airloop.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if required, false if not @todo Add exception logic for systems serving parking garage, warehouse, or multifamily

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1643
def air_loop_hvac_energy_recovery_ventilator_required?(air_loop_hvac, climate_zone)
  # ERV Not Applicable for AHUs that serve
  # parking garage, warehouse, or multifamily
  # if space_types_served_names.include?('PNNL_Asset_Rating_Apartment_Space_Type') ||
  # space_types_served_names.include?('PNNL_Asset_Rating_LowRiseApartment_Space_Type') ||
  # space_types_served_names.include?('PNNL_Asset_Rating_ParkingGarage_Space_Type') ||
  # space_types_served_names.include?('PNNL_Asset_Rating_Warehouse_Space_Type')
  # OpenStudio::logFree(OpenStudio::Info, "openstudio.standards.AirLoopHVAC", "For #{self.name}, ERV not applicable because it because it serves parking garage, warehouse, or multifamily.")
  # return false
  # end

  erv_required = nil
  # ERV not applicable for medical AHUs (AHU1 in Outpatient), per AIA 2001 - 7.31.D2.
  # @todo refactor: move building type specific code
  if air_loop_hvac.name.to_s.include? 'Outpatient F1'
    erv_required = false
    return erv_required
  end

  # ERV not applicable for medical AHUs, per AIA 2001 - 7.31.D2.
  if air_loop_hvac.name.to_s.include? 'VAV_ER'
    erv_required = false
    return erv_required
  elsif air_loop_hvac.name.to_s.include? 'VAV_OR'
    erv_required = false
    return erv_required
  end
  case template
  when '90.1-2004', '90.1-2007'
    # @todo Refactor figure out how to remove this.
    if air_loop_hvac.name.to_s.include? 'VAV_ICU'
      erv_required = false
      return erv_required
    elsif air_loop_hvac.name.to_s.include? 'VAV_PATRMS'
      erv_required = false
      return erv_required
    end
  end

  # ERV Not Applicable for AHUs that have DCV or that have no OA intake.
  if air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized
    oa_system = air_loop_hvac.airLoopHVACOutdoorAirSystem.get
    controller_oa = oa_system.getControllerOutdoorAir
    controller_mv = controller_oa.controllerMechanicalVentilation
    if controller_mv.demandControlledVentilation == true
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, ERV not applicable because DCV enabled.")
      return false
    end
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, ERV not applicable because it has no OA intake.")
    return false
  end

  # Get the AHU design supply air flow rate
  dsn_flow_m3_per_s = nil
  if air_loop_hvac.designSupplyAirFlowRate.is_initialized
    dsn_flow_m3_per_s = air_loop_hvac.designSupplyAirFlowRate.get
  elsif air_loop_hvac.autosizedDesignSupplyAirFlowRate.is_initialized
    dsn_flow_m3_per_s = air_loop_hvac.autosizedDesignSupplyAirFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} design supply air flow rate is not available, cannot apply efficiency standard.")
    return false
  end
  dsn_flow_cfm = OpenStudio.convert(dsn_flow_m3_per_s, 'm^3/s', 'cfm').get

  # Get the minimum OA flow rate
  min_oa_flow_m3_per_s = nil
  if controller_oa.minimumOutdoorAirFlowRate.is_initialized
    min_oa_flow_m3_per_s = controller_oa.minimumOutdoorAirFlowRate.get
  elsif controller_oa.autosizedMinimumOutdoorAirFlowRate.is_initialized
    min_oa_flow_m3_per_s = controller_oa.autosizedMinimumOutdoorAirFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{controller_oa.name}: minimum OA flow rate is not available, cannot apply efficiency standard.")
    return false
  end
  min_oa_flow_cfm = OpenStudio.convert(min_oa_flow_m3_per_s, 'm^3/s', 'cfm').get

  # Calculate the percent OA at design airflow
  pct_oa = min_oa_flow_m3_per_s / dsn_flow_m3_per_s

  # Determine the airflow limit
  erv_cfm = air_loop_hvac_energy_recovery_ventilator_flow_limit(air_loop_hvac, climate_zone, pct_oa)

  # Determine if an ERV is required
  if erv_cfm.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, ERV not required based on #{(pct_oa * 100).round}% OA flow, design supply air flow of #{dsn_flow_cfm.round}cfm, and climate zone #{climate_zone}.")
    erv_required = false
  elsif dsn_flow_cfm < erv_cfm
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, ERV not required based on #{(pct_oa * 100).round}% OA flow, design supply air flow of #{dsn_flow_cfm.round}cfm, and climate zone #{climate_zone}. Does not exceed minimum flow requirement of #{erv_cfm}cfm.")
    erv_required = false
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, ERV required based on #{(pct_oa * 100).round}% OA flow, design supply air flow of #{dsn_flow_cfm.round}cfm, and climate zone #{climate_zone}. Exceeds minimum flow requirement of #{erv_cfm}cfm.")
    erv_required = true
  end

  return erv_required
end
air_loop_hvac_energy_recovery_ventilator_type(air_loop_hvac, climate_zone) click to toggle source

Determine whether to apply an Energy Recovery Ventilator ‘ERV’ or a Heat Recovery Ventilator ‘HRV’ depending on the climate zone Defaults to ERV.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [String] the erv type

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1761
def air_loop_hvac_energy_recovery_ventilator_type(air_loop_hvac, climate_zone)
  erv_type = 'ERV'
  return erv_type
end
air_loop_hvac_fan_power_limitation_pressure_drop_adjustment_brake_horsepower(air_loop_hvac) click to toggle source

Determine the fan power limitation pressure drop adjustment Per Table 6.5.3.1.1B

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Double] fan power limitation pressure drop adjustment, in units of horsepower @todo Determine the presence of MERV filters and other stuff in Table 6.5.3.1.1B. May need to extend AirLoopHVAC data model

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 433
def air_loop_hvac_fan_power_limitation_pressure_drop_adjustment_brake_horsepower(air_loop_hvac)
  # Get design supply air flow rate (whether autosized or hard-sized)
  dsn_air_flow_m3_per_s = 0
  dsn_air_flow_cfm = 0
  if air_loop_hvac.designSupplyAirFlowRate.is_initialized
    dsn_air_flow_m3_per_s = air_loop_hvac.designSupplyAirFlowRate.get
    dsn_air_flow_cfm = OpenStudio.convert(dsn_air_flow_m3_per_s, 'm^3/s', 'cfm').get
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "* #{dsn_air_flow_cfm.round} cfm = Hard sized Design Supply Air Flow Rate.")
  elsif air_loop_hvac.autosizedDesignSupplyAirFlowRate.is_initialized
    dsn_air_flow_m3_per_s = air_loop_hvac.autosizedDesignSupplyAirFlowRate.get
    dsn_air_flow_cfm = OpenStudio.convert(dsn_air_flow_m3_per_s, 'm^3/s', 'cfm').get
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "* #{dsn_air_flow_cfm.round} cfm = Autosized Design Supply Air Flow Rate.")
  end

  # @todo determine the presence of MERV filters and other stuff
  # in Table 6.5.3.1.1B
  # perhaps need to extend AirLoopHVAC data model
  has_fully_ducted_return_and_or_exhaust_air_systems = false
  has_merv_9_through_12 = false
  has_merv_13_through_15 = false

  # Calculate Fan Power Limitation Pressure Drop Adjustment (in wc)
  fan_pwr_adjustment_in_wc = 0

  # Fully ducted return and/or exhaust air systems
  if has_fully_ducted_return_and_or_exhaust_air_systems
    adj_in_wc = 0.5
    fan_pwr_adjustment_in_wc += adj_in_wc
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "--Added #{adj_in_wc} in wc for Fully ducted return and/or exhaust air systems")
  end

  # MERV 9 through 12
  if has_merv_9_through_12
    adj_in_wc = 0.5
    fan_pwr_adjustment_in_wc += adj_in_wc
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "--Added #{adj_in_wc} in wc for Particulate Filtration Credit: MERV 9 through 12")
  end

  # MERV 13 through 15
  if has_merv_13_through_15
    adj_in_wc = 0.9
    fan_pwr_adjustment_in_wc += adj_in_wc
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "--Added #{adj_in_wc} in wc for Particulate Filtration Credit: MERV 13 through 15")
  end

  # Convert the pressure drop adjustment to brake horsepower (bhp)
  # assuming that all supply air passes through all devices
  fan_pwr_adjustment_bhp = fan_pwr_adjustment_in_wc * dsn_air_flow_cfm / 4131
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Fan Power Limitation Pressure Drop Adjustment = #{fan_pwr_adjustment_bhp.round(2)} bhp")

  return fan_pwr_adjustment_bhp
end
air_loop_hvac_find_design_supply_air_flow_rate(air_loop_hvac) click to toggle source

find design_supply_air_flow_rate

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Double] design supply air flow rate in m^3/s

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3460
def air_loop_hvac_find_design_supply_air_flow_rate(air_loop_hvac)
  # Get the design_supply_air_flow_rate
  design_supply_air_flow_rate = nil
  if air_loop_hvac.designSupplyAirFlowRate.is_initialized
    design_supply_air_flow_rate = air_loop_hvac.designSupplyAirFlowRate.get
  elsif air_loop_hvac.autosizedDesignSupplyAirFlowRate.is_initialized
    design_supply_air_flow_rate = air_loop_hvac.autosizedDesignSupplyAirFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} design supply air flow rate is not available.")
  end

  return design_supply_air_flow_rate
end
air_loop_hvac_floor_area_served(air_loop_hvac) click to toggle source

Calculate the total floor area of all zones attached to the air loop, in m^2.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop return [Double] the total floor area of all zones attached to the air loop in m^2.

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3412
def air_loop_hvac_floor_area_served(air_loop_hvac)
  total_area = 0.0

  air_loop_hvac.thermalZones.each do |zone|
    total_area += zone.floorArea
  end

  return total_area
end
air_loop_hvac_floor_area_served_exterior_zones(air_loop_hvac) click to toggle source

Calculate the total floor area of all zones attached to the air loop that have at least one exterior surface, in m^2.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop return [Double] the total floor area of all zones attached to the air loop in m^2.

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3443
def air_loop_hvac_floor_area_served_exterior_zones(air_loop_hvac)
  total_area = 0.0

  air_loop_hvac.thermalZones.each do |zone|
    # Skip zones that have no exterior surface area
    next if zone.exteriorSurfaceArea.zero?

    total_area += zone.floorArea
  end

  return total_area
end
air_loop_hvac_floor_area_served_interior_zones(air_loop_hvac) click to toggle source

Calculate the total floor area of all zones attached to the air loop that have no exterior surfaces, in m^2.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop return [Double] the total floor area of all zones attached to the air loop in m^2.

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3426
def air_loop_hvac_floor_area_served_interior_zones(air_loop_hvac)
  total_area = 0.0

  air_loop_hvac.thermalZones.each do |zone|
    # Skip zones that have exterior surface area
    next if zone.exteriorSurfaceArea > 0

    total_area += zone.floorArea
  end

  return total_area
end
air_loop_hvac_get_occupancy_schedule(air_loop_hvac, occupied_percentage_threshold: 0.05) click to toggle source

This method creates a new discrete fractional schedule ruleset. The value is set to one when occupancy across all zones is greater than or equal to the occupied_percentage_threshold, and zero all other times. This method is designed to use the total number of people on the airloop, so if there is a zone that is continuously occupied by a few people, but other zones that are intermittently occupied by many people, the first zone doesn’t drive the entire system.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param occupied_percentage_threshold [Double] the minimum fraction (0 to 1) that counts as occupied @return [ScheduleRuleset] a ScheduleRuleset where 0 = unoccupied, 1 = occupied

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2901
def air_loop_hvac_get_occupancy_schedule(air_loop_hvac, occupied_percentage_threshold: 0.05)
  # Create combined occupancy schedule of every space in every zone served by this airloop
  sch_ruleset = OpenstudioStandards::ThermalZone.thermal_zones_get_occupancy_schedule(air_loop_hvac.thermalZones,
                                                                                      sch_name: "#{air_loop_hvac.name} Occ Sch",
                                                                                      occupied_percentage_threshold: occupied_percentage_threshold)
  return sch_ruleset
end
air_loop_hvac_get_relief_fan_power(air_loop) click to toggle source

Get relief fan power for airloop

@param air_loop [OpenStudio::Model::AirLoopHVAC] AirLoopHVAC object @return [Double] Fan power

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3831
def air_loop_hvac_get_relief_fan_power(air_loop)
  relief_fan_power = 0

  if air_loop.reliefFan.is_initialized
    # Get return fan
    fan = air_loop.reliefFan.get

    # Get fan object
    if fan.to_FanConstantVolume.is_initialized
      fan = fan.to_FanConstantVolume.get
    elsif fan.to_FanVariableVolume.is_initialized
      fan = fan.to_FanVariableVolume.get
    elsif fan.to_FanOnOff.is_initialized
      fan = fan.to_FanOnOff.get
    end

    # Get fan power
    relief_fan_power += fan_fanpower(fan)
  end

  return relief_fan_power
end
air_loop_hvac_get_return_fan_power(air_loop) click to toggle source

Get return fan power for airloop

@param air_loop [OpenStudio::Model::AirLoopHVAC] AirLoopHVAC object @return [Double] Fan power

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3746
def air_loop_hvac_get_return_fan_power(air_loop)
  return_fan_power = 0

  if air_loop.returnFan.is_initialized
    # Get return fan
    fan = air_loop.returnFan.get

    # Get fan object
    if fan.to_FanConstantVolume.is_initialized
      fan = fan.to_FanConstantVolume.get
    elsif fan.to_FanVariableVolume.is_initialized
      fan = fan.to_FanVariableVolume.get
    elsif fan.to_FanOnOff.is_initialized
      fan = fan.to_FanOnOff.get
    end

    # Get fan power
    return_fan_power += fan_fanpower(fan)
  end

  return return_fan_power
end
air_loop_hvac_get_supply_fan(air_loop) click to toggle source

Get supply fan for airloop

@param air_loop [OpenStudio::Model::AirLoopHVAC] AirLoopHVAC object @return fan

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3791
def air_loop_hvac_get_supply_fan(air_loop)
  fan = nil
  if air_loop.supplyFan.is_initialized
    # Get return fan
    fan = air_loop.supplyFan.get

    # Get fan object
    if fan.to_FanConstantVolume.is_initialized
      fan = fan.to_FanConstantVolume.get
    elsif fan.to_FanVariableVolume.is_initialized
      fan = fan.to_FanVariableVolume.get
    elsif fan.to_FanOnOff.is_initialized
      fan = fan.to_FanOnOff.get
    end

  else
    air_loop.supplyComponents.each do |comp|
      if comp.to_AirLoopHVACUnitarySystem.is_initialized
        fan = comp.to_AirLoopHVACUnitarySystem.get.supplyFan
        next if fan.empty?

        # Get fan object
        fan = fan.get
        if fan.to_FanConstantVolume.is_initialized
          fan = fan.to_FanConstantVolume.get
        elsif fan.to_FanVariableVolume.is_initialized
          fan = fan.to_FanVariableVolume.get
        elsif fan.to_FanOnOff.is_initialized
          fan = fan.to_FanOnOff.get
        end
      end
    end
  end
  return fan
end
air_loop_hvac_get_supply_fan_power(air_loop) click to toggle source

Get supply fan power for airloop

@param air_loop [OpenStudio::Model::AirLoopHVAC] AirLoopHVAC object @return [Double] Fan power

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3773
def air_loop_hvac_get_supply_fan_power(air_loop)
  supply_fan_power = 0

  # Get fan
  fan = air_loop_hvac_get_supply_fan(air_loop)

  if !fan.nil?
    # Get fan power
    supply_fan_power += fan_fanpower(fan)
  end

  return supply_fan_power
end
air_loop_hvac_has_parallel_piu_air_terminals?(air_loop_hvac) click to toggle source

Determine if the air loop serves parallel PIU air terminals

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3325
def air_loop_hvac_has_parallel_piu_air_terminals?(air_loop_hvac)
  has_parallel_piu_terminals = false
  air_loop_hvac.thermalZones.each do |zone|
    zone.equipment.each do |equipment|
      # Get the object type
      obj_type = equipment.iddObjectType.valueName.to_s
      if obj_type == 'OS_AirTerminal_SingleDuct_ParallelPIU_Reheat'
        return true
      end
    end
  end

  return has_parallel_piu_terminals
end
air_loop_hvac_has_simple_transfer_air?(air_loop_hvac) click to toggle source

Checks if zones served by the air loop use zone exhaust fan a simplified approach to model transfer air

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] OpenStudio AirLoopHVAC object @return [Boolean] true if simple transfer air is modeled, false otherwise

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3889
def air_loop_hvac_has_simple_transfer_air?(air_loop_hvac)
  simple_transfer_air = false
  zones = air_loop_hvac.thermalZones
  zones_name = []
  zones.each do |zone|
    zones_name << zone.name.to_s
  end
  air_loop_hvac.model.getFanZoneExhausts.sort.each do |exhaust_fan|
    if (zones_name.include? exhaust_fan.thermalZone.get.name.to_s) && exhaust_fan.balancedExhaustFractionSchedule.is_initialized
      simple_transfer_air = true
    end
  end
  return simple_transfer_air
end
air_loop_hvac_humidifier_count(air_loop_hvac) click to toggle source

Determine how many humidifies are on the airloop

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Integer] the number of humidifiers

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3539
def air_loop_hvac_humidifier_count(air_loop_hvac)
  humidifiers = 0
  air_loop_hvac.supplyComponents.each do |cmp|
    if cmp.to_HumidifierSteamElectric.is_initialized
      humidifiers += 1
    end
  end
  return humidifiers
end
air_loop_hvac_include_cooling_coil?(air_loop_hvac) click to toggle source

Determine if the airloop includes cooling coils

@return [Boolean] returns true if cooling coils are included on the airloop

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1190
def air_loop_hvac_include_cooling_coil?(air_loop_hvac)
  air_loop_hvac.supplyComponents.each do |comp|
    return true if comp.to_CoilCoolingWater.is_initialized
    return true if comp.to_CoilCoolingWater.is_initialized
    return true if comp.to_CoilCoolingCooledBeam.is_initialized
    return true if comp.to_CoilCoolingDXMultiSpeed.is_initialized
    return true if comp.to_CoilCoolingDXSingleSpeed.is_initialized
    return true if comp.to_CoilCoolingDXTwoSpeed.is_initialized
    return true if comp.to_CoilCoolingDXTwoStageWithHumidityControlMode.is_initialized
    return true if comp.to_CoilCoolingDXVariableRefrigerantFlow.is_initialized
    return true if comp.to_CoilCoolingDXVariableSpeed.is_initialized
    return true if comp.to_CoilCoolingFourPipeBeam.is_initialized
    return true if comp.to_CoilCoolingLowTempRadiantConstFlow.is_initialized
    return true if comp.to_CoilCoolingLowTempRadiantVarFlow.is_initialized
    return true if comp.to_CoilCoolingWater.is_initialized
    return true if comp.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized
    return true if comp.to_CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFit.is_initialized

    if comp.to_AirLoopHVACUnitarySystem.is_initialized
      unitary_system = comp.to_AirLoopHVACUnitarySystem.get
      if unitary_system.coolingCoil.is_initialized
        cooling_coil = unitary_system.coolingCoil.get
        return true if cooling_coil.to_CoilCoolingWater.is_initialized
        return true if cooling_coil.to_CoilCoolingWater.is_initialized
        return true if cooling_coil.to_CoilCoolingCooledBeam.is_initialized
        return true if cooling_coil.to_CoilCoolingDXMultiSpeed.is_initialized
        return true if cooling_coil.to_CoilCoolingDXSingleSpeed.is_initialized
        return true if cooling_coil.to_CoilCoolingDXTwoSpeed.is_initialized
        return true if cooling_coil.to_CoilCoolingDXTwoStageWithHumidityControlMode.is_initialized
        return true if cooling_coil.to_CoilCoolingDXVariableRefrigerantFlow.is_initialized
        return true if cooling_coil.to_CoilCoolingDXVariableSpeed.is_initialized
        return true if cooling_coil.to_CoilCoolingFourPipeBeam.is_initialized
        return true if cooling_coil.to_CoilCoolingLowTempRadiantConstFlow.is_initialized
        return true if cooling_coil.to_CoilCoolingLowTempRadiantVarFlow.is_initialized
        return true if cooling_coil.to_CoilCoolingWater.is_initialized
        return true if cooling_coil.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized
        return true if cooling_coil.to_CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFit.is_initialized
      end
    end
  end
  return false
end
air_loop_hvac_include_economizer?(air_loop_hvac) click to toggle source

Determine if the airloop includes an air-economizer

@return [Boolean] returns true if the airloop has an air-economizer

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1247
def air_loop_hvac_include_economizer?(air_loop_hvac)
  return false unless air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized

  # Get OA system
  air_loop_hvac_oa_system = air_loop_hvac.airLoopHVACOutdoorAirSystem.get

  # Get OA controller
  air_loop_hvac_oa_controller = air_loop_hvac_oa_system.getControllerOutdoorAir

  # Get economizer type
  economizer_type = air_loop_hvac_oa_controller.getEconomizerControlType.to_s
  return false if economizer_type == 'NoEconomizer'

  return true
end
air_loop_hvac_include_evaporative_cooler?(air_loop_hvac) click to toggle source

Determine if the airloop includes evaporative coolers

@return [Boolean] returns true if evaporative coolers are included on the airloop

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1236
def air_loop_hvac_include_evaporative_cooler?(air_loop_hvac)
  air_loop_hvac.supplyComponents.each do |comp|
    return true if comp.to_EvaporativeCoolerDirectResearchSpecial.is_initialized
    return true if comp.to_EvaporativeCoolerIndirectResearchSpecial.is_initialized
  end
  return false
end
air_loop_hvac_include_hydronic_cooling_coil?(air_loop_hvac) click to toggle source

Determine if the airloop includes hydronic cooling coils

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if hydronic cooling coils are included on the airloop

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1180
def air_loop_hvac_include_hydronic_cooling_coil?(air_loop_hvac)
  air_loop_hvac.supplyComponents.each do |comp|
    return true if comp.to_CoilCoolingWater.is_initialized
  end
  return false
end
air_loop_hvac_include_unitary_system?(air_loop_hvac) click to toggle source

Determine if the air loop includes a unitary system

@return [Boolean] returns true if a unitary system is included on the air loop

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1283
def air_loop_hvac_include_unitary_system?(air_loop_hvac)
  air_loop_hvac.supplyComponents.each do |comp|
    return true if comp.to_AirLoopHVACUnitarySystem.is_initialized
  end

  return false
end
air_loop_hvac_include_wshp?(air_loop_hvac) click to toggle source

Determine if the airloop includes WSHP cooling coils

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if WSHP cooling coils are included on the airloop

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1267
def air_loop_hvac_include_wshp?(air_loop_hvac)
  air_loop_hvac.supplyComponents.each do |comp|
    return true if comp.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized

    if comp.to_AirLoopHVACUnitarySystem.is_initialized
      clg_coil = comp.to_AirLoopHVACUnitarySystem.get.coolingCoil.get
      return true if clg_coil.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized

    end
  end
  return false
end
air_loop_hvac_integrated_economizer_required?(air_loop_hvac, climate_zone) click to toggle source

Determine if the system economizer must be integrated or not. Default logic is from 90.1-2004.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1297
def air_loop_hvac_integrated_economizer_required?(air_loop_hvac, climate_zone)
  # Determine if it is a VAV system
  is_vav = air_loop_hvac_vav_system?(air_loop_hvac)

  # Determine the number of zones the system serves
  num_zones_served = air_loop_hvac.thermalZones.size

  minimum_capacity_btu_per_hr = 65_000
  minimum_capacity_w = OpenStudio.convert(minimum_capacity_btu_per_hr, 'Btu/hr', 'W').get
  # 6.5.1.3 Integrated Economizer Control
  # Exception a, DX VAV systems
  if is_vav == true && num_zones_served > 1
    integrated_economizer_required = false
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: non-integrated economizer per 6.5.1.3 exception a, DX VAV system.")
    # Exception b, DX units less than 65,000 Btu/hr
  elsif air_loop_hvac_total_cooling_capacity(air_loop_hvac) < minimum_capacity_w
    integrated_economizer_required = false
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: non-integrated economizer per 6.5.1.3 exception b, DX system less than #{minimum_capacity_btu_per_hr}Btu/hr.")
  else
    # Exception c, Systems in climate zones 1,2,3a,4a,5a,5b,6,7,8
    case climate_zone
    when 'ASHRAE 169-2006-0A',
         'ASHRAE 169-2006-0B',
         'ASHRAE 169-2006-1A',
         'ASHRAE 169-2006-1B',
         'ASHRAE 169-2006-2A',
         'ASHRAE 169-2006-2B',
         'ASHRAE 169-2006-3A',
         'ASHRAE 169-2006-4A',
         'ASHRAE 169-2006-5A',
         'ASHRAE 169-2006-5B',
         'ASHRAE 169-2006-6A',
         'ASHRAE 169-2006-6B',
         'ASHRAE 169-2006-7A',
         'ASHRAE 169-2006-7B',
         'ASHRAE 169-2006-8A',
         'ASHRAE 169-2006-8B',
         'ASHRAE 169-2013-0A',
         'ASHRAE 169-2013-0B',
         'ASHRAE 169-2013-1A',
         'ASHRAE 169-2013-1B',
         'ASHRAE 169-2013-2A',
         'ASHRAE 169-2013-2B',
         'ASHRAE 169-2013-3A',
         'ASHRAE 169-2013-4A',
         'ASHRAE 169-2013-5A',
         'ASHRAE 169-2013-5B',
         'ASHRAE 169-2013-6A',
         'ASHRAE 169-2013-6B',
         'ASHRAE 169-2013-7A',
         'ASHRAE 169-2013-7B',
         'ASHRAE 169-2013-8A',
         'ASHRAE 169-2013-8B'
      integrated_economizer_required = false
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: non-integrated economizer per 6.5.1.3 exception c, climate zone #{climate_zone}.")
    when 'ASHRAE 169-2006-3B',
         'ASHRAE 169-2006-3C',
         'ASHRAE 169-2006-4B',
         'ASHRAE 169-2006-4C',
         'ASHRAE 169-2006-5C',
         'ASHRAE 169-2013-3B',
         'ASHRAE 169-2013-3C',
         'ASHRAE 169-2013-4B',
         'ASHRAE 169-2013-4C',
         'ASHRAE 169-2013-5C'
      integrated_economizer_required = true
    end
  end

  return integrated_economizer_required
end
air_loop_hvac_minimum_zone_ventilation_efficiency(air_loop_hvac) click to toggle source

Determine minimum ventilation efficiency for zones. This is used to decrease the overall system minimum OA flow rate such that a few zones do not drive the overall system OA flow rate too high.

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1969
def air_loop_hvac_minimum_zone_ventilation_efficiency(air_loop_hvac)
  min_ventilation_efficiency = 0.6

  return min_ventilation_efficiency
end
air_loop_hvac_motorized_oa_damper_limits(air_loop_hvac, climate_zone) click to toggle source

Determine the air flow and number of story limits for whether motorized OA damper is required. Defaults to DOE Ref Pre-1980 logic (never required).

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Array<Double>] [minimum_oa_flow_cfm, maximum_stories]. If both nil, never required

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2814
def air_loop_hvac_motorized_oa_damper_limits(air_loop_hvac, climate_zone)
  minimum_oa_flow_cfm = nil
  maximum_stories = nil
  return [minimum_oa_flow_cfm, maximum_stories]
end
air_loop_hvac_motorized_oa_damper_required?(air_loop_hvac, climate_zone) click to toggle source

Determine if a motorized OA damper is required

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2738
def air_loop_hvac_motorized_oa_damper_required?(air_loop_hvac, climate_zone)
  motorized_oa_damper_required = false

  # @todo refactor: Remove building type dependent logic
  if air_loop_hvac.name.to_s.include? 'Outpatient F1'
    motorized_oa_damper_required = true
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: always has a damper, the minimum OA schedule is the same as airloop availability schedule.")
    return motorized_oa_damper_required
  end

  # If the system has an economizer, it must have a motorized damper.
  if air_loop_hvac_economizer?(air_loop_hvac)
    motorized_oa_damper_required = true
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Because the system has an economizer, it requires a motorized OA damper.")
    return motorized_oa_damper_required
  end

  # Determine the exceptions based on
  # number of stories, climate zone, and
  # outdoor air intake rates.
  minimum_oa_flow_cfm, maximum_stories = air_loop_hvac_motorized_oa_damper_limits(air_loop_hvac, climate_zone)

  # Assuming that buildings not requiring this always
  # used backdraft gravity dampers
  if minimum_oa_flow_cfm.nil? && maximum_stories.nil?
    return motorized_oa_damper_required
  end

  # Get the number of stories
  num_stories = air_loop_hvac.model.getBuildingStorys.size

  # Check the number of stories exception,
  # which is climate-zone dependent.
  if num_stories < maximum_stories
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Motorized OA damper not required because the building has #{num_stories} stories, less than the minimum of #{maximum_stories} stories for climate zone #{climate_zone}.")
    return motorized_oa_damper_required
  end

  # Get the min OA flow rate
  oa_flow_m3_per_s = 0
  if air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized
    oa_system = air_loop_hvac.airLoopHVACOutdoorAirSystem.get
    controller_oa = oa_system.getControllerOutdoorAir
    if controller_oa.minimumOutdoorAirFlowRate.is_initialized
      oa_flow_m3_per_s = controller_oa.minimumOutdoorAirFlowRate.get
    elsif controller_oa.autosizedMinimumOutdoorAirFlowRate.is_initialized
      oa_flow_m3_per_s = controller_oa.autosizedMinimumOutdoorAirFlowRate.get
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Could not determine the minimum OA flow rate, cannot determine if a motorized OA damper is required.")
      return motorized_oa_damper_required
    end
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, Motorized OA damper not applicable because it has no OA intake.")
    return motorized_oa_damper_required
  end
  oa_flow_cfm = OpenStudio.convert(oa_flow_m3_per_s, 'm^3/s', 'cfm').get

  # Check the OA flow rate exception
  if oa_flow_cfm < minimum_oa_flow_cfm
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Motorized OA damper not required because the system OA intake of #{oa_flow_cfm.round} cfm is less than the minimum threshold of #{minimum_oa_flow_cfm} cfm.")
    return motorized_oa_damper_required
  end

  # If here, motorized damper is required
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Motorized OA damper is required because the building has #{num_stories} stories which is greater than or equal to the minimum of #{maximum_stories} stories for climate zone #{climate_zone}, and the system OA intake of #{oa_flow_cfm.round} cfm is greater than or equal to the minimum threshold of #{minimum_oa_flow_cfm} cfm. ")
  motorized_oa_damper_required = true

  return motorized_oa_damper_required
end
air_loop_hvac_multi_stage_dx_cooling?(air_loop_hvac) click to toggle source

Determine if this Air Loop uses multi-stage DX cooling.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if uses multi-stage DX cooling, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3702
def air_loop_hvac_multi_stage_dx_cooling?(air_loop_hvac)
  dx_clg = false

  # Check for all DX coil types
  dx_types = [
    'OS_Coil_Cooling_DX_MultiSpeed',
    'OS_Coil_Cooling_DX_TwoSpeed',
    'OS_Coil_Cooling_DX_TwoStageWithHumidityControlMode'
  ]

  air_loop_hvac.supplyComponents.each do |component|
    # Get the object type, getting the internal coil
    # type if inside a unitary system.
    obj_type = component.iddObjectType.valueName.to_s
    case obj_type
    when 'OS_AirLoopHVAC_UnitaryHeatCool_VAVChangeoverBypass'
      component = component.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.get
      obj_type = component.coolingCoil.iddObjectType.valueName.to_s
    when 'OS_AirLoopHVAC_UnitaryHeatPump_AirToAir'
      component = component.to_AirLoopHVACUnitaryHeatPumpAirToAir.get
      obj_type = component.coolingCoil.iddObjectType.valueName.to_s
    when 'OS_AirLoopHVAC_UnitaryHeatPump_AirToAir_MultiSpeed'
      component = component.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.get
      obj_type = component.coolingCoil.iddObjectType.valueName.to_s
    when 'OS_AirLoopHVAC_UnitarySystem'
      component = component.to_AirLoopHVACUnitarySystem.get
      if component.coolingCoil.is_initialized
        obj_type = component.coolingCoil.get.iddObjectType.valueName.to_s
      end
    end
    # See if the object type is a DX coil
    if dx_types.include?(obj_type)
      dx_clg = true
      break # Stop if find a DX coil
    end
  end

  return dx_clg
end
air_loop_hvac_multizone_vav_optimization_required?(air_loop_hvac, climate_zone) click to toggle source

Determine if multizone vav optimization is required. Defaults to 90.1-2007 logic, where it is not required.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if required, false if not @todo Add exception logic for systems with AIA healthcare ventilation requirements dual duct systems

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1915
def air_loop_hvac_multizone_vav_optimization_required?(air_loop_hvac, climate_zone)
  multizone_opt_required = false
  return multizone_opt_required
end
air_loop_hvac_multizone_vav_system?(air_loop_hvac) click to toggle source

Determine if the system is a multizone VAV system

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if multizone vav, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2596
def air_loop_hvac_multizone_vav_system?(air_loop_hvac)
  multizone_vav_system = false

  # Must serve more than 1 zone
  if air_loop_hvac.thermalZones.size < 2
    return multizone_vav_system
  end

  # Must be a variable volume system
  is_vav = air_loop_hvac_vav_system?(air_loop_hvac)
  if is_vav == false
    return multizone_vav_system
  end

  # If here, it's a multizone VAV system
  multizone_vav_system = true

  return multizone_vav_system
end
air_loop_hvac_optimum_start_required?(air_loop_hvac) click to toggle source

Determines if optimum start control is required. Defaults to 90.1-2004 logic, which requires optimum start if > 10,000 cfm

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 237
def air_loop_hvac_optimum_start_required?(air_loop_hvac)
  opt_start_required = false

  # data centers don't require optimum start as generally not occupied
  return opt_start_required if air_loop_hvac.name.to_s.include?('CRAH') ||
                               air_loop_hvac.name.to_s.include?('CRAC')

  # Get design supply air flow rate (whether autosized or hard-sized)
  dsn_air_flow_m3_per_s = 0
  dsn_air_flow_cfm = 0
  if air_loop_hvac.designSupplyAirFlowRate.is_initialized
    dsn_air_flow_m3_per_s = air_loop_hvac.designSupplyAirFlowRate.get
    dsn_air_flow_cfm = OpenStudio.convert(dsn_air_flow_m3_per_s, 'm^3/s', 'cfm').get
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "* #{dsn_air_flow_cfm.round} cfm = Hard sized Design Supply Air Flow Rate.")
  elsif air_loop_hvac.autosizedDesignSupplyAirFlowRate.is_initialized
    dsn_air_flow_m3_per_s = air_loop_hvac.autosizedDesignSupplyAirFlowRate.get
    dsn_air_flow_cfm = OpenStudio.convert(dsn_air_flow_m3_per_s, 'm^3/s', 'cfm').get
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirLoopHVAC', "* #{dsn_air_flow_cfm.round} cfm = Autosized Design Supply Air Flow Rate.")
  end
  # Optimum start per 6.4.3.3.3, only required if > 10,000 cfm
  cfm_limit = 10_000
  if dsn_air_flow_cfm > cfm_limit
    opt_start_required = true
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Optimum start is required since design flow rate of #{dsn_air_flow_cfm.round} cfm exceeds the limit of #{cfm_limit} cfm.")
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Optimum start is not required since design flow rate of #{dsn_air_flow_cfm.round} cfm is below the limit of #{cfm_limit} cfm.")
  end

  return opt_start_required
end
air_loop_hvac_prm_baseline_economizer_required?(air_loop_hvac, climate_zone) click to toggle source

Determine if an economizer is required per the PRM. Default logic from 90.1-2007

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1375
def air_loop_hvac_prm_baseline_economizer_required?(air_loop_hvac, climate_zone)
  economizer_required = false

  # A big number of ft2 as the minimum requirement
  infinity_ft2 = 999_999_999_999
  min_int_area_served_ft2 = infinity_ft2
  min_ext_area_served_ft2 = infinity_ft2

  # Determine the minimum capacity that requires an economizer
  case climate_zone
  when 'ASHRAE 169-2006-0A',
       'ASHRAE 169-2006-0B',
       'ASHRAE 169-2006-1A',
       'ASHRAE 169-2006-1B',
       'ASHRAE 169-2006-2A',
       'ASHRAE 169-2006-3A',
       'ASHRAE 169-2006-4A',
       'ASHRAE 169-2013-0A',
       'ASHRAE 169-2013-0B',
       'ASHRAE 169-2013-1A',
       'ASHRAE 169-2013-1B',
       'ASHRAE 169-2013-2A',
       'ASHRAE 169-2013-3A',
       'ASHRAE 169-2013-4A'
    min_int_area_served_ft2 = infinity_ft2 # No requirement
    min_ext_area_served_ft2 = infinity_ft2 # No requirement
  else
    min_int_area_served_ft2 = 0 # Always required
    min_ext_area_served_ft2 = 0 # Always required
  end

  # Check whether the system requires an economizer by comparing
  # the system capacity to the minimum capacity.
  min_int_area_served_m2 = OpenStudio.convert(min_int_area_served_ft2, 'ft^2', 'm^2').get
  min_ext_area_served_m2 = OpenStudio.convert(min_ext_area_served_ft2, 'ft^2', 'm^2').get

  # Get the interior and exterior area served
  int_area_served_m2 = air_loop_hvac_floor_area_served_interior_zones(air_loop_hvac)
  ext_area_served_m2 = air_loop_hvac_floor_area_served_exterior_zones(air_loop_hvac)

  # Check the floor area exception
  if int_area_served_m2 < min_int_area_served_m2 && ext_area_served_m2 < min_ext_area_served_m2
    if min_int_area_served_ft2 == infinity_ft2 && min_ext_area_served_ft2 == infinity_ft2
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Economizer not required for climate zone #{climate_zone}.")
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Economizer not required for because the interior area served of #{int_area_served_m2} ft2 is less than the minimum of #{min_int_area_served_m2} and the perimeter area served of #{ext_area_served_m2} ft2 is less than the minimum of #{min_ext_area_served_m2} for climate zone #{climate_zone}.")
    end
    return economizer_required
  end

  # If here, economizer required
  economizer_required = true
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Economizer required for the performance rating method baseline.")

  return economizer_required
end
air_loop_hvac_prm_economizer_type_and_limits(air_loop_hvac, climate_zone) click to toggle source

Determine the economizer type and limits for the the PRM Defaults to 90.1-2007 logic.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Array<Double>] [economizer_type, drybulb_limit_f, enthalpy_limit_btu_per_lb, dewpoint_limit_f]

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1500
def air_loop_hvac_prm_economizer_type_and_limits(air_loop_hvac, climate_zone)
  economizer_type = 'NoEconomizer'
  drybulb_limit_f = nil
  enthalpy_limit_btu_per_lb = nil
  dewpoint_limit_f = nil

  case climate_zone
  when 'ASHRAE 169-2006-0B',
       'ASHRAE 169-2006-1B',
       'ASHRAE 169-2006-2B',
       'ASHRAE 169-2006-3B',
       'ASHRAE 169-2006-3C',
       'ASHRAE 169-2006-4B',
       'ASHRAE 169-2006-4C',
       'ASHRAE 169-2006-5B',
       'ASHRAE 169-2006-5C',
       'ASHRAE 169-2006-6B',
       'ASHRAE 169-2006-7B',
       'ASHRAE 169-2006-8A',
       'ASHRAE 169-2006-8B',
       'ASHRAE 169-2013-0B',
       'ASHRAE 169-2013-1B',
       'ASHRAE 169-2013-2B',
       'ASHRAE 169-2013-3B',
       'ASHRAE 169-2013-3C',
       'ASHRAE 169-2013-4B',
       'ASHRAE 169-2013-4C',
       'ASHRAE 169-2013-5B',
       'ASHRAE 169-2013-5C',
       'ASHRAE 169-2013-6B',
       'ASHRAE 169-2013-7B',
       'ASHRAE 169-2013-8A',
       'ASHRAE 169-2013-8B'
    economizer_type = 'FixedDryBulb'
    drybulb_limit_f = 75
  when 'ASHRAE 169-2006-5A',
       'ASHRAE 169-2006-6A',
       'ASHRAE 169-2006-7A',
       'ASHRAE 169-2013-5A',
       'ASHRAE 169-2013-6A',
       'ASHRAE 169-2013-7A'
    economizer_type = 'FixedDryBulb'
    drybulb_limit_f = 70
  else
    economizer_type = 'FixedDryBulb'
    drybulb_limit_f = 65
  end

  return [economizer_type, drybulb_limit_f, enthalpy_limit_btu_per_lb, dewpoint_limit_f]
end
air_loop_hvac_remove_erv(air_loop_hvac) click to toggle source
# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 1776
def air_loop_hvac_remove_erv(air_loop_hvac)
  # Get the OA system
  oa_sys = nil
  if air_loop_hvac.airLoopHVACOutdoorAirSystem.is_initialized
    oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem.get
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}, ERV cannot be removed because the system has no OA intake.")
    return false
  end

  # Get the existing ERV or create an ERV and add it to the OA system
  oa_sys.oaComponents.each do |oa_comp|
    if oa_comp.to_HeatExchangerAirToAirSensibleAndLatent.is_initialized
      erv = oa_comp.to_HeatExchangerAirToAirSensibleAndLatent.get
      erv.remove
    end
  end

  return true
end
air_loop_hvac_remove_motorized_oa_damper(air_loop_hvac) click to toggle source

Remove a motorized OA damper by modifying the OA schedule to require full OA at all times. Whenever the fan operates, the damper will be open and OA will be brought into the building. This reflects the use of a backdraft gravity damper, and increases building loads unnecessarily during unoccupied hours.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2876
def air_loop_hvac_remove_motorized_oa_damper(air_loop_hvac)
  # Get the OA system and OA controller
  oa_sys = air_loop_hvac.airLoopHVACOutdoorAirSystem
  return false unless oa_sys.is_initialized

  oa_sys = oa_sys.get
  oa_control = oa_sys.getControllerOutdoorAir

  # Set the minimum OA schedule to always 1 (100%)
  oa_control.setMinimumOutdoorAirSchedule(air_loop_hvac.model.alwaysOnDiscreteSchedule)

  return true
end
air_loop_hvac_residential_area_served(air_loop_hvac) click to toggle source

Determine how much residential area the airloop serves

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Double] residential area served in m^2

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3478
def air_loop_hvac_residential_area_served(air_loop_hvac)
  res_area = 0.0

  air_loop_hvac.thermalZones.each do |zone|
    zone.spaces.each do |space|
      # Skip spaces with no space type
      next if space.spaceType.empty?

      space_type = space.spaceType.get

      # Skip spaces with no standards space type
      next if space_type.standardsSpaceType.empty?

      standards_space_type = space_type.standardsSpaceType.get
      if standards_space_type.downcase.include?('apartment') || standards_space_type.downcase.include?('guestroom') || standards_space_type.downcase.include?('patroom')
        res_area += space.floorArea
      end
    end
  end

  return res_area
end
air_loop_hvac_return_air_plenum(air_loop_hvac) click to toggle source

Get the return air plenum zone object for an air loop, if it exists

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] OpenStudio AirLoopHVAC object @return [OpenStudio::Model::ThermalZone] OpenStudio thermal zone object of the return air plenum zone

when an air loop uses a return air plenum, nil otherwise
# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3909
def air_loop_hvac_return_air_plenum(air_loop_hvac)
  # Get return air node
  return_air_node = air_loop_hvac.demandOutletNode

  # Check if node is connected to a return plenum object
  air_loop_hvac.model.getAirLoopHVACReturnPlenums.each do |return_plenum|
    air_loop_hvac.model.getAirLoopHVACZoneMixers.each do |zone_air_mixer|
      inlets = zone_air_mixer.inletModelObjects
      inlets.each do |inlet|
        if inlet.to_Node.get == return_plenum.outletModelObject.get.to_Node.get
          if zone_air_mixer.outletModelObject.get.to_Node.get == return_air_node
            return return_plenum.thermalZone.get
          end
        end
      end
    end
  end

  return nil
end
air_loop_hvac_set_minimum_damper_position(zone, mdp) click to toggle source

Set an air terminal’s minimum damper position

@param zone [OpenStudio::Model::ThermalZone] thermal zone @param mdp [Double] minimum damper position @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2244
def air_loop_hvac_set_minimum_damper_position(zone, mdp)
  zone.equipment.each do |equip|
    if equip.to_AirTerminalSingleDuctVAVHeatAndCoolNoReheat.is_initialized
      term = equip.to_AirTerminalSingleDuctVAVHeatAndCoolNoReheat.get
      term.setZoneMinimumAirFlowFraction(mdp)
    elsif equip.to_AirTerminalSingleDuctVAVHeatAndCoolReheat.is_initialized
      term = equip.to_AirTerminalSingleDuctVAVHeatAndCoolReheat.get
      term.setZoneMinimumAirFlowFraction(mdp)
    elsif equip.to_AirTerminalSingleDuctVAVNoReheat.is_initialized
      term = equip.to_AirTerminalSingleDuctVAVNoReheat.get
      term.setConstantMinimumAirFlowFraction(mdp)
    elsif equip.to_AirTerminalSingleDuctVAVReheat.is_initialized
      term = equip.to_AirTerminalSingleDuctVAVReheat.get
      term.setConstantMinimumAirFlowFraction(mdp)
    end
  end

  return true
end
air_loop_hvac_set_vsd_curve_type() click to toggle source

Set default fan curve to be VSD with static pressure reset @return [String name of appropriate curve for this code version

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 378
def air_loop_hvac_set_vsd_curve_type
  return 'Multi Zone VAV with VSD and SP Setpoint Reset'
end
air_loop_hvac_single_zone_controls_num_stages(air_loop_hvac, climate_zone) click to toggle source

Determine the number of stages that should be used as controls for single zone DX systems. Defaults to zero, which means that no special single zone control is required.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Integer] the number of stages: 0, 1, 2

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3269
def air_loop_hvac_single_zone_controls_num_stages(air_loop_hvac, climate_zone)
  num_stages = 0
  return num_stages
end
air_loop_hvac_standby_mode_occupancy_control(air_loop_hvac, standby_mode_spaces) click to toggle source

Add occupant standby controls to air loop When the thermostat schedule is setup or setback the ventilation is shutoff. Currently this is done by scheduling air terminal dampers (so load can still be met) and cycling unitary system fans

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] OpenStudio AirLoopHVAC object @param standby_mode_spaces [Array<OpenStudio::Model::Space>] List of all spaces required to have standby mode controls @return [Boolean] true if sucessful, false otherwise

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3863
def air_loop_hvac_standby_mode_occupancy_control(air_loop_hvac, standby_mode_spaces)
  return true
end
air_loop_hvac_static_pressure_reset_required?(air_loop_hvac, has_ddc) click to toggle source

Determine if static pressure reset is required for this system. For 90.1, this determination needs information about whether or not the system has DDC control over the VAV terminals. Defaults to 90.1-2007 logic.

@todo Instead of requiring the input of whether a system

has DDC control of VAV terminals or not, determine this
from the system itself.  This may require additional information
be added to the OpenStudio data model.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param has_ddc [Boolean] whether or not the system has DDC control over VAV terminals. return [Boolean] returns true if static pressure reset is required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3287
def air_loop_hvac_static_pressure_reset_required?(air_loop_hvac, has_ddc)
  sp_reset_required = false

  if has_ddc
    sp_reset_required = true
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Static pressure reset is required because the system has DDC control of VAV terminals.")
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: Static pressure reset not required because the system does not have DDC control of VAV terminals.")
  end

  return sp_reset_required
end
air_loop_hvac_supply_air_temperature_reset_required?(air_loop_hvac, climate_zone) click to toggle source

Determine if the system required supply air temperature (SAT) reset. Defaults to 90.1-2007, no SAT reset required.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2451
def air_loop_hvac_supply_air_temperature_reset_required?(air_loop_hvac, climate_zone)
  is_sat_reset_required = false
  return is_sat_reset_required
end
air_loop_hvac_supply_return_exhaust_relief_fans(air_loop_hvac) click to toggle source

Get all of the supply, return, exhaust, and relief fans on this system

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Array] an array of FanConstantVolume, FanVariableVolume, and FanOnOff objects

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 589
def air_loop_hvac_supply_return_exhaust_relief_fans(air_loop_hvac)
  # Fans on the supply side of the airloop directly, or inside of unitary equipment.
  fans = []
  sup_and_oa_comps = air_loop_hvac.supplyComponents
  sup_and_oa_comps += air_loop_hvac.oaComponents
  sup_and_oa_comps.each do |comp|
    if comp.to_FanConstantVolume.is_initialized
      fans << comp.to_FanConstantVolume.get
    elsif comp.to_FanVariableVolume.is_initialized
      fans << comp.to_FanVariableVolume.get
    elsif comp.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.is_initialized
      sup_fan = comp.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.get.supplyAirFan
      if sup_fan.to_FanConstantVolume.is_initialized
        fans << sup_fan.to_FanConstantVolume.get
      elsif sup_fan.to_FanOnOff.is_initialized
        fans << sup_fan.to_FanOnOff.get
      end
    elsif comp.to_AirLoopHVACUnitarySystem.is_initialized
      sup_fan = comp.to_AirLoopHVACUnitarySystem.get.supplyFan
      next if sup_fan.empty?

      sup_fan = sup_fan.get
      if sup_fan.to_FanConstantVolume.is_initialized
        fans << sup_fan.to_FanConstantVolume.get
      elsif sup_fan.to_FanOnOff.is_initialized
        fans << sup_fan.to_FanOnOff.get
      elsif sup_fan.to_FanVariableVolume.is_initialized
        fans << sup_fan.to_FanVariableVolume.get
      end
    end
  end

  return fans
end
air_loop_hvac_system_fan_brake_horsepower(air_loop_hvac, include_terminal_fans = true) click to toggle source

Determine the total brake horsepower of the fans on the system with or without the fans inside of fan powered terminals.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @param include_terminal_fans [Boolean] if true, power from fan powered terminals will be included @return [Double] total brake horsepower of the fans on the system, in units of horsepower

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 630
def air_loop_hvac_system_fan_brake_horsepower(air_loop_hvac, include_terminal_fans = true)
  # @todo get the template from the parent model itself?
  # Or not because maybe you want to see the difference between two standards?
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name}-Determining #{template} allowable system fan power.")

  # Get all fans
  fans = []
  # Supply, exhaust, relief, and return fans
  fans += air_loop_hvac_supply_return_exhaust_relief_fans(air_loop_hvac)

  # Fans inside of fan-powered terminals
  if include_terminal_fans
    air_loop_hvac.demandComponents.each do |comp|
      if comp.to_AirTerminalSingleDuctSeriesPIUReheat.is_initialized
        term_fan = comp.to_AirTerminalSingleDuctSeriesPIUReheat.get.supplyAirFan
        if term_fan.to_FanConstantVolume.is_initialized
          fans << term_fan.to_FanConstantVolume.get
        end
      elsif comp.to_AirTerminalSingleDuctParallelPIUReheat.is_initialized
        term_fan = comp.to_AirTerminalSingleDuctParallelPIUReheat.get.fan
        if term_fan.to_FanConstantVolume.is_initialized
          fans << term_fan.to_FanConstantVolume.get
        end
      end
    end
  end

  # Loop through all fans on the system and
  # sum up their brake horsepower values.
  sys_fan_bhp = 0
  fans.sort.each do |fan|
    sys_fan_bhp += fan_brake_horsepower(fan)
  end

  return sys_fan_bhp
end
air_loop_hvac_system_multiplier(air_loop_hvac) click to toggle source

Determine if every zone on the system has an identical multiplier. If so, return this number. If not, return 1.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Integer] an integer representing the system multiplier.

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3630
def air_loop_hvac_system_multiplier(air_loop_hvac)
  mult = 1

  # Get all the zone multipliers
  zn_mults = []
  air_loop_hvac.thermalZones.each do |zone|
    zn_mults << zone.multiplier
  end

  # Warn if there are different multipliers
  uniq_mults = zn_mults.uniq
  if uniq_mults.size > 1
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name}: not all zones on the system have an identical zone multiplier.  Multipliers are: #{uniq_mults.join(', ')}.")
  else
    mult = uniq_mults[0]
  end

  return mult
end
air_loop_hvac_terminal_reheat?(air_loop_hvac) click to toggle source

Determine if the system has terminal reheat

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if has one or more reheat terminals, false if it doesn’t

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2620
def air_loop_hvac_terminal_reheat?(air_loop_hvac)
  has_term_rht = false
  air_loop_hvac.demandComponents.each do |sc|
    if sc.to_AirTerminalSingleDuctConstantVolumeReheat.is_initialized ||
       sc.to_AirTerminalSingleDuctParallelPIUReheat.is_initialized ||
       sc.to_AirTerminalSingleDuctSeriesPIUReheat.is_initialized ||
       sc.to_AirTerminalSingleDuctVAVHeatAndCoolReheat.is_initialized ||
       sc.to_AirTerminalSingleDuctVAVReheat.is_initialized
      has_term_rht = true
      break
    end
  end

  return has_term_rht
end
air_loop_hvac_total_cooling_capacity(air_loop_hvac) click to toggle source

Get the total cooling capacity for the air loop

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Double] total cooling capacity in watts @todo Change to pull water coil nominal capacity instead of design load; not a huge difference, but water coil nominal capacity not available in sizing table. @todo Handle all additional cooling coil types. Currently only handles CoilCoolingDXSingleSpeed, CoilCoolingDXTwoSpeed, and CoilCoolingWater

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 760
def air_loop_hvac_total_cooling_capacity(air_loop_hvac)
  # Sum the cooling capacity for all cooling components
  # on the airloop, which may be inside of unitary systems.
  total_cooling_capacity_w = 0
  air_loop_hvac.supplyComponents.each do |sc|
    # CoilCoolingDXSingleSpeed
    if sc.to_CoilCoolingDXSingleSpeed.is_initialized
      coil = sc.to_CoilCoolingDXSingleSpeed.get
      if coil.ratedTotalCoolingCapacity.is_initialized
        total_cooling_capacity_w += coil.ratedTotalCoolingCapacity.get
      elsif coil.autosizedRatedTotalCoolingCapacity.is_initialized
        total_cooling_capacity_w += coil.autosizedRatedTotalCoolingCapacity.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
      end
    elsif sc.to_CoilCoolingDXTwoSpeed.is_initialized
      coil = sc.to_CoilCoolingDXTwoSpeed.get
      if coil.ratedHighSpeedTotalCoolingCapacity.is_initialized
        total_cooling_capacity_w += coil.ratedHighSpeedTotalCoolingCapacity.get
      elsif coil.autosizedRatedHighSpeedTotalCoolingCapacity.is_initialized
        total_cooling_capacity_w += coil.autosizedRatedHighSpeedTotalCoolingCapacity.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
      end
      # CoilCoolingWater
    elsif sc.to_CoilCoolingWater.is_initialized
      coil = sc.to_CoilCoolingWater.get
      # error if the design coil capacity method isn't available
      if coil.model.version < OpenStudio::VersionString.new('3.6.0')
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', 'Required CoilCoolingWater method .autosizedDesignCoilLoad is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
      end
      if coil.autosizedDesignCoilLoad.is_initialized
        # @todo Change to pull water coil nominal capacity instead of design load
        total_cooling_capacity_w += coil.autosizedDesignCoilLoad.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
      end
      # CoilCoolingWaterToAirHeatPumpEquationFit
    elsif sc.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized
      coil = sc.to_CoilCoolingWaterToAirHeatPumpEquationFit.get
      if coil.ratedTotalCoolingCapacity.is_initialized
        total_cooling_capacity_w += coil.ratedTotalCoolingCapacity.get
      elsif coil.autosizedRatedTotalCoolingCapacity.is_initialized
        total_cooling_capacity_w += coil.autosizedRatedTotalCoolingCapacity.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
      end
    elsif sc.to_AirLoopHVACUnitarySystem.is_initialized
      unitary = sc.to_AirLoopHVACUnitarySystem.get
      if unitary.coolingCoil.is_initialized
        clg_coil = unitary.coolingCoil.get
        # CoilCoolingDXSingleSpeed
        if clg_coil.to_CoilCoolingDXSingleSpeed.is_initialized
          coil = clg_coil.to_CoilCoolingDXSingleSpeed.get
          if coil.ratedTotalCoolingCapacity.is_initialized
            total_cooling_capacity_w += coil.ratedTotalCoolingCapacity.get
          elsif coil.autosizedRatedTotalCoolingCapacity.is_initialized
            total_cooling_capacity_w += coil.autosizedRatedTotalCoolingCapacity.get
          else
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
          end
        # CoilCoolingDXTwoSpeed
        elsif clg_coil.to_CoilCoolingDXTwoSpeed.is_initialized
          coil = clg_coil.to_CoilCoolingDXTwoSpeed.get
          if coil.ratedHighSpeedTotalCoolingCapacity.is_initialized
            total_cooling_capacity_w += coil.ratedHighSpeedTotalCoolingCapacity.get
          elsif coil.autosizedRatedHighSpeedTotalCoolingCapacity.is_initialized
            total_cooling_capacity_w += coil.autosizedRatedHighSpeedTotalCoolingCapacity.get
          else
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
          end
        # CoilCoolingWater
        elsif clg_coil.to_CoilCoolingWater.is_initialized
          coil = clg_coil.to_CoilCoolingWater.get
          # error if the design coil capacity method isn't available
          if coil.model.version < OpenStudio::VersionString.new('3.6.0')
            OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', 'Required CoilCoolingWater method .autosizedDesignCoilLoad is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
          end
          if coil.autosizedDesignCoilLoad.is_initialized
            # @todo Change to pull water coil nominal capacity instead of design load
            total_cooling_capacity_w += coil.autosizedDesignCoilLoad.get
          else
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
          end
        # CoilCoolingWaterToAirHeatPumpEquationFit
        elsif clg_coil.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized
          coil = clg_coil.to_CoilCoolingWaterToAirHeatPumpEquationFit.get
          if coil.ratedTotalCoolingCapacity.is_initialized
            total_cooling_capacity_w += coil.ratedTotalCoolingCapacity.get
          elsif coil.autosizedRatedTotalCoolingCapacity.is_initialized
            total_cooling_capacity_w += coil.autosizedRatedTotalCoolingCapacity.get
          else
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
          end
        end
      end
    elsif sc.to_AirLoopHVACUnitaryHeatPumpAirToAir.is_initialized
      unitary = sc.to_AirLoopHVACUnitaryHeatPumpAirToAir.get
      clg_coil = unitary.coolingCoil
      # CoilCoolingDXSingleSpeed
      if clg_coil.to_CoilCoolingDXSingleSpeed.is_initialized
        coil = clg_coil.to_CoilCoolingDXSingleSpeed.get
        if coil.ratedTotalCoolingCapacity.is_initialized
          total_cooling_capacity_w += coil.ratedTotalCoolingCapacity.get
        elsif coil.autosizedRatedTotalCoolingCapacity.is_initialized
          total_cooling_capacity_w += coil.autosizedRatedTotalCoolingCapacity.get
        else
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
        end
      # CoilCoolingDXTwoSpeed
      elsif clg_coil.to_CoilCoolingDXTwoSpeed.is_initialized
        coil = clg_coil.to_CoilCoolingDXTwoSpeed.get
        if coil.ratedHighSpeedTotalCoolingCapacity.is_initialized
          total_cooling_capacity_w += coil.ratedHighSpeedTotalCoolingCapacity.get
        elsif coil.autosizedRatedHighSpeedTotalCoolingCapacity.is_initialized
          total_cooling_capacity_w += coil.autosizedRatedHighSpeedTotalCoolingCapacity.get
        else
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
        end
      # CoilCoolingWater
      elsif clg_coil.to_CoilCoolingWater.is_initialized
        coil = clg_coil.to_CoilCoolingWater.get
        # error if the design coil capacity method isn't available
        if coil.model.version < OpenStudio::VersionString.new('3.6.0')
          OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.AirLoopHVAC', 'Required CoilCoolingWater method .autosizedDesignCoilLoad is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
        end
        if coil.autosizedDesignCoilLoad.is_initialized
          # @todo Change to pull water coil nominal capacity instead of design load
          total_cooling_capacity_w += coil.autosizedDesignCoilLoad.get
        else
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
        end
      end
    elsif sc.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.is_initialized
      unitary = sc.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.get
      clg_coil = unitary.coolingCoil
      # CoilCoolingDXMultSpeed
      if clg_coil.to_CoilCoolingDXMultiSpeed.is_initialized
        coil = clg_coil.to_CoilCoolingDXMultiSpeed.get
        total_cooling_capacity_w = coil_cooling_dx_multi_speed_find_capacity(coil)
      end
    elsif sc.to_CoilCoolingDXVariableSpeed.is_initialized
      coil = sc.to_CoilCoolingDXVariableSpeed.get
      if coil.autosizedGrossRatedTotalCoolingCapacityAtSelectedNominalSpeedLevel.is_initialized
        # autosized capacity needs to be corrected for actual flow rate and fan power
        sys_fans = []
        air_loop_hvac.supplyComponents.each do |comp|
          if comp.to_FanConstantVolume.is_initialized
            sys_fans << comp.to_FanConstantVolume.get
          elsif comp.to_FanVariableVolume.is_initialized
            sys_fans << comp.to_FanVariableVolume.get
          end
        end
        max_pd = 0.0
        supply_fan = nil
        sys_fans.each do |fan|
          if fan.pressureRise.to_f > max_pd
            max_pd = fan.pressureRise.to_f
            supply_fan = fan # assume supply fan has higher pressure drop
          end
        end
        fan_power = supply_fan.autosizedMaximumFlowRate.to_f * supply_fan.pressureRise.to_f / supply_fan.fanTotalEfficiency.to_f
        nominal_cooling_capacity_w = coil.autosizedGrossRatedTotalCoolingCapacityAtSelectedNominalSpeedLevel.to_f
        nominal_flow_rate_factor = supply_fan.autosizedMaximumFlowRate.to_f / coil.autosizedRatedAirFlowRateAtSelectedNominalSpeedLevel.to_f
        fan_power_adjustment_w = fan_power / coil.speeds.last.referenceUnitGrossRatedSensibleHeatRatio.to_f
        total_cooling_capacity_w += nominal_cooling_capacity_w * nominal_flow_rate_factor + fan_power_adjustment_w
      elsif coil.grossRatedTotalCoolingCapacityAtSelectedNominalSpeedLevel.is_initialized
        total_cooling_capacity_w += coil.grossRatedTotalCoolingCapacityAtSelectedNominalSpeedLevel.to_f
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "For #{air_loop_hvac.name} capacity of #{coil.name} is not available, total cooling capacity of air loop will be incorrect when applying standard.")
      end
    elsif sc.to_CoilCoolingDXMultiSpeed.is_initialized ||
          sc.to_CoilCoolingCooledBeam.is_initialized ||
          sc.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.is_initialized ||
          sc.to_AirLoopHVACUnitarySystem.is_initialized
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.AirLoopHVAC', "#{air_loop_hvac.name} has a cooling coil named #{sc.name}, whose type is not yet covered by economizer checks.")
      # CoilCoolingDXMultiSpeed
      # CoilCoolingCooledBeam
      # CoilCoolingWaterToAirHeatPumpEquationFit
      # AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass
      # AirLoopHVACUnitaryHeatPumpAirToAir
      # AirLoopHVACUnitarySystem
    end
  end

  return total_cooling_capacity_w
end
air_loop_hvac_unitary_system?(air_loop_hvac) click to toggle source

Determine if the air loop is a unitary system

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if a unitary system is present, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2662
def air_loop_hvac_unitary_system?(air_loop_hvac)
  is_unitary_system = false
  air_loop_hvac.supplyComponents.each do |component|
    obj_type = component.iddObjectType.valueName.to_s
    case obj_type
    when 'OS_AirLoopHVAC_UnitarySystem', 'OS_AirLoopHVAC_UnitaryHeatPump_AirToAir', 'OS_AirLoopHVAC_UnitaryHeatPump_AirToAir_MultiSpeed', 'OS_AirLoopHVAC_UnitaryHeatCool_VAVChangeoverBypass'
      is_unitary_system = true
    end
  end
  return is_unitary_system
end
air_loop_hvac_unoccupied_fan_shutoff_required?(air_loop_hvac) click to toggle source

Determine if a system’s fans must shut off when not required. Per ASHRAE 90.1 section 6.4.3.3, HVAC systems are required to have off-hour controls

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3305
def air_loop_hvac_unoccupied_fan_shutoff_required?(air_loop_hvac)
  shutoff_required = true

  # Determine if the airloop serves any computer rooms or data centers, which default to always on.
  if air_loop_hvac_data_center_area_served(air_loop_hvac) > 0
    shutoff_required = false
  end

  return shutoff_required
end
air_loop_hvac_unoccupied_threshold() click to toggle source

Default occupancy fraction threshold for determining if the spaces on the air loop are occupied @return [Double] threshold at which the air loop space are considered unoccupied

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3318
def air_loop_hvac_unoccupied_threshold
  return 0.15
end
air_loop_hvac_vav_damper_action(air_loop_hvac) click to toggle source

Determine whether the VAV damper control is single maximum or dual maximum control. Defaults to 90.1-2007.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [String] the damper control type: Single Maximum, Dual Maximum

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2728
def air_loop_hvac_vav_damper_action(air_loop_hvac)
  damper_action = 'Dual Maximum'
  return damper_action
end
air_loop_hvac_vav_system?(air_loop_hvac) click to toggle source

Determine if the system is a VAV system based on the fan which may be inside of a unitary system.

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if vav system, false if not

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 2569
def air_loop_hvac_vav_system?(air_loop_hvac)
  is_vav = false
  air_loop_hvac.supplyComponents.reverse.each do |comp|
    if comp.to_FanVariableVolume.is_initialized
      is_vav = true
    elsif comp.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.is_initialized
      fan = comp.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.get.supplyAirFan
      if fan.to_FanVariableVolume.is_initialized
        is_vav = true
      end
    elsif comp.to_AirLoopHVACUnitarySystem.is_initialized
      fan = comp.to_AirLoopHVACUnitarySystem.get.supplyFan
      if fan.is_initialized
        if fan.get.to_FanVariableVolume.is_initialized
          is_vav = true
        end
      end
    end
  end

  return is_vav
end
air_terminal_single_duct_parallel_piu_reheat_apply_minimum_primary_airflow_fraction(air_terminal_single_duct_parallel_piu_reheat, zone_min_oa = nil) click to toggle source

Set the minimum primary air flow fraction based on OA rate of the space and the template.

@param air_terminal_single_duct_parallel_piu_reheat [OpenStudio::Model::AirTerminalSingleDuctParallelPIUReheat] the air terminal object @param zone_min_oa [Double] the zone outdoor air flow rate, in m^3/s. @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirTerminalSingleDuctParallelPIUReheat.rb, line 94
def air_terminal_single_duct_parallel_piu_reheat_apply_minimum_primary_airflow_fraction(air_terminal_single_duct_parallel_piu_reheat, zone_min_oa = nil)
  # Minimum primary air flow
  min_primary_airflow_frac = air_terminal_single_duct_parallel_reheat_piu_minimum_primary_airflow_fraction(air_terminal_single_duct_parallel_piu_reheat)
  air_terminal_single_duct_parallel_piu_reheat.setMinimumPrimaryAirFlowFraction(min_primary_airflow_frac)
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirTerminalSingleDuctParallelPIUReheat', "For #{air_terminal_single_duct_parallel_piu_reheat.name}: set minimum primary air flow fraction to #{min_primary_airflow_frac}.")

  # Minimum OA flow rate
  # If specified, set the primary air flow fraction as
  unless zone_min_oa.nil?
    min_primary_airflow_frac = [min_primary_airflow_frac, zone_min_oa / air_terminal_single_duct_parallel_piu_reheat.autosizedMaximumPrimaryAirFlowRate.get].max
    air_terminal_single_duct_parallel_piu_reheat.setMinimumPrimaryAirFlowFraction(min_primary_airflow_frac)
  end

  return true
end
air_terminal_single_duct_parallel_piu_reheat_apply_prm_baseline_fan_power(air_terminal_single_duct_parallel_piu_reheat) click to toggle source

Sets the fan power of a PIU fan based on the W/cfm specified in the standard.

@param air_terminal_single_duct_parallel_piu_reheat [OpenStudio::Model::AirTerminalSingleDuctParallelPIUReheat] air terminal object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirTerminalSingleDuctParallelPIUReheat.rb, line 8
def air_terminal_single_duct_parallel_piu_reheat_apply_prm_baseline_fan_power(air_terminal_single_duct_parallel_piu_reheat)
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirTerminalSingleDuctParallelPIUReheat', "Setting PIU fan power for #{air_terminal_single_duct_parallel_piu_reheat.name}.")

  # Determine the fan sizing flow rate, min flow rate,
  # and W/cfm
  sec_flow_frac = 0.5
  min_flow_frac = air_terminal_single_duct_parallel_reheat_piu_minimum_primary_airflow_fraction(air_terminal_single_duct_parallel_piu_reheat)
  fan_efficacy_w_per_cfm = 0.35

  # Set the fan on flow fraction
  unless air_terminal_single_duct_parallel_piu_reheat_fan_on_flow_fraction.nil?
    air_terminal_single_duct_parallel_piu_reheat.setFanOnFlowFraction(air_terminal_single_duct_parallel_piu_reheat_fan_on_flow_fraction)
  end

  # Convert efficacy to metric
  # 1 cfm = 0.0004719 m^3/s
  fan_efficacy_w_per_m3_per_s = fan_efficacy_w_per_cfm / 0.0004719

  # Get the maximum flow rate through the terminal
  max_primary_air_flow_rate = nil
  if air_terminal_single_duct_parallel_piu_reheat.maximumPrimaryAirFlowRate.is_initialized
    max_primary_air_flow_rate = air_terminal_single_duct_parallel_piu_reheat.maximumPrimaryAirFlowRate.get
  elsif air_terminal_single_duct_parallel_piu_reheat.autosizedMaximumPrimaryAirFlowRate.is_initialized
    max_primary_air_flow_rate = air_terminal_single_duct_parallel_piu_reheat.autosizedMaximumPrimaryAirFlowRate.get
  end

  # Set the max secondary air flow rate
  max_sec_flow_rate_m3_per_s = max_primary_air_flow_rate * sec_flow_frac
  air_terminal_single_duct_parallel_piu_reheat.setMaximumSecondaryAirFlowRate(max_sec_flow_rate_m3_per_s)
  max_sec_flow_rate_cfm = OpenStudio.convert(max_sec_flow_rate_m3_per_s, 'm^3/s', 'ft^3/min').get

  # Set the minimum flow fraction
  air_terminal_single_duct_parallel_piu_reheat.setMinimumPrimaryAirFlowFraction(min_flow_frac)

  # Get the fan
  fan = air_terminal_single_duct_parallel_piu_reheat.fan.to_FanConstantVolume.get

  # Set the impeller efficiency
  fan_change_impeller_efficiency(fan, fan_baseline_impeller_efficiency(fan))

  # Set the motor efficiency, preserving the impeller efficency.
  # For terminal fans, a bhp lookup of 0.5bhp is always used because
  # they are assumed to represent a series of small fans in reality.
  fan_apply_standard_minimum_motor_efficiency(fan, fan_brake_horsepower(fan))

  # Calculate a new pressure rise to hit the target W/cfm
  fan_tot_eff = fan.fanEfficiency
  fan_rise_new_pa = fan_efficacy_w_per_m3_per_s * fan_tot_eff
  fan.setPressureRise(fan_rise_new_pa)

  # Calculate the newly set efficacy
  fan_power_new_w = fan_rise_new_pa * max_sec_flow_rate_m3_per_s / fan_tot_eff
  fan_efficacy_new_w_per_cfm = fan_power_new_w / max_sec_flow_rate_cfm
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.AirTerminalSingleDuctParallelPIUReheat', "For #{air_terminal_single_duct_parallel_piu_reheat.name}: fan efficacy set to #{fan_efficacy_new_w_per_cfm.round(2)} W/cfm.")

  return true
end
air_terminal_single_duct_parallel_piu_reheat_fan_on_flow_fraction() click to toggle source

Return the fan on flow fraction for a parallel PIU terminal.

When returning nil, the fan on flow fraction will be set to be autosize in the EnergyPlus model; OpenStudio assumes that the default is “autosize”. When autosized, this input is set to be the same as the minimum primary air flow fraction which means that the secondary fan will be on when the primary air flow is at the minimum flow fraction.

@return [Double] returns nil or a float representing the fraction

# File lib/openstudio-standards/standards/Standards.AirTerminalSingleDuctParallelPIUReheat.rb, line 76
def air_terminal_single_duct_parallel_piu_reheat_fan_on_flow_fraction
  return nil
end
air_terminal_single_duct_parallel_reheat_piu_minimum_primary_airflow_fraction(air_terminal_single_duct_parallel_piu_reheat) click to toggle source

Specifies the minimum primary air flow fraction for PFB boxes.

@param air_terminal_single_duct_parallel_piu_reheat [OpenStudio::Model::AirTerminalSingleDuctParallelPIUReheat] air terminal object @return [Double] minimum primaru air flow fraction

# File lib/openstudio-standards/standards/Standards.AirTerminalSingleDuctParallelPIUReheat.rb, line 84
def air_terminal_single_duct_parallel_reheat_piu_minimum_primary_airflow_fraction(air_terminal_single_duct_parallel_piu_reheat)
  min_primary_airflow_fraction = 0.3
  return min_primary_airflow_fraction
end
air_terminal_single_duct_vav_reheat_apply_initial_prototype_damper_position(air_terminal_single_duct_vav_reheat, zone_oa_per_area) click to toggle source

@!group AirTerminalSingleDuctVAVReheat Set the initial minimum damper position based on OA rate of the space and the template. Defaults to basic behavior, but this method is overridden by all of the ASHRAE-based templates. Zones with low OA per area get lower initial guesses. Final position will be adjusted upward as necessary by Standards.AirLoopHVAC.apply_minimum_vav_damper_positions

@param air_terminal_single_duct_vav_reheat [OpenStudio::Model::AirTerminalSingleDuctVAVReheat] the air terminal object @param zone_oa_per_area [Double] the zone outdoor air per area in m^3/s*m^2 @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.AirTerminalSingleDuctVAVReheat.rb, line 11
def air_terminal_single_duct_vav_reheat_apply_initial_prototype_damper_position(air_terminal_single_duct_vav_reheat, zone_oa_per_area)
  min_damper_position = 0.3

  # Set the minimum flow fraction
  air_terminal_single_duct_vav_reheat.setConstantMinimumAirFlowFraction(min_damper_position)

  return true
end
air_terminal_single_duct_vav_reheat_apply_minimum_damper_position(air_terminal_single_duct_vav_reheat, zone_min_oa = nil, has_ddc = true) click to toggle source

Set the minimum damper position based on OA rate of the space and the template. Zones with low OA per area get lower initial guesses. Final position will be adjusted upward as necessary by Standards.AirLoopHVAC.adjust_minimum_vav_damper_positions

@param air_terminal_single_duct_vav_reheat [OpenStudio::Model::AirTerminalSingleDuctVAVReheat] the air terminal object @param zone_min_oa [Double] the zone outdoor air flow rate, in m^3/s.

If supplied, this will be set as a minimum limit in addition to the minimum
damper position.  EnergyPlus will use the larger of the two values during sizing.

@param has_ddc [Boolean] whether or not there is DDC control of the VAV terminal,

which impacts the minimum damper position requirement.

@return [Boolean] returns true if successful, false if not @todo remove exception where older vintages don’t have minimum positions adjusted.

# File lib/openstudio-standards/standards/Standards.AirTerminalSingleDuctVAVReheat.rb, line 16
def air_terminal_single_duct_vav_reheat_apply_minimum_damper_position(air_terminal_single_duct_vav_reheat, zone_min_oa = nil, has_ddc = true)
  # Minimum damper position
  min_damper_position = air_terminal_single_duct_vav_reheat_minimum_damper_position(air_terminal_single_duct_vav_reheat, has_ddc)
  air_terminal_single_duct_vav_reheat.setConstantMinimumAirFlowFraction(min_damper_position)
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.AirTerminalSingleDuctVAVReheat', "For #{air_terminal_single_duct_vav_reheat.name}: set minimum damper position to #{min_damper_position}.")

  # Minimum OA flow rate
  # If specified, will also add this limit
  # and the larger of the two will be used
  # for sizing.
  unless zone_min_oa.nil?
    air_terminal_single_duct_vav_reheat.setFixedMinimumAirFlowRate(zone_min_oa)
  end

  return true
end
air_terminal_single_duct_vav_reheat_minimum_damper_position(air_terminal_single_duct_vav_reheat, has_ddc = false) click to toggle source

Specifies the minimum damper position for VAV dampers. Defaults to 30%

@param air_terminal_single_duct_vav_reheat [OpenStudio::Model::AirTerminalSingleDuctVAVReheat] the air terminal object @param has_ddc [Boolean] whether or not there is DDC control of the VAV terminal in question @return [Double] minimum damper position

# File lib/openstudio-standards/standards/Standards.AirTerminalSingleDuctVAVReheat.rb, line 39
def air_terminal_single_duct_vav_reheat_minimum_damper_position(air_terminal_single_duct_vav_reheat, has_ddc = false)
  min_damper_position = 0.3
  return min_damper_position
end
air_terminal_single_duct_vav_reheat_reheat_type(air_terminal_single_duct_vav_reheat) click to toggle source

Determines whether the terminal has a NaturalGas, Electricity, or HotWater reheat coil.

@param air_terminal_single_duct_vav_reheat [OpenStudio::Model::AirTerminalSingleDuctVAVReheat] the air terminal object @return [String] reheat type. One of NaturalGas, Electricity, or HotWater.

# File lib/openstudio-standards/standards/Standards.AirTerminalSingleDuctVAVReheat.rb, line 69
def air_terminal_single_duct_vav_reheat_reheat_type(air_terminal_single_duct_vav_reheat)
  type = nil

  if air_terminal_single_duct_vav_reheat.to_AirTerminalSingleDuctVAVNoReheat.is_initialized
    return nil
  end

  # Get the reheat coil
  rht_coil = air_terminal_single_duct_vav_reheat.reheatCoil
  if rht_coil.to_CoilHeatingElectric.is_initialized
    type = 'Electricity'
  elsif rht_coil.to_CoilHeatingWater.is_initialized
    type = 'HotWater'
  elsif rht_coil.to_CoilHeatingGas.is_initialized
    type = 'NaturalGas'
  end

  return type
end
air_terminal_single_duct_vav_reheat_set_heating_cap(air_terminal_single_duct_vav_reheat) click to toggle source

Sets the capacity of the reheat coil based on the minimum flow fraction, and the maximum flow rate.

@param air_terminal_single_duct_vav_reheat [OpenStudio::Model::AirTerminalSingleDuctVAVReheat] the air terminal object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.AirTerminalSingleDuctVAVReheat.rb, line 48
def air_terminal_single_duct_vav_reheat_set_heating_cap(air_terminal_single_duct_vav_reheat)
  flow_rate_fraction = 0.0
  if air_terminal_single_duct_vav_reheat.constantMinimumAirFlowFraction.is_initialized
    flow_rate_fraction = air_terminal_single_duct_vav_reheat.constantMinimumAirFlowFraction.get
  end
  return false unless air_terminal_single_duct_vav_reheat.reheatCoil.to_CoilHeatingWater.is_initialized

  reheat_coil = air_terminal_single_duct_vav_reheat.reheatCoil.to_CoilHeatingWater.get
  if reheat_coil.autosizedRatedCapacity.to_f < 1.0e-6
    cap = 1.2 * 1000.0 * flow_rate_fraction * air_terminal_single_duct_vav_reheat.autosizedMaximumAirFlowRate.to_f * (18.0 - 13.0)
    reheat_coil.setPerformanceInputMethod('NominalCapacity')
    reheat_coil.setRatedCapacity(cap)
    air_terminal_single_duct_vav_reheat.setMaximumReheatAirTemperature(18.0)
  end
  return true
end
apply_lighting_schedule(space_type, space_type_properties, default_sch_set) click to toggle source

applies a lighting schedule to a space type

@param space_type [OpenStudio::Model::SpaceType] space type object @param space_type_properties [Hash] hash of space type properties @param default_sch_set [OpenStudio::Model::DefaultScheduleSet] default schedule set @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.SpaceType.rb, line 710
def apply_lighting_schedule(space_type, space_type_properties, default_sch_set)
  lighting_sch = space_type_properties['lighting_schedule']
  return false if lighting_sch.nil?

  default_sch_set.setLightingSchedule(model_add_schedule(space_type.model, lighting_sch))
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set lighting schedule to #{lighting_sch}.")
  return true
end
apply_limit_to_subsurface_ratio(model, ratio, surface_type = 'Wall') click to toggle source

This method will limit the subsurface of a given surface_type (“Wall” or “RoofCeiling”) to the ratio for the building. This method only reduces subsurface sizes at most.

@param model [OpenStudio::Model::Model] OpenStudio model object @param ratio [Double] ratio @param surface_type [String] surface type @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5352
def apply_limit_to_subsurface_ratio(model, ratio, surface_type = 'Wall')
  fdwr = get_outdoor_subsurface_ratio(model, surface_type)
  if fdwr <= ratio
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Building FDWR of #{fdwr} is already lower than limit of #{ratio.round}%.")
    return true
  end
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Reducing the size of all windows (by shrinking to centroid) to reduce window area down to the limit of #{ratio.round}%.")
  # Determine the factors by which to reduce the window / door area
  mult = ratio / fdwr
  # Reduce the window area if any of the categories necessary
  model.getSpaces.sort.each do |space|
    # Loop through all surfaces in this space
    space.surfaces.sort.each do |surface|
      # Skip non-outdoor surfaces
      next unless surface.outsideBoundaryCondition == 'Outdoors'
      # Skip non-walls
      next unless surface.surfaceType == surface_type

      # Subsurfaces in this surface
      surface.subSurfaces.sort.each do |ss|
        # Reduce the size of the window
        red = 1.0 - mult
        OpenstudioStandards::Geometry.sub_surface_reduce_area_by_percent_by_shrinking_toward_centroid(ss, red)
      end
    end
  end
  return true
end
boiler_get_eff_fplr(boiler_hot_water) click to toggle source

Determine what part load efficiency degredation curve should be used for a boiler

@param boiler_hot_water [OpenStudio::Model::BoilerHotWater] hot water boiler object @return [String] returns name of the boiler curve to be used, or nil if not applicable

# File lib/openstudio-standards/standards/Standards.BoilerHotWater.rb, line 135
def boiler_get_eff_fplr(boiler_hot_water)
  return nil
end
boiler_hot_water_apply_efficiency_and_curves(boiler_hot_water) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param boiler_hot_water [OpenStudio::Model::BoilerHotWater] hot water boiler object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.BoilerHotWater.rb, line 143
def boiler_hot_water_apply_efficiency_and_curves(boiler_hot_water)
  successfully_set_all_properties = false

  # Define the criteria to find the boiler properties
  # in the hvac standards data set.
  search_criteria = boiler_hot_water_find_search_criteria(boiler_hot_water)
  fuel_type = search_criteria['fuel_type']
  fluid_type = search_criteria['fluid_type']

  # Get the capacity
  capacity_w = boiler_hot_water_find_capacity(boiler_hot_water)

  # Convert capacity to Btu/hr
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Get the boiler properties
  blr_props = model_find_object(standards_data['boilers'], search_criteria, capacity_btu_per_hr)
  unless blr_props
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.BoilerHotWater', "For #{boiler_hot_water.name}, cannot find boiler properties with search criteria #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Get and assign boiler part load efficiency degradation curve
  eff_fplr = nil
  if blr_props['efffplr']
    eff_fplr = model_add_curve(boiler_hot_water.model, blr_props['efffplr'])
  else
    eff_fplr_curve_name = boiler_get_eff_fplr(boiler_hot_water)
    eff_fplr = model_add_curve(boiler_hot_water.model, eff_fplr_curve_name)
  end
  if eff_fplr
    boiler_hot_water.setNormalizedBoilerEfficiencyCurve(eff_fplr)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.BoilerHotWater', "For #{boiler_hot_water.name}, cannot find eff_fplr curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Get the minimum efficiency standards
  thermal_eff = nil

  # If specified as AFUE
  unless blr_props['minimum_annual_fuel_utilization_efficiency'].nil?
    min_afue = blr_props['minimum_annual_fuel_utilization_efficiency']
    thermal_eff = afue_to_thermal_eff(min_afue)
    new_comp_name = "#{boiler_hot_water.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_afue} AFUE"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.BoilerHotWater', "For #{template}: #{boiler_hot_water.name}: #{fuel_type} #{fluid_type} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; AFUE = #{min_afue}")
  end

  # If specified as thermal efficiency
  unless blr_props['minimum_thermal_efficiency'].nil?
    thermal_eff = blr_props['minimum_thermal_efficiency']
    new_comp_name = "#{boiler_hot_water.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{thermal_eff} Thermal Eff"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.BoilerHotWater', "For #{template}: #{boiler_hot_water.name}: #{fuel_type} #{fluid_type} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; Thermal Efficiency = #{thermal_eff}")
  end

  # If specified as combustion efficiency
  unless blr_props['minimum_combustion_efficiency'].nil?
    min_comb_eff = blr_props['minimum_combustion_efficiency']
    thermal_eff = combustion_eff_to_thermal_eff(min_comb_eff)
    new_comp_name = "#{boiler_hot_water.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_comb_eff} Combustion Eff"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.BoilerHotWater', "For #{template}: #{boiler_hot_water.name}: #{fuel_type} #{fluid_type} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; Combustion Efficiency = #{min_comb_eff}")
  end

  # Set the name
  boiler_hot_water.setName(new_comp_name)

  # Set the efficiency values
  unless thermal_eff.nil?
    boiler_hot_water.setNominalThermalEfficiency(thermal_eff)
  end

  return successfully_set_all_properties
end
boiler_hot_water_find_capacity(boiler_hot_water) click to toggle source

Find capacity in W

@param boiler_hot_water [OpenStudio::Model::BoilerHotWater] hot water boiler object @return [Double] capacity in W

# File lib/openstudio-standards/standards/Standards.BoilerHotWater.rb, line 41
def boiler_hot_water_find_capacity(boiler_hot_water)
  capacity_w = nil
  if boiler_hot_water.nominalCapacity.is_initialized
    capacity_w = boiler_hot_water.nominalCapacity.get
  elsif boiler_hot_water.autosizedNominalCapacity.is_initialized
    capacity_w = boiler_hot_water.autosizedNominalCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.BoilerHotWater', "For #{boiler_hot_water.name} capacity is not available, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  return capacity_w
end
boiler_hot_water_find_design_water_flow_rate(boiler_hot_water) click to toggle source

Find design water flow rate in m^3/s

@param boiler_hot_water [OpenStudio::Model::BoilerHotWater] hot water boiler object @return [Double] design water flow rate in m^3/s

# File lib/openstudio-standards/standards/Standards.BoilerHotWater.rb, line 60
def boiler_hot_water_find_design_water_flow_rate(boiler_hot_water)
  design_water_flow_rate_m3_per_s = nil
  if boiler_hot_water.designWaterFlowRate.is_initialized
    design_water_flow_rate_m3_per_s = boiler_hot_water.designWaterFlowRate.get
  elsif boiler_hot_water.autosizedDesignWaterFlowRate.is_initialized
    design_water_flow_rate_m3_per_s = boiler_hot_water.autosizedDesignWaterFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.BoilerHotWater', "For #{boiler_hot_water.name} design water flow rate is not available.")
    return false
  end

  return design_water_flow_rate_m3_per_s
end
boiler_hot_water_find_search_criteria(boiler_hot_water) click to toggle source

find search criteria

@param boiler_hot_water [OpenStudio::Model::BoilerHotWater] hot water boiler object @return [Hash] used for standards_lookup_table(model)

# File lib/openstudio-standards/standards/Standards.BoilerHotWater.rb, line 8
def boiler_hot_water_find_search_criteria(boiler_hot_water)
  # Define the criteria to find the boiler properties
  # in the hvac standards data set.
  search_criteria = {}
  search_criteria['template'] = template

  # Get fuel type
  fuel_type = nil
  case boiler_hot_water.fuelType
  when 'NaturalGas'
    fuel_type = 'NaturalGas'
  when 'Electricity'
    fuel_type = 'Electric'
  when 'FuelOilNo1', 'FuelOilNo2'
    fuel_type = 'Oil'
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.BoilerHotWater', "For #{boiler_hot_water.name}, a fuel type of #{fuel_type} is not yet supported.  Assuming 'NaturalGas'.")
    fuel_type = 'NaturalGas'
  end

  search_criteria['fuel_type'] = fuel_type

  # Get the fluid type
  fluid_type = 'Hot Water'
  search_criteria['fluid_type'] = fluid_type

  return search_criteria
end
boiler_hot_water_standard_minimum_thermal_efficiency(boiler_hot_water, rename = false) click to toggle source

Finds lookup object in standards and return minimum thermal efficiency

@param boiler_hot_water [OpenStudio::Model::BoilerHotWater] hot water boiler object @param rename [Boolean] if true, rename the boiler to include the new capacity and efficiency @return [Double] minimum thermal efficiency

# File lib/openstudio-standards/standards/Standards.BoilerHotWater.rb, line 79
def boiler_hot_water_standard_minimum_thermal_efficiency(boiler_hot_water, rename = false)
  # Get the boiler properties
  search_criteria = boiler_hot_water_find_search_criteria(boiler_hot_water)
  capacity_w = boiler_hot_water_find_capacity(boiler_hot_water)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Get the minimum efficiency standards
  thermal_eff = nil

  # Get the boiler properties
  blr_props = model_find_object(standards_data['boilers'], search_criteria, capacity_btu_per_hr)
  unless blr_props
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.BoilerHotWater', "For #{boiler_hot_water.name}, cannot find boiler properties, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  fuel_type = blr_props['fuel_type']
  fluid_type = blr_props['fluid_type']

  # If specified as AFUE
  unless blr_props['minimum_annual_fuel_utilization_efficiency'].nil?
    min_afue = blr_props['minimum_annual_fuel_utilization_efficiency']
    thermal_eff = afue_to_thermal_eff(min_afue)
    new_comp_name = "#{boiler_hot_water.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_afue} AFUE"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.BoilerHotWater', "For #{template}: #{boiler_hot_water.name}: #{fuel_type} #{fluid_type} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; AFUE = #{min_afue}")
  end

  # If specified as thermal efficiency
  unless blr_props['minimum_thermal_efficiency'].nil?
    thermal_eff = blr_props['minimum_thermal_efficiency']
    new_comp_name = "#{boiler_hot_water.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{thermal_eff} Thermal Eff"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.BoilerHotWater', "For #{template}: #{boiler_hot_water.name}: #{fuel_type} #{fluid_type} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; Thermal Efficiency = #{thermal_eff}")
  end

  # If specified as combustion efficiency
  unless blr_props['minimum_combustion_efficiency'].nil?
    min_comb_eff = blr_props['minimum_combustion_efficiency']
    thermal_eff = combustion_eff_to_thermal_eff(min_comb_eff)
    new_comp_name = "#{boiler_hot_water.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_comb_eff} Combustion Eff"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.BoilerHotWater', "For #{template}: #{boiler_hot_water.name}: #{fuel_type} #{fluid_type} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; Combustion Efficiency = #{min_comb_eff}")
  end

  # Rename
  if rename
    boiler_hot_water.setName(new_comp_name)
  end

  return thermal_eff
end
chiller_electric_eir_apply_efficiency_and_curves(chiller_electric_eir, clg_tower_objs) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param chiller_electric_eir [OpenStudio::Model::ChillerElectricEIR] chiller object @param clg_tower_objs [Array] cooling towers, currently unused @return [Boolean] returns true if successful, false if not @todo remove clg_tower_objs parameter if unused

# File lib/openstudio-standards/standards/Standards.ChillerElectricEIR.rb, line 213
def chiller_electric_eir_apply_efficiency_and_curves(chiller_electric_eir, clg_tower_objs)
  chillers = standards_data['chillers']

  # Define the criteria to find the chiller properties
  # in the hvac standards data set.
  search_criteria = chiller_electric_eir_find_search_criteria(chiller_electric_eir)
  cooling_type = search_criteria['cooling_type']
  condenser_type = search_criteria['condenser_type']
  compressor_type = search_criteria['compressor_type']
  compliance_path = search_criteria['compliance_path']

  # Get the chiller capacity
  capacity_w = chiller_electric_eir_find_capacity(chiller_electric_eir)

  # Convert capacity to tons
  capacity_tons = OpenStudio.convert(capacity_w, 'W', 'ton').get

  # Get the chiller properties
  chlr_props = model_find_object(chillers, search_criteria, capacity_tons, Date.today)
  cop = nil
  if chlr_props.nil?
    search_criteria.delete('compliance_path')
    compliance_path = nil
    chlr_props = model_find_object(standards_data['chillers'], search_criteria, capacity_tons, Date.today)
  end
  if chlr_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, cannot find chiller properties using #{search_criteria}, cannot apply standard efficiencies or curves.")
    return false
  else
    if !chlr_props['minimum_coefficient_of_performance'].nil?
      cop = chlr_props['minimum_coefficient_of_performance']
    elsif !chlr_props['minimum_energy_efficiency_ratio'].nil?
      cop = eer_to_cop(chlr_props['minimum_energy_efficiency_ratio'])
    elsif !chlr_props['minimum_kilowatts_per_tons'].nil?
      cop = kw_per_ton_to_cop(chlr_props['minimum_kilowatts_per_tons'])
    end
    if cop.nil?
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, cannot find minimum full load efficiency.")
      return false
    end
  end

  # Make the CAPFT curve
  cool_cap_f_t_name = chiller_electric_eir_get_cap_f_t_curve_name(chiller_electric_eir, compressor_type, cooling_type, capacity_tons, compliance_path)
  if cool_cap_f_t_name.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, cannot find performance curve describing the capacity of the chiller as a function of temperature, will not be set.")
    successfully_set_all_properties = false
  else
    cool_cap_f_t = model_add_curve(chiller_electric_eir.model, cool_cap_f_t_name)
    if cool_cap_f_t
      chiller_electric_eir.setCoolingCapacityFunctionOfTemperature(cool_cap_f_t)
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, the performance curve describing the capacity of the chiller as a function of temperature could not be found.")
      successfully_set_all_properties = false
    end
  end

  # Make the EIRFT curve
  cool_eir_f_t_name = chiller_electric_eir_get_eir_f_t_curve_name(chiller_electric_eir, compressor_type, cooling_type, capacity_tons, compliance_path)
  if cool_eir_f_t_name.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, cannot find performance curve describing the EIR of the chiller as a function of temperature, will not be set.")
    successfully_set_all_properties = false
  else
    cool_eir_f_t = model_add_curve(chiller_electric_eir.model, cool_eir_f_t_name)
    if cool_eir_f_t
      chiller_electric_eir.setElectricInputToCoolingOutputRatioFunctionOfTemperature(cool_eir_f_t)
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, the performance curve describing the EIR of the chiller as a function of temperature could not be found.")
      successfully_set_all_properties = false
    end
  end

  # Make the EIRFPLR curve
  cool_eir_f_plr_name = chiller_electric_eir_get_eir_f_plr_curve_name(chiller_electric_eir, compressor_type, cooling_type, capacity_tons, compliance_path)
  if cool_eir_f_plr_name.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, cannot find performance curve describing the EIR of the chiller as a function of part load ratio, will not be set.")
    successfully_set_all_properties = false
  else
    cool_plf_f_plr = model_add_curve(chiller_electric_eir.model, cool_eir_f_plr_name)
    if cool_plf_f_plr
      chiller_electric_eir.setElectricInputToCoolingOutputRatioFunctionOfPLR(cool_plf_f_plr)
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, the performance curve describing the EIR of the chiller as a function of part load ratio could not be found.")
      successfully_set_all_properties = false
    end
  end

  # Set the efficiency value
  if cop.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, cannot find minimum full load efficiency, will not be set.")
    successfully_set_all_properties = false
  else
    chiller_electric_eir.setReferenceCOP(cop)
    kw_per_ton = cop_to_kw_per_ton(cop)
  end

  # Append the name with size and kw/ton
  chiller_electric_eir.setName("#{chiller_electric_eir.name} #{capacity_tons.round}tons #{kw_per_ton.round(3)}kW/ton")
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.ChillerElectricEIR', "For #{template}: #{chiller_electric_eir.name}: #{cooling_type} #{condenser_type} #{compressor_type} Capacity = #{capacity_tons.round}tons; COP = #{cop.round(1)} (#{kw_per_ton.round(3)}kW/ton)")

  return successfully_set_all_properties
end
chiller_electric_eir_find_capacity(chiller_electric_eir) click to toggle source

Finds capacity in W

@param chiller_electric_eir [OpenStudio::Model::ChillerElectricEIR] chiller object @return [Double] capacity in W to be used for find object

# File lib/openstudio-standards/standards/Standards.ChillerElectricEIR.rb, line 72
def chiller_electric_eir_find_capacity(chiller_electric_eir)
  if chiller_electric_eir.referenceCapacity.is_initialized
    capacity_w = chiller_electric_eir.referenceCapacity.get
  elsif chiller_electric_eir.autosizedReferenceCapacity.is_initialized
    capacity_w = chiller_electric_eir.autosizedReferenceCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name} capacity is not available, cannot apply efficiency standard.")
    return false
  end

  return capacity_w
end
chiller_electric_eir_find_search_criteria(chiller_electric_eir) click to toggle source

Finds the search criteria

@param chiller_electric_eir [OpenStudio::Model::ChillerElectricEIR] chiller object @return [Hash] has for search criteria to be used for find object

# File lib/openstudio-standards/standards/Standards.ChillerElectricEIR.rb, line 8
def chiller_electric_eir_find_search_criteria(chiller_electric_eir)
  search_criteria = {}
  search_criteria['template'] = template

  # Determine if WaterCooled or AirCooled by
  # checking if the chiller is connected to a condenser
  # water loop or not.  Use name as fallback for exporting HVAC library.
  cooling_type = chiller_electric_eir.condenserType

  search_criteria['cooling_type'] = cooling_type

  # @todo Standards replace this with a mechanism to store this
  # data in the chiller object itself.
  # For now, retrieve the condenser type from the name
  name = chiller_electric_eir.name.get
  condenser_type = nil
  compressor_type = nil
  absorption_type = nil
  if cooling_type == 'AirCooled'
    if name.include?('WithCondenser')
      condenser_type = 'WithCondenser'
    elsif name.include?('WithoutCondenser')
      condenser_type = 'WithoutCondenser'
    else
      # default to 'WithCondenser' if not an absorption chiller
      condenser_type = 'WithCondenser' if absorption_type.nil?
    end
  elsif cooling_type == 'WaterCooled'
    # use the chiller additional properties compressor type if defined
    if chiller_electric_eir.additionalProperties.hasFeature('compressor_type')
      compressor_type = chiller_electric_eir.additionalProperties.getFeatureAsString('compressor_type').get
    else
      # try to lookup by chiller name
      if name.include?('Reciprocating')
        compressor_type = 'Reciprocating'
      elsif name.include?('Rotary Screw')
        compressor_type = 'Rotary Screw'
      elsif name.include?('Scroll')
        compressor_type = 'Scroll'
      elsif name.include?('Centrifugal')
        compressor_type = 'Centrifugal'
      end
    end
  end
  unless condenser_type.nil?
    search_criteria['condenser_type'] = condenser_type
  end
  unless compressor_type.nil?
    search_criteria['compressor_type'] = compressor_type
  end

  # @todo Find out what compliance path is desired
  # perhaps this could be set using additional
  # properties when the chiller is created
  # Assume path a by default for now
  search_criteria['compliance_path'] = 'Path A'

  return search_criteria
end
chiller_electric_eir_get_cap_f_t_curve_name(chiller_electric_eir, compressor_type, cooling_type, chiller_tonnage, compliance_path) click to toggle source

Get applicable performance curve for capacity as a function of temperature

@param chiller_electric_eir [OpenStudio::Model::ChillerElectricEIR] chiller object @param compressor_type [String] compressor type @param cooling_type [String] cooling type (‘AirCooled’ or ‘WaterCooled’) @param chiller_tonnage [Double] chiller capacity in ton @return [String] name of applicable cuvre, nil if not found @todo the current assingment is meant to replicate what was in the data, it probably needs to be reviewed

# File lib/openstudio-standards/standards/Standards.ChillerElectricEIR.rb, line 131
def chiller_electric_eir_get_cap_f_t_curve_name(chiller_electric_eir, compressor_type, cooling_type, chiller_tonnage, compliance_path)
  curve_name = nil
  case cooling_type
  when 'AirCooled'
    curve_name = 'AirCooled_Chiller_2010_PathA_CAPFT'
  when 'WaterCooled'
    case compressor_type
    when 'Centrifugal'
      if chiller_tonnage >= 150
        curve_name = 'WaterCooled_Centrifugal_Chiller_GT150_2004_CAPFT'
      else
        curve_name = 'WaterCooled_Centrifugal_Chiller_LT150_2004_CAPFT'
      end
    when 'Reciprocating', 'Rotary Screw', 'Scroll'
      curve_name = 'ChlrWtrPosDispPathAAllQRatio_fTchwsTcwsSI'
    end
  end
  return curve_name
end
chiller_electric_eir_get_eir_f_plr_curve_name(chiller_electric_eir, compressor_type, cooling_type, chiller_tonnage, compliance_path) click to toggle source

Get applicable performance curve for EIR as a function of part load ratio

@param chiller_electric_eir [OpenStudio::Model::ChillerElectricEIR] chiller object @param compressor_type [String] compressor type @param cooling_type [String] cooling type (‘AirCooled’ or ‘WaterCooled’) @param chiller_tonnage [Double] chiller capacity in ton @return [String] name of applicable cuvre, nil if not found @todo the current assingment is meant to replicate what was in the data, it probably needs to be reviewed

# File lib/openstudio-standards/standards/Standards.ChillerElectricEIR.rb, line 189
def chiller_electric_eir_get_eir_f_plr_curve_name(chiller_electric_eir, compressor_type, cooling_type, chiller_tonnage, compliance_path)
  case cooling_type
  when 'AirCooled'
    return 'AirCooled_Chiller_AllCapacities_2004_2010_EIRFPLR'
  when 'WaterCooled'
    case compressor_type
    when 'Centrifugal'
      return 'ChlrWtrCentPathAAllEIRRatio_fQRatio'
    when 'Reciprocating', 'Rotary Screw', 'Scroll'
      return 'ChlrWtrCentPathAAllEIRRatio_fQRatio'
    else
      return nil
    end
  else
    return nil
  end
end
chiller_electric_eir_get_eir_f_t_curve_name(chiller_electric_eir, compressor_type, cooling_type, chiller_tonnage, compliance_path) click to toggle source

Get applicable performance curve for EIR as a function of temperature

@param chiller_electric_eir [OpenStudio::Model::ChillerElectricEIR] chiller object @param compressor_type [String] compressor type @param cooling_type [String] cooling type (‘AirCooled’ or ‘WaterCooled’) @param chiller_tonnage [Double] chiller capacity in ton @return [String] name of applicable cuvre, nil if not found @todo the current assingment is meant to replicate what was in the data, it probably needs to be reviewed

# File lib/openstudio-standards/standards/Standards.ChillerElectricEIR.rb, line 159
def chiller_electric_eir_get_eir_f_t_curve_name(chiller_electric_eir, compressor_type, cooling_type, chiller_tonnage, compliance_path)
  case cooling_type
  when 'AirCooled'
    return 'AirCooled_Chiller_2010_PathA_EIRFT'
  when 'WaterCooled'
    case compressor_type
    when 'Centrifugal'
      if chiller_tonnage >= 150
        return 'WaterCooled_Centrifugal_Chiller_GT150_2004_EIRFT'
      else
        return 'WaterCooled_Centrifugal_Chiller_LT150_2004_EIRFT'
      end
    when 'Reciprocating', 'Rotary Screw', 'Scroll'
      return 'ChlrWtrPosDispPathAAllEIRRatio_fTchwsTcwsSI'
    else
      return nil
    end
  else
    return nil
  end
end
chiller_electric_eir_standard_minimum_full_load_efficiency(chiller_electric_eir) click to toggle source

Finds lookup object in standards and return full load efficiency

@param chiller_electric_eir [OpenStudio::Model::ChillerElectricEIR] chiller object @return [Double] full load efficiency (COP)

# File lib/openstudio-standards/standards/Standards.ChillerElectricEIR.rb, line 89
def chiller_electric_eir_standard_minimum_full_load_efficiency(chiller_electric_eir)
  # Get the chiller properties
  search_criteria = chiller_electric_eir_find_search_criteria(chiller_electric_eir)
  capacity_w = chiller_electric_eir_find_capacity(chiller_electric_eir)
  return nil unless capacity_w

  capacity_tons = OpenStudio.convert(capacity_w, 'W', 'ton').get
  chlr_props = model_find_object(standards_data['chillers'], search_criteria, capacity_tons, Date.today)

  if chlr_props.nil?
    search_criteria.delete('compliance_path')
    chlr_props = model_find_object(standards_data['chillers'], search_criteria, capacity_tons, Date.today)
  end
  if chlr_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, cannot find minimum full load efficiency.")
    return nil
  else
    cop = nil
    if !chlr_props['minimum_coefficient_of_performance'].nil?
      cop = chlr_props['minimum_coefficient_of_performance']
    elsif !chlr_props['minimum_energy_efficiency_ratio'].nil?
      cop = eer_to_cop(chlr_props['minimum_energy_efficiency_ratio'])
    elsif !chlr_props['minimum_kilowatts_per_tons'].nil?
      cop = kw_per_ton_to_cop(chlr_props['minimum_kilowatts_per_tons'])
    end
    if cop.nil?
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.ChillerElectricEIR', "For #{chiller_electric_eir.name}, cannot find minimum full load efficiency.")
      return nil
    end
  end

  return cop
end
chw_sizing_control(model, chilled_water_loop, dsgn_sup_wtr_temp, dsgn_sup_wtr_temp_delt) click to toggle source

Apply sizing and controls to chilled water loop

@param model [OpenStudio::Model::Model] OpenStudio model object @param chilled_water_loop [OpenStudio::Model::PlantLoop] chilled water loop @param dsgn_sup_wtr_temp [Double] design chilled water supply T @param dsgn_sup_wtr_temp_delt [Double] design chilled water supply delta T @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 21
def chw_sizing_control(model, chilled_water_loop, dsgn_sup_wtr_temp, dsgn_sup_wtr_temp_delt)
  # chilled water loop sizing and controls
  if dsgn_sup_wtr_temp.nil?
    dsgn_sup_wtr_temp = 44.0
    dsgn_sup_wtr_temp_c = OpenStudio.convert(dsgn_sup_wtr_temp, 'F', 'C').get
  else
    dsgn_sup_wtr_temp_c = OpenStudio.convert(dsgn_sup_wtr_temp, 'F', 'C').get
  end
  if dsgn_sup_wtr_temp_delt.nil?
    dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(10.1, 'R', 'K').get
  else
    dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(dsgn_sup_wtr_temp_delt, 'R', 'K').get
  end
  chilled_water_loop.setMinimumLoopTemperature(1.0)
  chilled_water_loop.setMaximumLoopTemperature(40.0)
  sizing_plant = chilled_water_loop.sizingPlant
  sizing_plant.setLoopType('Cooling')
  sizing_plant.setDesignLoopExitTemperature(dsgn_sup_wtr_temp_c)
  sizing_plant.setLoopDesignTemperatureDifference(dsgn_sup_wtr_temp_delt_k)
  chw_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                 dsgn_sup_wtr_temp_c,
                                                                                 name: "#{chilled_water_loop.name} Temp - #{dsgn_sup_wtr_temp.round(0)}F",
                                                                                 schedule_type_limit: 'Temperature')
  chw_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, chw_temp_sch)
  chw_stpt_manager.setName("#{chilled_water_loop.name} Setpoint Manager")
  chw_stpt_manager.addToNode(chilled_water_loop.supplyOutletNode)
  # @todo Yixing check the CHW Setpoint from standards
  # @todo Should be a OutdoorAirReset, see the changes I've made in Standards.PlantLoop.apply_prm_baseline_temperatures

  return true
end
coil_cooling_dx_multi_speed_apply_efficiency_and_curves(coil_cooling_dx_multi_speed, sql_db_vars_map) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param coil_cooling_dx_multi_speed [OpenStudio::Model::CoilCoolingDXMultiSpeed] coil cooling dx multi speed object @param sql_db_vars_map [Hash] hash map @return [Hash] hash of coil objects

# File lib/openstudio-standards/standards/Standards.CoilCoolingDXMultiSpeed.rb, line 9
def coil_cooling_dx_multi_speed_apply_efficiency_and_curves(coil_cooling_dx_multi_speed, sql_db_vars_map)
  successfully_set_all_properties = true

  # Define the criteria to find the chiller properties
  # in the hvac standards data set.
  search_criteria = {}
  search_criteria['template'] = template
  cooling_type = coil_cooling_dx_multi_speed.condenserType
  search_criteria['cooling_type'] = cooling_type

  # @todo Standards - add split system vs single package to model
  # For now, assume single package as default
  sub_category = 'Single Package'

  # Determine the heating type if unitary or zone hvac
  heat_pump = false
  heating_type = nil
  containing_comp = nil
  if coil_cooling_dx_multi_speed.airLoopHVAC.empty?
    if coil_cooling_dx_multi_speed.containingHVACComponent.is_initialized
      containing_comp = coil_cooling_dx_multi_speed.containingHVACComponent.get
      if containing_comp.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.is_initialized
        htg_coil = containing_comp.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.get.heatingCoil
        if htg_coil.to_CoilHeatingDXMultiSpeed.is_initialized
          heat_pump = true
          heating_type = 'Electric Resistance or None'
        elsif htg_coil.to_CoilHeatingGasMultiStage.is_initialized
          heating_type = 'All Other'
        end
        # @todo Add other unitary systems
      end
    elsif coil_cooling_dx_multi_speed.containingZoneHVACComponent.is_initialized
      containing_comp = coil_cooling_dx_multi_speed.containingZoneHVACComponent.get
      if containing_comp.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
        sub_category = 'PTAC'
        htg_coil = containing_comp.to_ZoneHVACPackagedTerminalAirConditioner.get.heatingCoil
        if htg_coil.to_CoilHeatingElectric.is_initialized
          heating_type = 'Electric Resistance or None'
        elsif htg_coil.to_CoilHeatingWater.is_initialized || htg_coil.to_CoilHeatingGas.is_initialized || htg_col.to_CoilHeatingGasMultiStage
          heating_type = 'All Other'
        end
        # @todo Add other zone hvac systems
      end
    end
  end

  # Add the heating type to the search criteria
  unless heating_type.nil?
    search_criteria['heating_type'] = heating_type
  end

  search_criteria['subcategory'] = sub_category

  # Get the coil capacity
  capacity_w = nil
  clg_stages = stages
  if clg_stages.last.grossRatedTotalCoolingCapacity.is_initialized
    capacity_w = clg_stages.last.grossRatedTotalCoolingCapacity.get
  elsif coil_cooling_dx_multi_speed.autosizedSpeed4GrossRatedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_dx_multi_speed.autosizedSpeed4GrossRatedTotalCoolingCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{coil_cooling_dx_multi_speed.name} capacity is not available, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Volume flow rate
  flow_rate4 = nil
  if clg_stages.last.ratedAirFlowRate.is_initialized
    flow_rate4 = clg_stages.last.ratedAirFlowRate.get
  elsif coil_cooling_dx_multi_speed.autosizedSpeed4RatedAirFlowRate.is_initialized
    flow_rate4 = coil_cooling_dx_multi_speed.autosizedSpeed4RatedAirFlowRate.get
  end

  # Convert capacity to Btu/hr
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Lookup efficiencies depending on whether it is a unitary AC or a heat pump
  ac_props = nil
  ac_props = if heat_pump == true
               model_find_object(standards_data['heat_pumps'], search_criteria, capacity_btu_per_hr, Date.today)
             else
               model_find_object(standards_data['unitary_acs'], search_criteria, capacity_btu_per_hr, Date.today)
             end

  # Check to make sure properties were found
  if ac_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{coil_cooling_dx_multi_speed.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Make the COOL-CAP-FT curve
  cool_cap_ft = model_add_curve(model, ac_props['cool_cap_ft'], standards)
  if cool_cap_ft
    clg_stages.each do |stage|
      stage.setTotalCoolingCapacityFunctionofTemperatureCurve(cool_cap_ft)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{coil_cooling_dx_multi_speed.name}, cannot find cool_cap_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-CAP-FFLOW curve
  cool_cap_fflow = model_add_curve(model, ac_props['cool_cap_fflow'], standards)
  if cool_cap_fflow
    clg_stages.each do |stage|
      stage.setTotalCoolingCapacityFunctionofFlowFractionCurve(cool_cap_fflow)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{coil_cooling_dx_multi_speed.name}, cannot find cool_cap_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-EIR-FT curve
  cool_eir_ft = model_add_curve(model, ac_props['cool_eir_ft'], standards)
  if cool_eir_ft
    clg_stages.each do |stage|
      stage.setEnergyInputRatioFunctionofTemperatureCurve(cool_eir_ft)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{coil_cooling_dx_multi_speed.name}, cannot find cool_eir_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-EIR-FFLOW curve
  cool_eir_fflow = model_add_curve(model, ac_props['cool_eir_fflow'], standards)
  if cool_eir_fflow
    clg_stages.each do |stage|
      stage.setEnergyInputRatioFunctionofFlowFractionCurve(cool_eir_fflow)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{coil_cooling_dx_multi_speed.name}, cannot find cool_eir_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-PLF-FPLR curve
  cool_plf_fplr = model_add_curve(model, ac_props['cool_plf_fplr'], standards)
  if cool_plf_fplr
    clg_stages.each do |stage|
      stage.setPartLoadFractionCorrelationCurve(cool_plf_fplr)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{coil_cooling_dx_multi_speed.name}, cannot find cool_plf_fplr curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Get the minimum efficiency standards
  cop = nil

  if coil_dx_subcategory(coil_cooling_dx_multi_speed) == 'PTAC'
    ptac_eer_coeff_1 = ac_props['ptac_eer_coefficient_1']
    ptac_eer_coeff_2 = ac_props['ptac_eer_coefficient_2']
    capacity_btu_per_hr = 7000 if capacity_btu_per_hr < 7000
    capacity_btu_per_hr = 15_000 if capacity_btu_per_hr > 15_000
    ptac_eer = ptac_eer_coeff_1 + (ptac_eer_coeff_2 * capacity_btu_per_hr)
    cop = eer_to_cop_no_fan(ptac_eer)
    # self.setName("#{self.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{ptac_eer}EER")
    new_comp_name = "#{coil_cooling_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{ptac_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{template}: #{coil_cooling_dx_multi_speed.name}: #{cooling_type} #{heating_type} #{subcategory} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{ptac_eer}")
  end

  # If specified as SEER
  unless ac_props['minimum_seasonal_energy_efficiency_ratio'].nil?
    min_seer = ac_props['minimum_seasonal_energy_efficiency_ratio']
    cop = seer_to_cop_no_fan(min_seer)
    new_comp_name = "#{coil_cooling_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER"
    #      self.setName("#{self.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{template}: #{coil_cooling_dx_multi_speed.name}: #{cooling_type} #{heating_type} #{subcategory} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SEER = #{min_seer}")
  end

  # If specified as EER
  unless ac_props['minimum_energy_efficiency_ratio'].nil?
    min_eer = ac_props['minimum_energy_efficiency_ratio']
    cop = eer_to_cop_no_fan(min_eer)
    new_comp_name = "#{coil_cooling_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{template}: #{coil_cooling_dx_multi_speed.name}: #{cooling_type} #{heating_type} #{subcategory} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  # if specified as SEER (heat pump)
  unless ac_props['minimum_seasonal_efficiency'].nil?
    min_seer = ac_props['minimum_seasonal_efficiency']
    cop = seer_to_cop_no_fan(min_seer)
    new_comp_name = "#{coil_cooling_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER"
    #      self.setName("#{self.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{template}: #{coil_cooling_dx_multi_speed.name}: #{cooling_type} #{heating_type} #{subcategory} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SEER = #{min_seer}")
  end

  # If specified as EER (heat pump)
  unless ac_props['minimum_full_load_efficiency'].nil?
    min_eer = ac_props['minimum_full_load_efficiency']
    cop = eer_to_cop_no_fan(min_eer)
    new_comp_name = "#{coil_cooling_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{template}: #{coil_cooling_dx_multi_speed.name}: #{cooling_type} #{heating_type} #{subcategory} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  sql_db_vars_map[new_comp_name] = name.to_s
  coil_cooling_dx_multi_speed.setName(new_comp_name)

  # Set the efficiency values

  unless cop.nil?
    clg_stages.each do |istage|
      istage.setGrossRatedCoolingCOP(cop)
    end
  end

  return sql_db_vars_map
end
coil_cooling_dx_multi_speed_find_capacity(coil_cooling_dx_multi_speed) click to toggle source

Finds capacity in W

@param coil_cooling_dx_multi_speed [OpenStudio::Model::CoilCoolingDXMultiSpeed] coil cooling dx multi speed object @return [Double] capacity in W to be used for find object

# File lib/openstudio-standards/standards/Standards.CoilCoolingDXMultiSpeed.rb, line 224
def coil_cooling_dx_multi_speed_find_capacity(coil_cooling_dx_multi_speed)
  capacity_w = nil
  clg_stages = coil_cooling_dx_multi_speed.stages
  if clg_stages.last.grossRatedTotalCoolingCapacity.is_initialized
    capacity_w = clg_stages.last.grossRatedTotalCoolingCapacity.get
  elsif (clg_stages.size == 1) && coil_cooling_dx_multi_speed.autosizedSpeed1GrossRatedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_dx_multi_speed.autosizedSpeed1GrossRatedTotalCoolingCapacity.get
  elsif (clg_stages.size == 2) && coil_cooling_dx_multi_speed.autosizedSpeed2GrossRatedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_dx_multi_speed.autosizedSpeed2GrossRatedTotalCoolingCapacity.get
  elsif (clg_stages.size == 3) && coil_cooling_dx_multi_speed.autosizedSpeed3GrossRatedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_dx_multi_speed.autosizedSpeed3GrossRatedTotalCoolingCapacity.get
  elsif (clg_stages.size == 4) && coil_cooling_dx_multi_speed.autosizedSpeed4GrossRatedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_dx_multi_speed.autosizedSpeed4GrossRatedTotalCoolingCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{coil_cooling_dx_multi_speed.name} capacity is not available, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  return capacity_w
end
coil_cooling_dx_multi_speed_standard_minimum_cop(coil_cooling_dx_multi_speed) click to toggle source

Finds lookup object in standards and return efficiency

@param coil_cooling_dx_multi_speed [OpenStudio::Model::CoilCoolingDXMultiSpeed] coil cooling dx multi speed object @return [Array] array of full load efficiency (COP), new object name @todo align the method arguments and return types

# File lib/openstudio-standards/standards/Standards.CoilCoolingDXMultiSpeed.rb, line 251
def coil_cooling_dx_multi_speed_standard_minimum_cop(coil_cooling_dx_multi_speed)
  search_criteria = coil_dx_find_search_criteria(coil_cooling_dx_multi_speed)
  cooling_type = search_criteria['cooling_type']
  heating_type = search_criteria['heating_type']
  capacity_w = coil_cooling_dx_multi_speed_find_capacity(coil_cooling_dx_multi_speed)

  # Convert capacity to Btu/hr
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Lookup efficiencies depending on whether it is a unitary AC or a heat pump
  ac_props = nil
  ac_props = if coil_dx_heat_pump?(coil_cooling_dx_multi_speed)
               model_find_object(standards_data['heat_pumps'], search_criteria, capacity_btu_per_hr, Date.today)
             else
               model_find_object(standards_data['unitary_acs'], search_criteria, capacity_btu_per_hr, Date.today)
             end

  # Get the minimum efficiency standards
  cop = nil

  # If specified as SEER
  unless ac_props['minimum_seasonal_energy_efficiency_ratio'].nil?
    min_seer = ac_props['minimum_seasonal_energy_efficiency_ratio']
    cop = seer_to_cop_no_fan(min_seer)
    new_comp_name = "#{coil_cooling_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER"
    #      self.setName("#{self.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{template}: #{coil_cooling_dx_multi_speed.name}: #{cooling_type} #{heating_type} #{coil_dx_subcategory(coil_cooling_dx_multi_speed)} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SEER = #{min_seer}")
  end

  # If specified as EER
  unless ac_props['minimum_energy_efficiency_ratio'].nil?
    min_eer = ac_props['minimum_energy_efficiency_ratio']
    cop = eer_to_cop_no_fan(min_eer)
    new_comp_name = "#{coil_cooling_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{template}: #{coil_cooling_dx_multi_speed.name}: #{cooling_type} #{heating_type} #{coil_dx_subcategory(coil_cooling_dx_multi_speed)} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  # if specified as SEER (heat pump)
  unless ac_props['minimum_seasonal_efficiency'].nil?
    min_seer = ac_props['minimum_seasonal_efficiency']
    cop = seer_to_cop_no_fan(min_seer)
    new_comp_name = "#{coil_cooling_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER"
    #      self.setName("#{self.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{template}: #{coil_cooling_dx_multi_speed.name}: #{cooling_type} #{heating_type} #{coil_dx_subcategory(coil_cooling_dx_multi_speed)} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SEER = #{min_seer}")
  end

  # If specified as EER (heat pump)
  unless ac_props['minimum_full_load_efficiency'].nil?
    min_eer = ac_props['minimum_full_load_efficiency']
    cop = eer_to_cop_no_fan(min_eer)
    new_comp_name = "#{coil_cooling_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{template}: #{coil_cooling_dx_multi_speed.name}: #{cooling_type} #{heating_type} #{coil_dx_subcategory(coil_cooling_dx_multi_speed)} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  return cop, new_comp_name
end
coil_cooling_dx_single_speed_apply_efficiency_and_curves(coil_cooling_dx_single_speed, sql_db_vars_map, necb_ref_hp = false) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param coil_cooling_dx_single_speed [OpenStudio::Model::CoilCoolingDXSingleSpeed] coil cooling dx single speed object @param sql_db_vars_map [Hash] hash map @param necb_ref_hp [Boolean] for compatability with NECB ruleset only. @return [Hash] hash of coil objects

# File lib/openstudio-standards/standards/Standards.CoilCoolingDXSingleSpeed.rb, line 178
def coil_cooling_dx_single_speed_apply_efficiency_and_curves(coil_cooling_dx_single_speed, sql_db_vars_map, necb_ref_hp = false)
  successfully_set_all_properties = true

  # Get the search criteria.
  search_criteria = coil_dx_find_search_criteria(coil_cooling_dx_single_speed, necb_ref_hp)

  # Get the capacity.
  capacity_w = coil_cooling_dx_single_speed_find_capacity(coil_cooling_dx_single_speed, necb_ref_hp)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Lookup efficiencies depending on whether it is a unitary AC or a heat pump
  ac_props = nil
  ac_props = if coil_dx_heat_pump?(coil_cooling_dx_single_speed)
               model_find_object(standards_data['heat_pumps'], search_criteria, capacity_btu_per_hr, Date.today)
             else
               model_find_object(standards_data['unitary_acs'], search_criteria, capacity_btu_per_hr, Date.today)
             end

  # Check to make sure properties were found
  if ac_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return sql_db_vars_map
  end

  # Make the COOL-CAP-FT curve
  cool_cap_ft = model_add_curve(coil_cooling_dx_single_speed.model, ac_props['cool_cap_ft'])
  if cool_cap_ft
    coil_cooling_dx_single_speed.setTotalCoolingCapacityFunctionOfTemperatureCurve(cool_cap_ft)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}, cannot find cool_cap_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-CAP-FFLOW curve
  cool_cap_fflow = model_add_curve(coil_cooling_dx_single_speed.model, ac_props['cool_cap_fflow'])
  if cool_cap_fflow
    coil_cooling_dx_single_speed.setTotalCoolingCapacityFunctionOfFlowFractionCurve(cool_cap_fflow)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}, cannot find cool_cap_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-EIR-FT curve
  cool_eir_ft = model_add_curve(coil_cooling_dx_single_speed.model, ac_props['cool_eir_ft'])
  if cool_eir_ft
    coil_cooling_dx_single_speed.setEnergyInputRatioFunctionOfTemperatureCurve(cool_eir_ft)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}, cannot find cool_eir_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-EIR-FFLOW curve
  cool_eir_fflow = model_add_curve(coil_cooling_dx_single_speed.model, ac_props['cool_eir_fflow'])
  if cool_eir_fflow
    coil_cooling_dx_single_speed.setEnergyInputRatioFunctionOfFlowFractionCurve(cool_eir_fflow)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}, cannot find cool_eir_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-PLF-FPLR curve
  cool_plf_fplr = model_add_curve(coil_cooling_dx_single_speed.model, ac_props['cool_plf_fplr'])
  if cool_plf_fplr
    coil_cooling_dx_single_speed.setPartLoadFractionCorrelationCurve(cool_plf_fplr)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}, cannot find cool_plf_fplr curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Preserve the original name
  orig_name = coil_cooling_dx_single_speed.name.to_s

  # Find the minimum COP and rename with efficiency rating
  cop = coil_cooling_dx_single_speed_standard_minimum_cop(coil_cooling_dx_single_speed, true, necb_ref_hp)

  # Map the original name to the new name
  sql_db_vars_map[coil_cooling_dx_single_speed.name.to_s] = orig_name

  # Set the efficiency values
  unless cop.nil?
    coil_cooling_dx_single_speed.setRatedCOP(OpenStudio::OptionalDouble.new(cop))
  end

  return sql_db_vars_map
end
coil_cooling_dx_single_speed_find_capacity(coil_cooling_dx_single_speed, necb_ref_hp = false) click to toggle source

Finds capacity in W

@param coil_cooling_dx_single_speed [OpenStudio::Model::CoilCoolingDXSingleSpeed] coil cooling dx single speed object @param necb_ref_hp [Boolean] for compatability with NECB ruleset only. @return [Double] capacity in W to be used for find object

# File lib/openstudio-standards/standards/Standards.CoilCoolingDXSingleSpeed.rb, line 11
def coil_cooling_dx_single_speed_find_capacity(coil_cooling_dx_single_speed, necb_ref_hp = false)
  capacity_w = nil
  if coil_cooling_dx_single_speed.ratedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_dx_single_speed.ratedTotalCoolingCapacity.get
  elsif coil_cooling_dx_single_speed.autosizedRatedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_dx_single_speed.autosizedRatedTotalCoolingCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name} capacity is not available, cannot apply efficiency standard.")
    return 0.0
  end

  # If it's a PTAC or PTHP System, we need to divide the capacity by the potential zone multiplier
  # because the COP is dependent on capacity, and the capacity should be the capacity of a single zone, not all the zones
  if ['PTAC', 'PTHP'].include?(coil_dx_subcategory(coil_cooling_dx_single_speed))
    mult = 1
    comp = coil_cooling_dx_single_speed.containingZoneHVACComponent
    if comp.is_initialized
      if comp.get.thermalZone.is_initialized
        mult = comp.get.thermalZone.get.multiplier
        if mult > 1
          total_cap = capacity_w
          capacity_w /= mult
          OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}, total capacity of #{OpenStudio.convert(total_cap, 'W', 'kBtu/hr').get.round(2)}kBTU/hr was divided by the zone multiplier of #{mult} to give #{capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get.round(2)}kBTU/hr.")
        end
      end
    end
  end

  return capacity_w
end
coil_cooling_dx_single_speed_standard_minimum_cop(coil_cooling_dx_single_speed, rename = false, necb_ref_hp = false) click to toggle source

Finds lookup object in standards and return efficiency

@param coil_cooling_dx_single_speed [OpenStudio::Model::CoilCoolingDXSingleSpeed] coil cooling dx single speed object @param rename [Boolean] if true, object will be renamed to include capacity and efficiency level @param necb_ref_hp [Boolean] for compatability with NECB ruleset only. @return [Double] full load efficiency (COP)

# File lib/openstudio-standards/standards/Standards.CoilCoolingDXSingleSpeed.rb, line 48
def coil_cooling_dx_single_speed_standard_minimum_cop(coil_cooling_dx_single_speed, rename = false, necb_ref_hp = false)
  search_criteria = coil_dx_find_search_criteria(coil_cooling_dx_single_speed, necb_ref_hp)
  cooling_type = search_criteria['cooling_type']
  heating_type = search_criteria['heating_type']
  sub_category = search_criteria['subcategory']
  capacity_w = coil_cooling_dx_single_speed_find_capacity(coil_cooling_dx_single_speed, necb_ref_hp)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Look up the efficiency characteristics
  # Lookup efficiencies depending on whether it is a unitary AC or a heat pump
  ac_props = nil
  ac_props = if coil_dx_heat_pump?(coil_cooling_dx_single_speed)
               model_find_object(standards_data['heat_pumps'], search_criteria, capacity_btu_per_hr, Date.today)
             else
               model_find_object(standards_data['unitary_acs'], search_criteria, capacity_btu_per_hr, Date.today)
             end

  # Check to make sure properties were found
  if ac_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Get the minimum efficiency standards
  cop = nil

  # If PTHP, use equations if coefficients are specified
  pthp_eer_coeff_1 = ac_props['pthp_eer_coefficient_1']
  pthp_eer_coeff_2 = ac_props['pthp_eer_coefficient_2']
  if sub_category == 'PTHP' && !pthp_eer_coeff_1.nil? && !pthp_eer_coeff_2.nil?
    # TABLE 6.8.1D
    # EER = pthp_eer_coeff_1 - (pthp_eer_coeff_2 * Cap / 1000)
    # Note c: Cap means the rated cooling capacity of the product in Btu/h.
    # If the unit's capacity is less than 7000 Btu/h, use 7000 Btu/h in the calculation.
    # If the unit's capacity is greater than 15,000 Btu/h, use 15,000 Btu/h in the calculation.
    eer_calc_cap_btu_per_hr = capacity_btu_per_hr
    eer_calc_cap_btu_per_hr = 7000 if capacity_btu_per_hr < 7000
    eer_calc_cap_btu_per_hr = 15_000 if capacity_btu_per_hr > 15_000
    pthp_eer = pthp_eer_coeff_1 - (pthp_eer_coeff_2 * eer_calc_cap_btu_per_hr / 1000.0)
    cop = eer_to_cop_no_fan(pthp_eer)
    new_comp_name = "#{coil_cooling_dx_single_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{pthp_eer.round(1)}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{pthp_eer.round(1)}")
  end

  # If PTAC, use equations if coefficients are specified
  ptac_eer_coeff_1 = ac_props['ptac_eer_coefficient_1']
  ptac_eer_coeff_2 = ac_props['ptac_eer_coefficient_2']
  if sub_category == 'PTAC' && !ptac_eer_coeff_1.nil? && !ptac_eer_coeff_2.nil?
    # TABLE 6.8.1D
    # EER = ptac_eer_coeff_1 - (ptac_eer_coeff_2 * Cap / 1000)
    # Note c: Cap means the rated cooling capacity of the product in Btu/h.
    # If the unit's capacity is less than 7000 Btu/h, use 7000 Btu/h in the calculation.
    # If the unit's capacity is greater than 15,000 Btu/h, use 15,000 Btu/h in the calculation.
    eer_calc_cap_btu_per_hr = capacity_btu_per_hr
    eer_calc_cap_btu_per_hr = 7000 if capacity_btu_per_hr < 7000
    eer_calc_cap_btu_per_hr = 15_000 if capacity_btu_per_hr > 15_000
    ptac_eer = ptac_eer_coeff_1 - (ptac_eer_coeff_2 * eer_calc_cap_btu_per_hr / 1000.0)
    cop = eer_to_cop_no_fan(ptac_eer)
    new_comp_name = "#{coil_cooling_dx_single_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{ptac_eer.round(1)}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{ptac_eer.round(1)}")
  end

  # If CRAC, use equations if coefficients are specified
  crac_minimum_scop = ac_props['minimum_scop']
  if sub_category == 'CRAC' && !crac_minimum_scop.nil?
    # TABLE 6.8.1K in 90.1-2010, TABLE 6.8.1-10 in 90.1-2019
    # cop = scop/sensible heat ratio
    if coil_cooling_dx_single_speed.ratedSensibleHeatRatio.is_initialized
      crac_sensible_heat_ratio = coil_cooling_dx_single_speed.ratedSensibleHeatRatio.get
    elsif coil_cooling_dx_single_speed.autosizedRatedSensibleHeatRatio.is_initialized
      # Though actual inlet temperature is very high (thus basically no dehumidification),
      # sensible heat ratio can't be pre-assigned as 1 because it should be the value at conditions defined in ASHRAE Standard 127 => 26.7 degC drybulb/19.4 degC wetbulb.
      crac_sensible_heat_ratio = coil_cooling_dx_single_speed.autosizedRatedSensibleHeatRatio.get
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.CoilCoolingDXSingleSpeed', 'Failed to get autosized sensible heat ratio')
    end
    cop = crac_minimum_scop / crac_sensible_heat_ratio
    cop = cop.round(2)
    new_comp_name = "#{coil_cooling_dx_single_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{crac_minimum_scop}SCOP #{cop}COP"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{coil_cooling_dx_single_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SCOP = #{crac_minimum_scop}")
  end

  # If specified as SEER
  unless ac_props['minimum_seasonal_energy_efficiency_ratio'].nil?
    min_seer = ac_props['minimum_seasonal_energy_efficiency_ratio']
    cop = seer_to_cop_no_fan(min_seer)
    new_comp_name = "#{coil_cooling_dx_single_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{template}: #{coil_cooling_dx_single_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SEER = #{min_seer}")
  end

  # If specified as EER
  unless ac_props['minimum_energy_efficiency_ratio'].nil?
    min_eer = ac_props['minimum_energy_efficiency_ratio']
    cop = eer_to_cop_no_fan(min_eer)
    new_comp_name = "#{coil_cooling_dx_single_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{template}: #{coil_cooling_dx_single_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  # if specified as SEER (heat pump)
  unless ac_props['minimum_seasonal_efficiency'].nil?
    min_seer = ac_props['minimum_seasonal_efficiency']
    cop = seer_to_cop_no_fan(min_seer)
    new_comp_name = "#{coil_cooling_dx_single_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{template}: #{coil_cooling_dx_single_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SEER = #{min_seer}")
  end

  # If specified as EER (heat pump)
  unless ac_props['minimum_full_load_efficiency'].nil?
    min_eer = ac_props['minimum_full_load_efficiency']
    cop = eer_to_cop_no_fan(min_eer)
    new_comp_name = "#{coil_cooling_dx_single_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXSingleSpeed', "For #{template}: #{coil_cooling_dx_single_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  # Rename
  if rename
    coil_cooling_dx_single_speed.setName(new_comp_name)
  end

  return cop
end
coil_cooling_dx_two_speed_apply_efficiency_and_curves(coil_cooling_dx_two_speed, sql_db_vars_map) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param coil_cooling_dx_two_speed [OpenStudio::Model::CoilCoolingDXTwoSpeed] coil cooling dx two speed object @param sql_db_vars_map [Hash] hash map @return [Hash] hash of coil objects

# File lib/openstudio-standards/standards/Standards.CoilCoolingDXTwoSpeed.rb, line 107
def coil_cooling_dx_two_speed_apply_efficiency_and_curves(coil_cooling_dx_two_speed, sql_db_vars_map)
  successfully_set_all_properties = true

  # Get the search criteria
  search_criteria = coil_dx_find_search_criteria(coil_cooling_dx_two_speed)

  # Get the capacity
  capacity_w = coil_cooling_dx_two_speed_find_capacity(coil_cooling_dx_two_speed)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Lookup efficiencies depending on whether it is a unitary AC or a heat pump
  ac_props = nil
  ac_props = if coil_dx_heat_pump?(coil_cooling_dx_two_speed)
               model_find_object(standards_data['heat_pumps'], search_criteria, capacity_btu_per_hr, Date.today)
             else
               model_find_object(standards_data['unitary_acs'], search_criteria, capacity_btu_per_hr, Date.today)
             end

  # Check to make sure properties were found
  if ac_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return sql_db_vars_map
  end

  # Make the total COOL-CAP-FT curve
  tot_cool_cap_ft = model_add_curve(coil_cooling_dx_two_speed.model, ac_props['cool_cap_ft'])
  if tot_cool_cap_ft
    coil_cooling_dx_two_speed.setTotalCoolingCapacityFunctionOfTemperatureCurve(tot_cool_cap_ft)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find cool_cap_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the total COOL-CAP-FFLOW curve
  tot_cool_cap_fflow = model_add_curve(coil_cooling_dx_two_speed.model, ac_props['cool_cap_fflow'])
  if tot_cool_cap_fflow
    coil_cooling_dx_two_speed.setTotalCoolingCapacityFunctionOfFlowFractionCurve(tot_cool_cap_fflow)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find cool_cap_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-EIR-FT curve
  cool_eir_ft = model_add_curve(coil_cooling_dx_two_speed.model, ac_props['cool_eir_ft'])
  if cool_eir_ft
    coil_cooling_dx_two_speed.setEnergyInputRatioFunctionOfTemperatureCurve(cool_eir_ft)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find cool_eir_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-EIR-FFLOW curve
  cool_eir_fflow = model_add_curve(coil_cooling_dx_two_speed.model, ac_props['cool_eir_fflow'])
  if cool_eir_fflow
    coil_cooling_dx_two_speed.setEnergyInputRatioFunctionOfFlowFractionCurve(cool_eir_fflow)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find cool_eir_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the COOL-PLF-FPLR curve
  cool_plf_fplr = model_add_curve(coil_cooling_dx_two_speed.model, ac_props['cool_plf_fplr'])
  if cool_plf_fplr
    coil_cooling_dx_two_speed.setPartLoadFractionCorrelationCurve(cool_plf_fplr)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find cool_plf_fplr curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the low speed COOL-CAP-FT curve
  low_speed_cool_cap_ft = model_add_curve(coil_cooling_dx_two_speed.model, ac_props['cool_cap_ft'])
  if low_speed_cool_cap_ft
    coil_cooling_dx_two_speed.setLowSpeedTotalCoolingCapacityFunctionOfTemperatureCurve(low_speed_cool_cap_ft)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find cool_cap_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the low speed COOL-EIR-FT curve
  low_speed_cool_eir_ft = model_add_curve(coil_cooling_dx_two_speed.model, ac_props['cool_eir_ft'])
  if low_speed_cool_eir_ft
    coil_cooling_dx_two_speed.setLowSpeedEnergyInputRatioFunctionOfTemperatureCurve(low_speed_cool_eir_ft)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find cool_eir_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Preserve the original name
  orig_name = coil_cooling_dx_two_speed.name.to_s

  # Find the minimum COP and rename with efficiency rating
  cop = coil_cooling_dx_two_speed_standard_minimum_cop(coil_cooling_dx_two_speed, true)

  # Map the original name to the new name
  sql_db_vars_map[coil_cooling_dx_two_speed.name.to_s] = orig_name

  # Set the efficiency values
  unless cop.nil?
    coil_cooling_dx_two_speed.setRatedHighSpeedCOP(cop)
    coil_cooling_dx_two_speed.setRatedLowSpeedCOP(cop)
  end

  return sql_db_vars_map
end
coil_cooling_dx_two_speed_find_capacity(coil_cooling_dx_two_speed) click to toggle source

Finds capacity in W

@param coil_cooling_dx_two_speed [OpenStudio::Model::CoilCoolingDXTwoSpeed] coil cooling dx two speed object @return [Double] capacity in W to be used for find object

# File lib/openstudio-standards/standards/Standards.CoilCoolingDXTwoSpeed.rb, line 10
def coil_cooling_dx_two_speed_find_capacity(coil_cooling_dx_two_speed)
  capacity_w = nil
  if coil_cooling_dx_two_speed.ratedHighSpeedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_dx_two_speed.ratedHighSpeedTotalCoolingCapacity.get
  elsif coil_cooling_dx_two_speed.autosizedRatedHighSpeedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_dx_two_speed.autosizedRatedHighSpeedTotalCoolingCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name} capacity is not available, cannot apply efficiency standard.")
    return 0.0
  end

  return capacity_w
end
coil_cooling_dx_two_speed_standard_minimum_cop(coil_cooling_dx_two_speed, rename = false) click to toggle source

Finds lookup object in standards and return efficiency

@param coil_cooling_dx_two_speed [OpenStudio::Model::CoilCoolingDXTwoSpeed] coil cooling dx two speed object @param rename [Boolean] if true, object will be renamed to include capacity and efficiency level @return [Double] full load efficiency (COP)

# File lib/openstudio-standards/standards/Standards.CoilCoolingDXTwoSpeed.rb, line 29
def coil_cooling_dx_two_speed_standard_minimum_cop(coil_cooling_dx_two_speed, rename = false)
  search_criteria = coil_dx_find_search_criteria(coil_cooling_dx_two_speed)
  cooling_type = search_criteria['cooling_type']
  heating_type = search_criteria['heating_type']
  sub_category = search_criteria['subcategory']
  capacity_w = coil_cooling_dx_two_speed_find_capacity(coil_cooling_dx_two_speed)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Lookup efficiencies depending on whether it is a unitary AC or a heat pump
  ac_props = nil
  ac_props = if coil_dx_heat_pump?(coil_cooling_dx_two_speed)
               model_find_object(standards_data['heat_pumps'], search_criteria, capacity_btu_per_hr, Date.today)
             else
               model_find_object(standards_data['unitary_acs'], search_criteria, capacity_btu_per_hr, Date.today)
             end

  # Check to make sure properties were found
  if ac_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Get the minimum efficiency standards
  cop = nil

  # Check to make sure properties were found
  if ac_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{coil_cooling_dx_two_speed.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    return cop # value of nil
  end

  # If specified as SEER
  unless ac_props['minimum_seasonal_energy_efficiency_ratio'].nil?
    min_seer = ac_props['minimum_seasonal_energy_efficiency_ratio']
    cop = seer_to_cop_no_fan(min_seer)
    new_comp_name = "#{coil_cooling_dx_two_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{template}: #{coil_cooling_dx_two_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SEER = #{min_seer}")
  end

  # If specified as EER
  unless ac_props['minimum_energy_efficiency_ratio'].nil?
    min_eer = ac_props['minimum_energy_efficiency_ratio']
    cop = eer_to_cop_no_fan(min_eer)
    new_comp_name = "#{coil_cooling_dx_two_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{template}: #{coil_cooling_dx_two_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  # if specified as SEER (heat pump)
  unless ac_props['minimum_seasonal_efficiency'].nil?
    min_seer = ac_props['minimum_seasonal_efficiency']
    cop = seer_to_cop_no_fan(min_seer)
    new_comp_name = "#{coil_cooling_dx_two_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{template}: #{coil_cooling_dx_two_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SEER = #{min_seer}")
  end

  # If specified as EER (heat pump)
  unless ac_props['minimum_full_load_efficiency'].nil?
    min_eer = ac_props['minimum_full_load_efficiency']
    cop = eer_to_cop_no_fan(min_eer)
    new_comp_name = "#{coil_cooling_dx_two_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingDXTwoSpeed', "For #{template}: #{coil_cooling_dx_two_speed.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  # Rename
  if rename
    coil_cooling_dx_two_speed.setName(new_comp_name)
  end

  return cop
end
coil_cooling_water_to_air_heat_pump_apply_efficiency_and_curves(coil_cooling_water_to_air_heat_pump, sql_db_vars_map) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param coil_cooling_water_to_air_heat_pump [OpenStudio::Model::CoilCoolingWaterToAirHeatPumpEquationFit] coil cooling object @param sql_db_vars_map [Hash] hash map @return [Hash] hash of coil objects

# File lib/openstudio-standards/standards/Standards.CoilCoolingWaterToAirHeatPumpEquationFit.rb, line 105
def coil_cooling_water_to_air_heat_pump_apply_efficiency_and_curves(coil_cooling_water_to_air_heat_pump, sql_db_vars_map)
  # Get the search criteria
  search_criteria = {}
  search_criteria['template'] = template
  capacity_w = coil_cooling_water_to_air_heat_pump_find_capacity(coil_cooling_water_to_air_heat_pump)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get

  # Look up the efficiency characteristics
  coil_props = model_find_object(standards_data['water_source_heat_pumps'], search_criteria, capacity_btu_per_hr, Date.today)

  # Check to make sure properties were found
  if coil_props.nil?
    # search again without capacity
    matching_objects = model_find_objects(standards_data['water_source_heat_pumps'], search_criteria, nil, Date.today)
    if matching_objects.size.zero?
      # This proves that the search_criteria has issue finding the correct coil prop
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingWaterToAirHeatPumpEquationFit', "For #{coil_cooling_water_to_air_heat_pump.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    else
      # Issue warning indicate the coil size is may be too large
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingWaterToAirHeatPumpEquationFit', "The capacity of the coil: #{coil_cooling_water_to_air_heat_pump.name} maybe too large to be found in the efficiency standard. The coil capacity is #{capacity_btu_per_hr} Btu/hr.")
    end
    return sql_db_vars_map
  end

  # @todo Add methods to set coefficients, and add coefficients to data spreadsheet
  # using OS defaults for now
  # tot_cool_cap_coeff1 = coil_props['tot_cool_cap_coeff1']
  # if tot_cool_cap_coeff1
  #   coil_cooling_water_to_air_heat_pump.setTotalCoolingCapacityCoefficient1(tot_cool_cap_coeff1)
  # else
  #   OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingWaterToAirHeatPumpEquationFit', "For #{coil_cooling_water_to_air_heat_pump.name}, cannot find tot_cool_cap_coeff1, will not be set.")
  #   successfully_set_all_properties = false
  # end

  # Preserve the original name
  orig_name = coil_cooling_water_to_air_heat_pump.name.to_s

  # Find the minimum COP and rename with efficiency rating
  cop = coil_cooling_water_to_air_heat_pump_standard_minimum_cop(coil_cooling_water_to_air_heat_pump, true)

  # Map the original name to the new name
  sql_db_vars_map[coil_cooling_water_to_air_heat_pump.name.to_s] = orig_name

  # Set the efficiency values
  unless cop.nil?
    coil_cooling_water_to_air_heat_pump.setRatedCoolingCoefficientofPerformance(cop)
  end

  return sql_db_vars_map
end
coil_cooling_water_to_air_heat_pump_find_capacity(coil_cooling_water_to_air_heat_pump) click to toggle source

Finds capacity in W

@param coil_cooling_water_to_air_heat_pump [OpenStudio::Model::CoilCoolingWaterToAirHeatPumpEquationFit] coil cooling object @return [Double] capacity in W to be used for find object

# File lib/openstudio-standards/standards/Standards.CoilCoolingWaterToAirHeatPumpEquationFit.rb, line 8
def coil_cooling_water_to_air_heat_pump_find_capacity(coil_cooling_water_to_air_heat_pump)
  capacity_w = nil
  if coil_cooling_water_to_air_heat_pump.ratedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_water_to_air_heat_pump.ratedTotalCoolingCapacity.get
  elsif coil_cooling_water_to_air_heat_pump.autosizedRatedTotalCoolingCapacity.is_initialized
    capacity_w = coil_cooling_water_to_air_heat_pump.autosizedRatedTotalCoolingCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingWaterToAirHeatPumpEquationFit', "For #{coil_cooling_water_to_air_heat_pump.name} capacity is not available, cannot apply efficiency standard.")
    return 0.0
  end

  return capacity_w
end
coil_cooling_water_to_air_heat_pump_standard_minimum_cop(coil_cooling_water_to_air_heat_pump, rename = false, computer_room_air_conditioner = false) click to toggle source

Finds lookup object in standards and return efficiency

@param coil_cooling_water_to_air_heat_pump [OpenStudio::Model::CoilCoolingWaterToAirHeatPumpEquationFit] coil cooling object @param rename [Boolean] if true, object will be renamed to include capacity and efficiency level @return [Double] full load efficiency (COP)

# File lib/openstudio-standards/standards/Standards.CoilCoolingWaterToAirHeatPumpEquationFit.rb, line 27
def coil_cooling_water_to_air_heat_pump_standard_minimum_cop(coil_cooling_water_to_air_heat_pump, rename = false, computer_room_air_conditioner = false)
  search_criteria = {}
  search_criteria['template'] = template
  if computer_room_air_conditioner
    search_criteria['cooling_type'] = 'WaterCooled'
    search_criteria['heating_type'] = 'All Other'
    search_criteria['subcategory'] = 'CRAC'
    cooling_type = search_criteria['cooling_type']
    heating_type = search_criteria['heating_type']
    sub_category = search_criteria['subcategory']
  end
  capacity_w = coil_cooling_water_to_air_heat_pump_find_capacity(coil_cooling_water_to_air_heat_pump)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get
  return nil unless capacity_kbtu_per_hr > 0.0

  # Look up the efficiency characteristics
  if computer_room_air_conditioner
    equipment_type = 'unitary_acs'
  else
    equipment_type = 'water_source_heat_pumps'
  end
  coil_props = model_find_object(standards_data[equipment_type], search_criteria, capacity_btu_per_hr, Date.today)

  # Check to make sure properties were found
  if coil_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingWaterToAirHeatPumpEquationFit', "For #{coil_cooling_water_to_air_heat_pump.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Get the minimum efficiency standards
  cop = nil

  # If specified as EER (heat pump)
  unless coil_props['minimum_full_load_efficiency'].nil?
    min_eer = coil_props['minimum_full_load_efficiency']
    cop = eer_to_cop_no_fan(min_eer, capacity_w = nil)
    new_comp_name = "#{coil_cooling_water_to_air_heat_pump.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingWaterToAirHeatPumpEquationFit', "For #{template}: #{coil_cooling_water_to_air_heat_pump.name}: Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  # If specified as SCOP (water-cooled Computer Room Air Conditioned (CRAC))
  if computer_room_air_conditioner
    crac_minimum_scop = coil_props['minimum_scop']
    unless crac_minimum_scop.nil?
      # cop = scop / sensible heat ratio
      # sensible heat ratio = sensible cool capacity / total cool capacity
      if coil_cooling_water_to_air_heat_pump.ratedSensibleCoolingCapacity.is_initialized
        crac_sensible_cool = coil_cooling_water_to_air_heat_pump.ratedSensibleCoolingCapacity.get
        crac_total_cool = coil_cooling_water_to_air_heat_pump.ratedTotalCoolingCapacity.get
        crac_sensible_cool_ratio = crac_sensible_cool / crac_total_cool
      elsif coil_cooling_water_to_air_heat_pump.autosizedRatedSensibleCoolingCapacity.is_initialized
        crac_sensible_cool = coil_cooling_water_to_air_heat_pump.autosizedRatedSensibleCoolingCapacity.get
        crac_total_cool = coil_cooling_water_to_air_heat_pump.autosizedRatedTotalCoolingCapacity.get
        crac_sensible_heat_ratio = crac_sensible_cool / crac_total_cool
      else
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.CoilCoolingWaterToAirHeatPumpEquationFit', 'Failed to get autosized sensible cool capacity')
      end
      cop = crac_minimum_scop / crac_sensible_heat_ratio
      cop = cop.round(2)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilCoolingWaterToAirHeatPumpEquationFit', "For #{coil_cooling_water_to_air_heat_pump.name}: #{cooling_type} #{heating_type} #{sub_category} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SCOP = #{crac_minimum_scop}")
    end
  end

  # Rename
  if rename
    coil_cooling_water_to_air_heat_pump.setName(new_comp_name)
  end

  return cop
end
coil_heating_dx_multi_speed_apply_efficiency_and_curves(coil_heating_dx_multi_speed, sql_db_vars_map) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param coil_heating_dx_multi_speed [OpenStudio::Model::CoilHeatingDXMultiSpeed] coil heating dx multi speed object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.CoilHeatingDXMultiSpeed.rb, line 8
def coil_heating_dx_multi_speed_apply_efficiency_and_curves(coil_heating_dx_multi_speed, sql_db_vars_map)
  successfully_set_all_properties = true

  # Define the criteria to find the unitary properties
  # in the hvac standards data set.
  search_criteria = {}
  search_criteria['template'] = template

  # Determine supplemental heating type if unitary
  heat_pump = false
  suppl_heating_type = nil
  if coil_heating_dx_multi_speed.airLoopHVAC.empty?
    if coil_heating_dx_multi_speed.containingHVACComponent.is_initialized
      containing_comp = coil_heating_dx_multi_speed.containingHVACComponent.get
      if containing_comp.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.is_initialized
        heat_pump = true
        htg_coil = containing_comp.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.get.supplementalHeatingCoil
        suppl_heating_type = if htg_coil.to_CoilHeatingElectric.is_initialized
                               'Electric Resistance or None'
                             else
                               'All Other'
                             end
      end
      # @todo Add other unitary systems
    end
  end

  # @todo Standards - add split system vs single package to model
  # For now, assume single package
  subcategory = 'Single Package'
  search_criteria['subcategory'] = subcategory

  # Get the coil capacity
  clg_capacity = nil
  if heat_pump == true
    containing_comp = coil_heating_dx_multi_speed.containingHVACComponent.get
    heat_pump_comp = containing_comp.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.get
    ccoil = heat_pump_comp.coolingCoil
    dxcoil = ccoil.to_CoilCoolingDXMultiSpeed.get
    dxcoil_name = dxcoil.name.to_s
    if sql_db_vars_map
      if sql_db_vars_map[dxcoil_name]
        dxcoil.setName(sql_db_vars_map[dxcoil_name])
      end
    end
    clg_stages = dxcoil.stages
    if clg_stages.last.grossRatedTotalCoolingCapacity.is_initialized
      clg_capacity = clg_stages.last.grossRatedTotalCoolingCapacity.get
    elsif dxcoil.autosizedSpeed4GrossRatedTotalCoolingCapacity.is_initialized
      clg_capacity = dxcoil.autosizedSpeed4GrossRatedTotalCoolingCapacity.get
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{coil_heating_dx_multi_speed.name} capacity is not available, cannot apply efficiency standard.")
      successfully_set_all_properties = false
      return successfully_set_all_properties
    end
    dxcoil.setName(dxcoil_name)
  end

  # Convert capacity to Btu/hr
  capacity_btu_per_hr = OpenStudio.convert(clg_capacity, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(clg_capacity, 'W', 'kBtu/hr').get

  # Lookup efficiencies depending on whether it is a unitary AC or a heat pump
  hp_props = model_find_object(standards_data['heat_pumps'], search_criteria, capacity_btu_per_hr, Date.today)

  # Check to make sure properties were found
  if hp_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXMultipeed', "For #{coil_heating_dx_multi_speed.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Make the HEAT-CAP-FT curve
  htg_stages = stages
  heat_cap_ft = model_add_curve(model, hp_props['heat_cap_ft'], standards)
  if heat_cap_ft
    htg_stages.each do |istage|
      istage.setHeatingCapacityFunctionofTemperatureCurve(heat_cap_ft)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{coil_heating_dx_multi_speed.name}, cannot find heat_cap_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the HEAT-CAP-FFLOW curve
  heat_cap_fflow = model_add_curve(model, hp_props['heat_cap_fflow'], standards)
  if heat_cap_fflow
    htg_stages.each do |istage|
      istage.setHeatingCapacityFunctionofFlowFractionCurve(heat_cap_fflow)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{coil_heating_dx_multi_speed.name}, cannot find heat_cap_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the HEAT-EIR-FT curve
  heat_eir_ft = model_add_curve(model, hp_props['heat_eir_ft'], standards)
  if heat_eir_ft
    htg_stages.each do |istage|
      istage.setEnergyInputRatioFunctionofTemperatureCurve(heat_eir_ft)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{coil_heating_dx_multi_speed.name}, cannot find heat_eir_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the HEAT-EIR-FFLOW curve
  heat_eir_fflow = model_add_curve(model, hp_props['heat_eir_fflow'], standards)
  if heat_eir_fflow
    htg_stages.each do |istage|
      istage.setEnergyInputRatioFunctionofFlowFractionCurve(heat_eir_fflow)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{coil_heating_dx_multi_speed.name}, cannot find heat_eir_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the HEAT-PLF-FPLR curve
  heat_plf_fplr = model_add_curve(model, hp_props['heat_plf_fplr'], standards)
  if heat_plf_fplr
    htg_stages.each do |istage|
      istage.setPartLoadFractionCorrelationCurve(heat_plf_fplr)
    end
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{coil_heating_dx_multi_speed.name}, cannot find heat_plf_fplr curve, will not be set.")
    successfully_set_all_properties = false
  end

  htg_capacity = nil
  flow_rate4 = nil
  htg_stages = coil_heating_dx_multi_speed.stages
  if htg_stages.last.grossRatedHeatingCapacity.is_initialized
    htg_capacity = htg_stages.last.grossRatedHeatingCapacity.get
  elsif coil_heating_dx_multi_speed.autosizedSpeed4GrossRatedHeatingCapacity.is_initialized
    htg_capacity = coil_heating_dx_multi_speed.autosizedSpeed4GrossRatedHeatingCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{coil_heating_dx_multi_speed.name} capacity is not available, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end
  if htg_stages.last.ratedAirFlowRate.is_initialized
    flow_rate4 = htg_stages.last.ratedAirFlowRate.get
  elsif coil_heating_dx_multi_speed.autosizedSpeed4RatedAirFlowRate.is_initialized
    flow_rate4 = coil_heating_dx_multi_speed.autosizedSpeed4RatedAirFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{coil_heating_dx_multi_speed.name} capacity is not available, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Convert capacity to Btu/hr
  capacity_btu_per_hr = OpenStudio.convert(htg_capacity, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(htg_capacity, 'W', 'kBtu/hr').get

  # Get the minimum efficiency standards
  cop = nil

  # If specified as SEER
  unless hp_props['minimum_seasonal_energy_efficiency_ratio'].nil?
    min_seer = hp_props['minimum_seasonal_energy_efficiency_ratio']
    cop = seer_to_cop_no_fan(min_seer)
    coil_heating_dx_multi_speed.setName("#{coil_heating_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_seer}SEER")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{template}: #{coil_heating_dx_multi_speed.name}: #{suppl_heating_type} #{subcategory} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; SEER = #{min_seer}")
  end

  # If specified as EER
  unless hp_props['minimum_energy_efficiency_ratio'].nil?
    min_eer = hp_props['minimum_energy_efficiency_ratio']
    cop = eer_to_cop_no_fan(min_eer)
    coil_heating_dx_multi_speed.setName("#{coil_heating_dx_multi_speed.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_eer}EER")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingDXMultiSpeed', "For #{template}: #{coil_heating_dx_multi_speed.name}:  #{suppl_heating_type} #{subcategory} Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  # Set the efficiency values
  return false if cop.nil?

  htg_stages.each do |istage|
    istage.setGrossRatedHeatingCOP(cop)
  end
  return true
end
coil_heating_dx_single_speed_apply_defrost_eir_curve_limits(htg_coil) click to toggle source

sets defrost curve limits

@param htg_coil [OpenStudio::Model::CoilHeatingDXSingleSpeed] a DX heating coil @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilHeatingDXSingleSpeed.rb, line 204
def coil_heating_dx_single_speed_apply_defrost_eir_curve_limits(htg_coil)
  return false unless htg_coil.defrostEnergyInputRatioFunctionofTemperatureCurve.is_initialized

  def_eir_f_of_temp = htg_coil.defrostEnergyInputRatioFunctionofTemperatureCurve.get.to_CurveBiquadratic.get
  def_eir_f_of_temp.setMinimumValueofx(12.77778)
  def_eir_f_of_temp.setMaximumValueofx(23.88889)
  def_eir_f_of_temp.setMinimumValueofy(21.11111)
  def_eir_f_of_temp.setMaximumValueofy(46.11111)

  return true
end
coil_heating_dx_single_speed_apply_efficiency_and_curves(coil_heating_dx_single_speed, sql_db_vars_map, necb_ref_hp = false) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param coil_heating_dx_single_speed [OpenStudio::Model::CoilHeatingDXSingleSpeed] coil heating dx single speed object @param sql_db_vars_map [Hash] hash map @param necb_ref_hp [Boolean] for compatability with NECB ruleset only. @return [Hash] hash of coil objects

# File lib/openstudio-standards/standards/Standards.CoilHeatingDXSingleSpeed.rb, line 186
def coil_heating_dx_single_speed_apply_efficiency_and_curves(coil_heating_dx_single_speed, sql_db_vars_map, necb_ref_hp = false)
  successfully_set_all_properties = true

  # Get the search criteria
  search_criteria = coil_dx_find_search_criteria(coil_heating_dx_single_speed, necb_ref_hp)

  # Get the capacity
  capacity_w = coil_heating_dx_single_speed_find_capacity(coil_heating_dx_single_speed, necb_ref_hp)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Lookup efficiencies
  ac_props = model_find_object(standards_data['heat_pumps_heating'], search_criteria, capacity_btu_per_hr, Date.today)

  # Check to make sure properties were found
  if ac_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return sql_db_vars_map
  end

  # Make the HEAT-CAP-FT curve
  heat_cap_ft = model_add_curve(coil_heating_dx_single_speed.model, ac_props['heat_cap_ft'])
  if heat_cap_ft
    coil_heating_dx_single_speed.setTotalHeatingCapacityFunctionofTemperatureCurve(heat_cap_ft)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}, cannot find heat_cap_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the HEAT-CAP-FFLOW curve
  heat_cap_fflow = model_add_curve(coil_heating_dx_single_speed.model, ac_props['heat_cap_fflow'])
  if heat_cap_fflow
    coil_heating_dx_single_speed.setTotalHeatingCapacityFunctionofFlowFractionCurve(heat_cap_fflow)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}, cannot find heat_cap_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the HEAT-EIR-FT curve
  heat_eir_ft = model_add_curve(coil_heating_dx_single_speed.model, ac_props['heat_eir_ft'])
  if heat_eir_ft
    coil_heating_dx_single_speed.setEnergyInputRatioFunctionofTemperatureCurve(heat_eir_ft)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}, cannot find heat_eir_ft curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the HEAT-EIR-FFLOW curve
  heat_eir_fflow = model_add_curve(coil_heating_dx_single_speed.model, ac_props['heat_eir_fflow'])
  if heat_eir_fflow
    coil_heating_dx_single_speed.setEnergyInputRatioFunctionofFlowFractionCurve(heat_eir_fflow)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}, cannot find heat_eir_fflow curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Make the HEAT-PLF-FPLR curve
  heat_plf_fplr = model_add_curve(coil_heating_dx_single_speed.model, ac_props['heat_plf_fplr'])
  if heat_plf_fplr
    coil_heating_dx_single_speed.setPartLoadFractionCorrelationCurve(heat_plf_fplr)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}, cannot find heat_plf_fplr curve, will not be set.")
    successfully_set_all_properties = false
  end

  # Preserve the original name
  orig_name = coil_heating_dx_single_speed.name.to_s

  # Find the minimum COP and rename with efficiency rating
  cop = coil_heating_dx_single_speed_standard_minimum_cop(coil_heating_dx_single_speed, true, necb_ref_hp)

  # Map the original name to the new name
  sql_db_vars_map[coil_heating_dx_single_speed.name.to_s] = orig_name

  # Set the efficiency values
  unless cop.nil?
    coil_heating_dx_single_speed.setRatedCOP(cop)
  end

  return sql_db_vars_map
end
coil_heating_dx_single_speed_find_capacity(coil_heating_dx_single_speed, necb_ref_hp = false) click to toggle source

Finds capacity in W. This is the cooling capacity of the paired DX cooling coil.

@param coil_heating_dx_single_speed [OpenStudio::Model::CoilHeatingDXSingleSpeed] coil heating dx single speed object @param necb_ref_hp [Boolean] for compatability with NECB ruleset only. @return [Double] capacity in W to be used for find object

# File lib/openstudio-standards/standards/Standards.CoilHeatingDXSingleSpeed.rb, line 11
def coil_heating_dx_single_speed_find_capacity(coil_heating_dx_single_speed, necb_ref_hp = false)
  capacity_w = nil

  # Get the paired cooling coil
  clg_coil = nil

  # Unitary and zone equipment
  if coil_heating_dx_single_speed.airLoopHVAC.empty?
    if coil_heating_dx_single_speed.containingHVACComponent.is_initialized
      containing_comp = coil_heating_dx_single_speed.containingHVACComponent.get
      if containing_comp.to_AirLoopHVACUnitaryHeatPumpAirToAir.is_initialized
        clg_coil = containing_comp.to_AirLoopHVACUnitaryHeatPumpAirToAir.get.coolingCoil
      elsif containing_comp.to_AirLoopHVACUnitarySystem.is_initialized
        unitary = containing_comp.to_AirLoopHVACUnitarySystem.get
        if unitary.coolingCoil.is_initialized
          clg_coil = unitary.coolingCoil.get
        end
      end
      # @todo Add other unitary systems
    elsif coil_heating_dx_single_speed.containingZoneHVACComponent.is_initialized
      containing_comp = coil_heating_dx_single_speed.containingZoneHVACComponent.get
      # PTHP
      if containing_comp.to_ZoneHVACPackagedTerminalHeatPump.is_initialized
        pthp = containing_comp.to_ZoneHVACPackagedTerminalHeatPump.get
        clg_coil = containing_comp.to_ZoneHVACPackagedTerminalHeatPump.get.coolingCoil
      end
    end
  end

  # On AirLoop directly
  if coil_heating_dx_single_speed.airLoopHVAC.is_initialized
    air_loop = coil_heating_dx_single_speed.airLoopHVAC.get
    # Check for the presence of any other type of cooling coil
    clg_types = ['OS:Coil:Cooling:DX:SingleSpeed',
                 'OS:Coil:Cooling:DX:TwoSpeed',
                 'OS:Coil:Cooling:DX:MultiSpeed']
    clg_types.each do |ct|
      coils = air_loop.supplyComponents(ct.to_IddObjectType)
      next if coils.empty?

      clg_coil = coils[0]
      break # Stop on first DX cooling coil found
    end
  end

  # If no paired cooling coil was found,
  # throw an error and fall back to the heating capacity
  # of the DX heating coil
  if clg_coil.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}, the paired DX cooling coil could not be found to determine capacity. Efficiency will incorrectly be based on DX coil's heating capacity.")
    if coil_heating_dx_single_speed.ratedTotalHeatingCapacity.is_initialized
      capacity_w = coil_heating_dx_single_speed.ratedTotalHeatingCapacity.get
    elsif coil_heating_dx_single_speed.autosizedRatedTotalHeatingCapacity.is_initialized
      capacity_w = coil_heating_dx_single_speed.autosizedRatedTotalHeatingCapacity.get
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name} capacity is not available, cannot apply efficiency standard to paired DX heating coil.")
      return 0.0
    end
    return capacity_w
  end

  # If a coil was found, cast to the correct type
  if clg_coil.to_CoilCoolingDXSingleSpeed.is_initialized
    clg_coil = clg_coil.to_CoilCoolingDXSingleSpeed.get
    capacity_w = coil_cooling_dx_single_speed_find_capacity(clg_coil)
  elsif clg_coil.to_CoilCoolingDXTwoSpeed.is_initialized
    clg_coil = clg_coil.to_CoilCoolingDXTwoSpeed.get
    capacity_w = coil_cooling_dx_two_speed_find_capacity(clg_coil)
  elsif clg_coil.to_CoilCoolingDXMultiSpeed.is_initialized
    clg_coil = clg_coil.to_CoilCoolingDXMultiSpeed.get
    capacity_w = coil_cooling_dx_multi_speed_find_capacity(clg_coil)
  end

  # If it's a PTAC or PTHP System, we need to divide the capacity by the potential zone multiplier
  # because the COP is dependent on capacity, and the capacity should be the capacity of a single zone, not all the zones
  if ['PTAC', 'PTHP'].include?(coil_dx_subcategory(coil_heating_dx_single_speed))
    mult = 1
    comp = coil_heating_dx_single_speed.containingZoneHVACComponent
    if comp.is_initialized
      if comp.get.thermalZone.is_initialized
        mult = comp.get.thermalZone.get.multiplier
        if mult > 1
          total_cap = capacity_w
          capacity_w /= mult
          OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}, total capacity of #{OpenStudio.convert(total_cap, 'W', 'kBtu/hr').get.round(2)}kBTU/hr was divided by the zone multiplier of #{mult} to give #{capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get.round(2)}kBTU/hr.")
        end
      end
    end
  end

  return capacity_w
end
coil_heating_dx_single_speed_standard_minimum_cop(coil_heating_dx_single_speed, rename = false, necb_ref_hp = false) click to toggle source

Finds lookup object in standards and return efficiency

@param coil_heating_dx_single_speed [OpenStudio::Model::CoilHeatingDXSingleSpeed] coil heating dx single speed object @param rename [Boolean] if true, object will be renamed to include capacity and efficiency level @param necb_ref_hp [Boolean] for compatability with NECB ruleset only. @return [Double] full load efficiency (COP)

# File lib/openstudio-standards/standards/Standards.CoilHeatingDXSingleSpeed.rb, line 110
def coil_heating_dx_single_speed_standard_minimum_cop(coil_heating_dx_single_speed, rename = false, necb_ref_hp = false)
  # find ac properties
  search_criteria = coil_dx_find_search_criteria(coil_heating_dx_single_speed, necb_ref_hp)
  sub_category = search_criteria['subcategory']
  suppl_heating_type = search_criteria['heating_type']
  capacity_w = coil_heating_dx_single_speed_find_capacity(coil_heating_dx_single_speed, necb_ref_hp)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Get the minimum efficiency standards
  cop = nil

  # find object
  ac_props = model_find_object(standards_data['heat_pumps_heating'], search_criteria, capacity_btu_per_hr, Date.today)

  # Check to make sure properties were found
  if ac_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    return cop # value of nil
  end

  # If PTHP, use equations
  if sub_category == 'PTHP' && !ac_props['pthp_cop_coefficient_1'].nil? && !ac_props['pthp_cop_coefficient_2'].nil?
    pthp_cop_coeff_1 = ac_props['pthp_cop_coefficient_1']
    pthp_cop_coeff_2 = ac_props['pthp_cop_coefficient_2']
    # TABLE 6.8.1D
    # COP = pthp_cop_coeff_1 - (pthp_cop_coeff_2 * Cap / 1000)
    # Note c: Cap means the rated cooling capacity of the product in Btu/h.
    # If the unit's capacity is less than 7000 Btu/h, use 7000 Btu/h in the calculation.
    # If the unit's capacity is greater than 15,000 Btu/h, use 15,000 Btu/h in the calculation.
    capacity_btu_per_hr = 7000 if capacity_btu_per_hr < 7000
    capacity_btu_per_hr = 15_000 if capacity_btu_per_hr > 15_000
    min_coph = pthp_cop_coeff_1 - (pthp_cop_coeff_2 * capacity_btu_per_hr / 1000.0)
    cop = cop_heating_to_cop_heating_no_fan(min_coph, OpenStudio.convert(capacity_kbtu_per_hr, 'kBtu/hr', 'W').get)
    new_comp_name = "#{coil_heating_dx_single_speed.name} #{capacity_kbtu_per_hr.round} Clg kBtu/hr #{min_coph.round(1)}COPH"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{coil_heating_dx_single_speed.name}: #{sub_category} Cooling Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; COPH = #{min_coph.round(2)}")
  end

  # If specified as HSPF
  unless ac_props['minimum_heating_seasonal_performance_factor'].nil?
    min_hspf = ac_props['minimum_heating_seasonal_performance_factor']
    cop = hspf_to_cop_no_fan(min_hspf)
    new_comp_name = "#{coil_heating_dx_single_speed.name} #{capacity_kbtu_per_hr.round} Clg kBtu/hr #{min_hspf.round(1)}HSPF"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{template}: #{coil_heating_dx_single_speed.name}: #{suppl_heating_type} #{sub_category} Cooling Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; HSPF = #{min_hspf}")
  end

  # If specified as COPH
  unless ac_props['minimum_coefficient_of_performance_heating'].nil?
    min_coph = ac_props['minimum_coefficient_of_performance_heating']
    cop = cop_heating_to_cop_heating_no_fan(min_coph, OpenStudio.convert(capacity_kbtu_per_hr, 'kBtu/hr', 'W').get)
    new_comp_name = "#{coil_heating_dx_single_speed.name} #{capacity_kbtu_per_hr.round} Clg kBtu/hr #{min_coph.round(1)}COPH"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{template}: #{coil_heating_dx_single_speed.name}: #{suppl_heating_type} #{sub_category} Cooling Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; COPH = #{min_coph}")
  end

  # If specified as EER
  unless ac_props['minimum_energy_efficiency_ratio'].nil?
    min_eer = ac_props['minimum_energy_efficiency_ratio']
    cop = eer_to_cop_no_fan(min_eer)
    new_comp_name = "#{coil_heating_dx_single_speed.name} #{capacity_kbtu_per_hr.round} Clg kBtu/hr #{min_eer.round(1)}EER"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingDXSingleSpeed', "For #{template}: #{coil_heating_dx_single_speed.name}:  #{suppl_heating_type} #{sub_category} Cooling Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; EER = #{min_eer}")
  end

  # Rename
  if rename
    coil_heating_dx_single_speed.setName(new_comp_name)
  end

  return cop
end
coil_heating_gas_additional_search_criteria(coil_heating_gas, search_criteria) click to toggle source

Applies the standard efficiency ratings to CoilHeatingGas.

@param coil_heating_gas [OpenStudio::Model::CoilHeatingGas] coil heating gas object @param search_criteria [Hash] search criteria for looking up furnace data @return [Hash] updated search criteria

# File lib/openstudio-standards/standards/Standards.CoilHeatingGas.rb, line 9
def coil_heating_gas_additional_search_criteria(coil_heating_gas, search_criteria)
  return search_criteria
end
coil_heating_gas_apply_efficiency_and_curves(coil_heating_gas) click to toggle source

Applies the standard efficiency ratings to CoilHeatingGas.

@param coil_heating_gas [OpenStudio::Model::CoilHeatingGas] coil heating gas object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.CoilHeatingGas.rb, line 17
def coil_heating_gas_apply_efficiency_and_curves(coil_heating_gas)
  successfully_set_all_properties = false
  # Initialize search criteria
  search_criteria = {}
  search_criteria['template'] = template
  search_criteria['equipment_type'] = 'Warm Air Furnace'
  search_criteria['fuel_type'] = 'NaturalGas'
  search_criteria = coil_heating_gas_additional_search_criteria(coil_heating_gas, search_criteria)

  # Get the capacity, but return false if not available
  capacity_w = coil_heating_gas_find_capacity(coil_heating_gas)

  # Return false if the coil does not have a heating capacity associated with it. Cannot apply the standard if without
  # it.
  return successfully_set_all_properties if capacity_w == false

  # Convert capacity to Btu/hr
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  return false unless capacity_btu_per_hr > 0

  # Get the boiler properties, if it exists for this template
  return false unless standards_data.include?('furnaces')

  furnace_props = model_find_object(standards_data['furnaces'], search_criteria, capacity_btu_per_hr)
  unless furnace_props
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingGas', "For #{coil_heating_gas.name}, cannot find furnace properties with search criteria #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Get the minimum efficiency standards
  thermal_eff = nil

  # If specified as thermal efficiency, this takes precedent
  if !furnace_props['minimum_thermal_efficiency'].nil?
    thermal_eff = furnace_props['minimum_thermal_efficiency']
    new_comp_name = "#{coil_heating_gas.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{thermal_eff} Thermal Eff"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingGas', "For #{template}: #{coil_heating_gas.name}: = #{capacity_kbtu_per_hr.round}kBtu/hr; Thermal Efficiency = #{thermal_eff}")

  else # If not thermal efficiency, check other parameters

    # If specified as AFUE
    unless furnace_props['minimum_annual_fuel_utilization_efficiency'].nil?
      min_afue = furnace_props['minimum_annual_fuel_utilization_efficiency']
      thermal_eff = afue_to_thermal_eff(min_afue)
      new_comp_name = "#{coil_heating_gas.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_afue} AFUE"
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingGas', "For #{template}: #{coil_heating_gas.name}: = #{capacity_kbtu_per_hr.round}kBtu/hr; AFUE = #{min_afue}")
    end

    # If specified as combustion efficiency
    unless furnace_props['minimum_combustion_efficiency'].nil?
      min_comb_eff = furnace_props['minimum_combustion_efficiency']
      thermal_eff = combustion_eff_to_thermal_eff(min_comb_eff)
      new_comp_name = "#{coil_heating_gas.name} #{capacity_kbtu_per_hr.round}kBtu/hr #{min_comb_eff} Combustion Eff"
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingGas', "For #{template}: #{coil_heating_gas.name}: = #{capacity_kbtu_per_hr.round}kBtu/hr; Combustion Efficiency = #{min_comb_eff}")
    end

  end

  # Set the efficiency values
  unless thermal_eff.nil?

    # Set the name
    coil_heating_gas.setName(new_comp_name)
    coil_heating_gas.setGasBurnerEfficiency(thermal_eff)
    successfully_set_all_properties = true
  end

  return successfully_set_all_properties
end
coil_heating_gas_apply_prototype_efficiency(coil_heating_gas) click to toggle source

Updates the efficiency of some gas heating coils per the prototype assumptions. Defaults to making no changes.

@param coil_heating_gas [OpenStudio::Model::CoilHeatingGas] a gas heating coil @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilHeatingGas.rb, line 70
def coil_heating_gas_apply_prototype_efficiency(coil_heating_gas)
  # do nothing
  return true
end
coil_heating_gas_find_capacity(coil_heating_gas) click to toggle source

Retrieves the capacity of an OpenStudio::Model::CoilHeatingGas in watts

@param coil_heating_gas [OpenStudio::Model::CoilHeatingGas] the gas heating coil @return [Double, false] a double representing the capacity of the CoilHeatingGas object in watts. If unsuccessful in

determining the capacity, this function returns false.
# File lib/openstudio-standards/standards/Standards.CoilHeatingGas.rb, line 95
def coil_heating_gas_find_capacity(coil_heating_gas)
  capacity_w = nil
  if coil_heating_gas.nominalCapacity.is_initialized
    capacity_w = coil_heating_gas.nominalCapacity.get
  elsif coil_heating_gas.autosizedNominalCapacity.is_initialized
    capacity_w = coil_heating_gas.autosizedNominalCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingGas', "For #{coil_heating_gas.name} capacity is not available, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  return capacity_w
end
coil_heating_gas_multi_stage_apply_efficiency_and_curves(coil_heating_gas_multi_stage) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param coil_heating_gas_multi_stage [OpenStudio::Model::CoilHeatingGasMultiStage] coil heating gas multi stage object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.CoilHeatingGasMultiStage.rb, line 23
def coil_heating_gas_multi_stage_apply_efficiency_and_curves(coil_heating_gas_multi_stage)
  successfully_set_all_properties = true

  # Get the coil capacity
  capacity_w = nil
  htg_stages = stages
  if htg_stages.last.nominalCapacity.is_initialized
    capacity_w = htg_stages.last.nominalCapacity.get
  elsif coil_heating_gas_multi_stage.autosizedStage4NominalCapacity.is_initialized
    capacity_w = coil_heating_gas_multi_stage.autosizedStage4NominalCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingGasMultiStage', "For #{coil_heating_gas_multi_stage.name} capacity is not available, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # plf vs plr curve for furnace
  furnace_plffplr_curve = model_add_curve(model, furnace_plffplr_curve_name, standards)
  if furnace_plffplr_curve
    coil_heating_gas_multi_stage.setPartLoadFractionCorrelationCurve(furnace_plffplr_curve)
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingGasMultiStage', "For #{coil_heating_gas_multi_stage.name}, cannot find plffplr curve, will not be set.")
    successfully_set_all_properties = false
  end
end
coil_heating_gas_multi_stage_find_capacity(coil_heating_gas_multi_stage) click to toggle source

Finds capacity in W

@param coil_heating_gas_multi_stage [OpenStudio::Model::CoilHeatingGasMultiStage] coil heating gas multi stage object @return [Double] capacity in W to be used for find object

# File lib/openstudio-standards/standards/Standards.CoilHeatingGasMultiStage.rb, line 53
def coil_heating_gas_multi_stage_find_capacity(coil_heating_gas_multi_stage)
  capacity_w = nil
  htg_stages = coil_heating_gas_multi_stage.stages
  if htg_stages.last.nominalCapacity.is_initialized
    capacity_w = htg_stages.last.nominalCapacity.get
  elsif (htg_stages.size == 1) && coil_heating_gas_multi_stage.autosizedStage1NominalCapacity.is_initialized
    capacity_w = coil_heating_gas_multi_stage.autosizedStage1NominalCapacity.get
  elsif (htg_stages.size == 2) && coil_heating_gas_multi_stage.autosizedStage2NominalCapacity.is_initialized
    capacity_w = coil_heating_gas_multi_stage.autosizedStage2NominalCapacity.get
  elsif (htg_stages.size == 3) && coil_heating_gas_multi_stage.autosizedStage3NominalCapacity.is_initialized
    capacity_w = coil_heating_gas_multi_stage.autosizedStage3NominalCapacity.get
  elsif (htg_stages.size == 4) && coil_heating_gas_multi_stage.autosizedStage4NominalCapacity.is_initialized
    capacity_w = coil_heating_gas_multi_stage.autosizedStage4NominalCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilCoolingDXMultiSpeed', "For #{coil_heating_gas_multi_stage.name} capacity is not available, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end
end
coil_heating_gas_multi_stage_find_search_criteria(coil_heating_gas_multi_stage) click to toggle source

find search criteria

@param coil_heating_gas_multi_stage [OpenStudio::Model::CoilHeatingGasMultiStage] coil heating gas multi stage object @return [Hash] used for model_find_object(model)

# File lib/openstudio-standards/standards/Standards.CoilHeatingGasMultiStage.rb, line 8
def coil_heating_gas_multi_stage_find_search_criteria(coil_heating_gas_multi_stage)
  # Define the criteria to find the coil heating gas multi-stage properties
  # in the hvac standards data set.
  search_criteria = {}
  search_criteria['template'] = template
  search_criteria['fuel_type'] = 'Gas'
  search_criteria['fluid_type'] = 'Air'

  return search_criteria
end
coil_heating_water_to_air_heat_pump_apply_efficiency_and_curves(coil_heating_water_to_air_heat_pump, sql_db_vars_map) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param coil_heating_water_to_air_heat_pump [OpenStudio::Model::CoilHeatingWaterToAirHeatPumpEquationFit] coil heating object @param sql_db_vars_map [Hash] hash map @return [Hash] hash of coil objects

# File lib/openstudio-standards/standards/Standards.CoilHeatingWaterToAirHeatPumpEquationFit.rb, line 133
def coil_heating_water_to_air_heat_pump_apply_efficiency_and_curves(coil_heating_water_to_air_heat_pump, sql_db_vars_map)
  successfully_set_all_properties = true

  # Get the search criteria
  search_criteria = {}
  search_criteria['template'] = template
  capacity_w = coil_heating_water_to_air_heat_pump_find_capacity(coil_heating_water_to_air_heat_pump)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get

  # Look up the efficiency characteristics
  coil_props = model_find_object(standards_data['water_source_heat_pumps_heating'], search_criteria, capacity_btu_per_hr, Date.today)

  # Check to make sure properties were found
  if coil_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingWaterToAirHeatPumpEquationFit', "For #{coil_heating_water_to_air_heat_pump.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return sql_db_vars_map
  end

  # @todo Add methods to set coefficients, and add coefficients to data spreadsheet
  # using OS defaults for now
  # heat_cap_coeff1 = coil_props['heat_cap_coeff1']
  # if heat_cap_coeff1
  #   coil_heating_water_to_air_heat_pump.setHeatingCapacityCoefficient1(heat_cap_coeff1)
  # else
  #   OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingWaterToAirHeatPumpEquationFit', "For #{coil_heating_water_to_air_heat_pump.name}, cannot find heat_cap_coeff1, will not be set.")
  #   successfully_set_all_properties = false
  # end

  # Preserve the original name
  orig_name = coil_heating_water_to_air_heat_pump.name.to_s

  # Find the minimum COP and rename with efficiency rating
  cop = coil_heating_water_to_air_heat_pump_standard_minimum_cop(coil_heating_water_to_air_heat_pump, true)

  # Map the original name to the new name
  sql_db_vars_map[coil_heating_water_to_air_heat_pump.name.to_s] = orig_name

  # Set the efficiency values
  unless cop.nil?
    coil_heating_water_to_air_heat_pump.setRatedHeatingCoefficientofPerformance(cop)
  end

  return sql_db_vars_map
end
coil_heating_water_to_air_heat_pump_find_capacity(coil_heating_water_to_air_heat_pump) click to toggle source

Finds capacity in W. This is the cooling capacity of the paired cooling coil.

@param coil_heating_water_to_air_heat_pump [OpenStudio::Model::CoilHeatingWaterToAirHeatPumpEquationFit] coil heating object @return [Double] capacity in W to be used for find object

# File lib/openstudio-standards/standards/Standards.CoilHeatingWaterToAirHeatPumpEquationFit.rb, line 9
def coil_heating_water_to_air_heat_pump_find_capacity(coil_heating_water_to_air_heat_pump)
  capacity_w = nil

  # Get the paired cooling coil
  clg_coil = nil

  # Unitary and zone equipment
  if coil_heating_water_to_air_heat_pump.airLoopHVAC.empty?
    if coil_heating_water_to_air_heat_pump.containingHVACComponent.is_initialized
      containing_comp = coil_heating_water_to_air_heat_pump.containingHVACComponent.get
      if containing_comp.to_AirLoopHVACUnitaryHeatPumpAirToAir.is_initialized
        clg_coil = containing_comp.to_AirLoopHVACUnitaryHeatPumpAirToAir.get.coolingCoil
      elsif containing_comp.to_AirLoopHVACUnitarySystem.is_initialized
        unitary = containing_comp.to_AirLoopHVACUnitarySystem.get
        if unitary.coolingCoil.is_initialized
          clg_coil = unitary.coolingCoil.get
        end
      end
    elsif coil_heating_water_to_air_heat_pump.containingZoneHVACComponent.is_initialized
      containing_comp = coil_heating_water_to_air_heat_pump.containingZoneHVACComponent.get
      # PTHP
      if containing_comp.to_ZoneHVACPackagedTerminalHeatPump.is_initialized
        clg_coil = containing_comp.to_ZoneHVACPackagedTerminalHeatPump.get.coolingCoil
      # WSHP
      elsif containing_comp.to_ZoneHVACWaterToAirHeatPump.is_initialized
        clg_coil = containing_comp.to_ZoneHVACWaterToAirHeatPump.get.coolingCoil
      end
    end
  end

  # On AirLoop directly
  if coil_heating_water_to_air_heat_pump.airLoopHVAC.is_initialized
    air_loop = coil_heating_water_to_air_heat_pump.airLoopHVAC.get
    # Check for the presence of any other type of cooling coil
    clg_types = ['OS:Coil:Cooling:DX:SingleSpeed',
                 'OS:Coil:Cooling:DX:TwoSpeed',
                 'OS:Coil:Cooling:DX:MultiSpeed']
    clg_types.each do |ct|
      coils = air_loop.supplyComponents(ct.to_IddObjectType)
      next if coils.empty?

      clg_coil = coils[0]
      break # Stop on first cooling coil found
    end
  end

  # If no paired cooling coil was found,
  # throw an error and fall back to the heating capacity of the heating coil
  if clg_coil.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingWaterToAirHeatPumpEquationFit', "For #{coil_heating_water_to_air_heat_pump.name}, the paired cooling coil could not be found to determine capacity. Efficiency will incorrectly be based on coil's heating capacity.")
    if coil_heating_water_to_air_heat_pump.ratedTotalHeatingCapacity.is_initialized
      capacity_w = coil_heating_water_to_air_heat_pump.ratedTotalHeatingCapacity.get
    elsif coil_heating_water_to_air_heat_pump.autosizedRatedTotalHeatingCapacity.is_initialized
      capacity_w = coil_heating_water_to_air_heat_pump.autosizedRatedTotalHeatingCapacity.get
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingWaterToAirHeatPumpEquationFit', "For #{coil_heating_water_to_air_heat_pump.name} capacity is not available, cannot apply efficiency standard to paired heating coil.")
      return 0.0
    end
    return capacity_w
  end

  # If a coil was found, cast to the correct type
  if clg_coil.to_CoilCoolingDXSingleSpeed.is_initialized
    clg_coil = clg_coil.to_CoilCoolingDXSingleSpeed.get
    capacity_w = coil_cooling_dx_single_speed_find_capacity(clg_coil)
  elsif clg_coil.to_CoilCoolingDXTwoSpeed.is_initialized
    clg_coil = clg_coil.to_CoilCoolingDXTwoSpeed.get
    capacity_w = coil_cooling_dx_two_speed_find_capacity(clg_coil)
  elsif clg_coil.to_CoilCoolingDXMultiSpeed.is_initialized
    clg_coil = clg_coil.to_CoilCoolingDXMultiSpeed.get
    capacity_w = coil_cooling_dx_multi_speed_find_capacity(clg_coil)
  elsif clg_coil.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized
    clg_coil = clg_coil.to_CoilCoolingWaterToAirHeatPumpEquationFit.get
    capacity_w = coil_cooling_water_to_air_heat_pump_find_capacity(clg_coil)
  end

  return capacity_w
end
coil_heating_water_to_air_heat_pump_standard_minimum_cop(coil_heating_water_to_air_heat_pump, rename = false) click to toggle source

Finds lookup object in standards and return efficiency

@param coil_heating_water_to_air_heat_pump [OpenStudio::Model::CoilHeatingWaterToAirHeatPumpEquationFit] coil heating object @param rename [Boolean] if true, object will be renamed to include capacity and efficiency level @return [Double] full load efficiency (COP)

# File lib/openstudio-standards/standards/Standards.CoilHeatingWaterToAirHeatPumpEquationFit.rb, line 93
def coil_heating_water_to_air_heat_pump_standard_minimum_cop(coil_heating_water_to_air_heat_pump, rename = false)
  search_criteria = {}
  search_criteria['template'] = template
  capacity_w = coil_heating_water_to_air_heat_pump_find_capacity(coil_heating_water_to_air_heat_pump)
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
  capacity_kbtu_per_hr = OpenStudio.convert(capacity_w, 'W', 'kBtu/hr').get

  # Look up the efficiency characteristics
  coil_props = model_find_object(standards_data['water_source_heat_pumps_heating'], search_criteria, capacity_btu_per_hr, Date.today)

  # Check to make sure properties were found
  if coil_props.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.CoilHeatingWaterToAirHeatPumpEquationFit', "For #{coil_heating_water_to_air_heat_pump.name}, cannot find efficiency info using #{search_criteria}, cannot apply efficiency standard.")
    successfully_set_all_properties = false
    return successfully_set_all_properties
  end

  # Get the minimum efficiency standards
  cop = nil

  # If specified as EER
  unless coil_props['minimum_coefficient_of_performance_heating'].nil?
    cop = coil_props['minimum_coefficient_of_performance_heating']
    new_comp_name = "#{coil_heating_water_to_air_heat_pump.name} #{capacity_kbtu_per_hr.round} Clg kBtu/hr #{cop.round(1)}COPH"
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.CoilHeatingWaterToAirHeatPumpEquationFit', "For #{template}: #{coil_heating_water_to_air_heat_pump.name}: Cooling Capacity = #{capacity_kbtu_per_hr.round}kBtu/hr; COPH = #{cop}")
  end

  # Rename
  if rename
    coil_heating_water_to_air_heat_pump.setName(new_comp_name)
  end

  return cop
end
combustion_eff_to_thermal_eff(combustion_eff) click to toggle source

A helper method to convert from combustion efficiency to thermal efficiency @ref [References::USDOEPrototypeBuildings] Boiler Addendum 90.1-04an

@param combustion_eff [Double] Combustion efficiency (%) @return [Double] Thermal efficiency (%)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 425
def combustion_eff_to_thermal_eff(combustion_eff)
  return combustion_eff - 0.007
end
controller_water_coil_set_convergence_limits(controller_water_coil) click to toggle source

Sets the convergence tolerance to 0.0001 deltaC for all hot water coils.

@param controller_water_coil [OpenStudio::Model::ControllerWaterCoil] controller water coil object @return [Boolean] returns true if successful, false if not @todo Figure out what the reason for this is, because it seems like a workaround for an E+ bug that was probably addressed long ago.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ControllerWaterCoil.rb, line 9
def controller_water_coil_set_convergence_limits(controller_water_coil)
  controller_action = controller_water_coil.action
  if controller_action.is_initialized
    if controller_action.get == 'Normal'
      controller_water_coil.setControllerConvergenceTolerance(0.0001)
    end
  end

  return true
end
convert_curve_biquadratic(coeffs, ip_to_si = true) click to toggle source

Convert biquadratic curves that are a function of temperature from IP (F) to SI © or vice-versa. The curve is of the form z = C1 + C2*x + C3*x^2 + C4*y + C5*y^2 + C6*x*y where C1, C2, … are the coefficients, x is the first independent variable (in F or C) y is the second independent variable (in F or C) and z is the resulting value

@author Scott Horowitz, NREL @param coeffs [Array<Double>] an array of 6 coefficients, in order @return [Array<Double>] the revised coefficients in the new unit system

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 449
def convert_curve_biquadratic(coeffs, ip_to_si = true)
  if ip_to_si
    # Convert IP curves to SI curves
    si_coeffs = []
    si_coeffs << coeffs[0] + 32.0 * (coeffs[1] + coeffs[3]) + 1024.0 * (coeffs[2] + coeffs[4] + coeffs[5])
    si_coeffs << 9.0 / 5.0 * coeffs[1] + 576.0 / 5.0 * coeffs[2] + 288.0 / 5.0 * coeffs[5]
    si_coeffs << 81.0 / 25.0 * coeffs[2]
    si_coeffs << 9.0 / 5.0 * coeffs[3] + 576.0 / 5.0 * coeffs[4] + 288.0 / 5.0 * coeffs[5]
    si_coeffs << 81.0 / 25.0 * coeffs[4]
    si_coeffs << 81.0 / 25.0 * coeffs[5]
    return si_coeffs
  else
    # Convert SI curves to IP curves
    ip_coeffs = []
    ip_coeffs << coeffs[0] - 160.0 / 9.0 * (coeffs[1] + coeffs[3]) + 25_600.0 / 81.0 * (coeffs[2] + coeffs[4] + coeffs[5])
    ip_coeffs << 5.0 / 9.0 * (coeffs[1] - 320.0 / 9.0 * coeffs[2] - 160.0 / 9.0 * coeffs[5])
    ip_coeffs << 25.0 / 81.0 * coeffs[2]
    ip_coeffs << 5.0 / 9.0 * (coeffs[3] - 320.0 / 9.0 * coeffs[4] - 160.0 / 9.0 * coeffs[5])
    ip_coeffs << 25.0 / 81.0 * coeffs[4]
    ip_coeffs << 25.0 / 81.0 * coeffs[5]
    return ip_coeffs
  end
end
cooling_tower_single_speed_apply_efficiency_and_curves(cooling_tower_single_speed) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param cooling_tower_single_speed [OpenStudio::Model::CoolingTowerSingleSpeed] single speed cooling tower @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.CoolingTowerSingleSpeed.rb, line 10
def cooling_tower_single_speed_apply_efficiency_and_curves(cooling_tower_single_speed)
  cooling_tower_apply_minimum_power_per_flow(cooling_tower_single_speed)
  return true
end
cooling_tower_two_speed_apply_efficiency_and_curves(cooling_tower_two_speed) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param cooling_tower_two_speed [OpenStudio::Model::CoolingTowerTwoSpeed] two speed cooling tower @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.CoolingTowerTwoSpeed.rb, line 10
def cooling_tower_two_speed_apply_efficiency_and_curves(cooling_tower_two_speed)
  cooling_tower_apply_minimum_power_per_flow(cooling_tower_two_speed)

  return true
end
cooling_tower_variable_speed_apply_efficiency_and_curves(cooling_tower_variable_speed) click to toggle source

Applies the standard efficiency ratings and typical performance curves to this object.

@param cooling_tower_variable_speed [OpenStudio::Model::CoolingTowerVariableSpeed] variable speed cooling tower @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.CoolingTowerVariableSpeed.rb, line 10
def cooling_tower_variable_speed_apply_efficiency_and_curves(cooling_tower_variable_speed)
  cooling_tower_apply_minimum_power_per_flow(cooling_tower_variable_speed)
  return true
end
cop_heating_to_cop_heating_no_fan(coph47, capacity_w) click to toggle source

Convert from COP_H to COP (no fan) for heat pump heating coils @ref [References::ASHRAE9012013] Appendix G

@param coph47 [Double] coefficient of performance at 47F Tdb, 42F Twb @param capacity_w [Double] the heating capacity at AHRI rating conditions, in W @return [Double] Coefficient of Performance (COP)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 293
def cop_heating_to_cop_heating_no_fan(coph47, capacity_w)
  # Convert the capacity to Btu/hr
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get

  cop = 1.48E-7 * coph47 * capacity_btu_per_hr + 1.062 * coph47

  return cop
end
cop_no_fan_to_eer(cop, capacity_w = nil) click to toggle source

Convert from COP to EER @ref [References::USDOEPrototypeBuildings]

@param cop [Double] COP @return [Double] Energy Efficiency Ratio (EER)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 353
def cop_no_fan_to_eer(cop, capacity_w = nil)
  if capacity_w.nil?
    # From Thornton et al. 2011
    # r is the ratio of supply fan power to total equipment power at the rating condition,
    # assumed to be 0.12 for the reference buildngs per Thornton et al. 2011.
    r = 0.12
    eer = OpenStudio.convert(1.0, 'W', 'Btu/h').get * (cop * (1 - r) - r)
  else
    # The 90.1-2013 method
    # Convert the capacity to Btu/hr
    capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
    eer = cop / (7.84E-8 * capacity_btu_per_hr + 0.338)
  end

  return eer
end
cop_no_fan_to_seer(cop) click to toggle source

Convert from COP to SEER @ref [References::USDOEPrototypeBuildings]

@param cop [Double] COP @return [Double] Seasonal Energy Efficiency Ratio

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 255
def cop_no_fan_to_seer(cop)
  delta = 0.3796**2 - 4.0 * 0.0076 * cop
  seer = (-delta**0.5 + 0.3796) / (2.0 * 0.0076)

  return seer
end
cop_to_eer(cop) click to toggle source

Convert from COP to EER

@param cop [Double] Coefficient of Performance (COP) @return [Double] Energy Efficiency Ratio (EER)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 382
def cop_to_eer(cop)
  return cop * OpenStudio.convert(1.0, 'W', 'Btu/h').get
end
cop_to_kw_per_ton(cop) click to toggle source

Convert from COP to kW/ton

@param cop [Double] Coefficient of Performance (COP) @return [Double] kW of input power per ton of cooling

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 390
def cop_to_kw_per_ton(cop)
  return 3.517 / cop
end
cop_to_seer(cop) click to toggle source

Convert from COP to SEER (with fan) for cooling coils per the method specified in Thornton et al. 2011

@param cop [Double] Coefficient of Performance (COP) @return [Double] seasonal energy efficiency ratio (SEER)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 279
def cop_to_seer(cop)
  eer = cop_to_eer(cop)
  delta = 1.1088**2 - 4.0 * 0.0182 * eer
  seer = (1.1088 - delta**0.5) / (2.0 * 0.0182)

  return seer
end
create_air_conditioner_variable_refrigerant_flow(model, name: 'VRF System', schedule: nil, type: nil, cooling_cop: 4.287, heating_cop: 4.147, heat_recovery: true, defrost_strategy: 'Resistive', condenser_type: 'AirCooled', condenser_loop: nil, master_zone: nil, priority_control_type: 'LoadPriority') click to toggle source

Prototype AirConditionerVariableRefrigerantFlow object Enters in default curves for coil by type of coil

@param model [OpenStudio::Model::Model] OpenStudio model object @param name [String] the name of the system, or nil in which case it will be defaulted @param schedule [String] name of the availability schedule, or [<OpenStudio::Model::Schedule>] Schedule object, or nil in which case default to always on @param type [String] the type of unit to reference for the correct curve set @param cooling_cop [Double] rated cooling coefficient of performance @param heating_cop [Double] rated heating coefficient of performance @param heat_recovery [Boolean] does the unit have heat recovery @param defrost_strategy [String] type of defrost strategy. options are ReverseCycle or Resistive @param condenser_type [String] type of condenser

options are AirCooled (default), WaterCooled, and EvaporativelyCooled.
if WaterCooled, the user most include a condenser_loop

@param master_zone [<OpenStudio::Model::ThermalZone>] master control zone to switch between heating and cooling @param priority_control_type [String] type of master thermostat priority control type

options are LoadPriority, ZonePriority, ThermostatOffsetPriority, MasterThermostatPriority

@return [OpenStudio::Model::AirConditionerVariableRefrigerantFlow] the vrf unit

# File lib/openstudio-standards/prototypes/common/objects/Prototype.AirConditionerVariableRefrigerantFlow.rb, line 22
def create_air_conditioner_variable_refrigerant_flow(model,
                                                     name: 'VRF System',
                                                     schedule: nil,
                                                     type: nil,
                                                     cooling_cop: 4.287,
                                                     heating_cop: 4.147,
                                                     heat_recovery: true,
                                                     defrost_strategy: 'Resistive',
                                                     condenser_type: 'AirCooled',
                                                     condenser_loop: nil,
                                                     master_zone: nil,
                                                     priority_control_type: 'LoadPriority')

  vrf_outdoor_unit = OpenStudio::Model::AirConditionerVariableRefrigerantFlow.new(model)

  # set name
  if name.nil?
    vrf_outdoor_unit.setName('VRF System')
  else
    vrf_outdoor_unit.setName(name)
  end

  # set availability schedule
  if schedule.nil?
    # default always on
    availability_schedule = model.alwaysOnDiscreteSchedule
  elsif schedule.class == String
    availability_schedule = model_add_schedule(model, schedule)

    if availability_schedule.nil? && schedule == 'alwaysOffDiscreteSchedule'
      availability_schedule = model.alwaysOffDiscreteSchedule
    elsif availability_schedule.nil?
      availability_schedule = model.alwaysOnDiscreteSchedule
    end
  elsif !schedule.to_Schedule.empty?
    availability_schedule = schedule
  else
    availability_schedule = model.alwaysOnDiscreteSchedule
  end
  vrf_outdoor_unit.setAvailabilitySchedule(availability_schedule)

  # set cops
  vrf_outdoor_unit.setRatedCoolingCOP(cooling_cop)
  vrf_outdoor_unit.setRatedHeatingCOP(heating_cop)

  # heat recovery
  if heat_recovery
    vrf_outdoor_unit.setHeatPumpWasteHeatRecovery(true)
  else
    vrf_outdoor_unit.setHeatPumpWasteHeatRecovery(false)
  end

  # defrost strategy
  vrf_outdoor_unit.setDefrostStrategy(defrost_strategy)

  # defaults
  vrf_outdoor_unit.setMinimumOutdoorTemperatureinCoolingMode(-15.0)
  vrf_outdoor_unit.setMaximumOutdoorTemperatureinCoolingMode(50.0)
  vrf_outdoor_unit.setMinimumOutdoorTemperatureinHeatingMode(-25.0)
  vrf_outdoor_unit.setMaximumOutdoorTemperatureinHeatingMode(16.1)
  vrf_outdoor_unit.setMinimumOutdoorTemperatureinHeatRecoveryMode(-10.0)
  vrf_outdoor_unit.setMaximumOutdoorTemperatureinHeatRecoveryMode(27.2)
  vrf_outdoor_unit.setEquivalentPipingLengthusedforPipingCorrectionFactorinCoolingMode(30.48)
  vrf_outdoor_unit.setEquivalentPipingLengthusedforPipingCorrectionFactorinHeatingMode(30.48)
  vrf_outdoor_unit.setVerticalHeightusedforPipingCorrectionFactor(10.668)

  # condenser type
  if condenser_type == 'WaterCooled'
    vrf_outdoor_unit.setString(56, condenser_type)
    # require condenser_loop
    unless condenser_loop
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'Must specify condenser_loop for vrf_outdoor_unit if WaterCooled')
    end
    condenser_loop.addDemandBranchForComponent(vrf_outdoor_unit)
  elsif condenser_type == 'EvaporativelyCooled'
    vrf_outdoor_unit.setString(56, condenser_type)
  end

  # set master zone
  unless master_zone.to_ThermalZone.empty?
    vrf_outdoor_unit.setZoneforMasterThermostatLocation(master_zone)
    vrf_outdoor_unit.setMasterThermostatPriorityControlType(priority_control_type)
  end

  vrf_cool_cap_f_of_low_temp = nil
  vrf_cool_cap_ratio_boundary = nil
  vrf_cool_cap_f_of_high_temp = nil
  vrf_cool_eir_f_of_low_temp = nil
  vrf_cool_eir_ratio_boundary = nil
  vrf_cool_eir_f_of_high_temp = nil
  vrf_cooling_eir_low_plr = nil
  vrf_cooling_eir_high_plr = nil
  vrf_cooling_comb_ratio = nil
  vrf_cooling_cplffplr = nil
  vrf_heat_cap_f_of_low_temp = nil
  vrf_heat_cap_ratio_boundary = nil
  vrf_heat_cap_f_of_high_temp = nil
  vrf_heat_eir_f_of_low_temp = nil
  vrf_heat_eir_boundary = nil
  vrf_heat_eir_f_of_high_temp = nil
  vrf_heating_eir_low_plr = nil
  vrf_heating_eir_hi_plr = nil
  vrf_heating_comb_ratio = nil
  vrf_heating_cplffplr = nil
  vrf_defrost_eir_f_of_temp = nil

  # curve sets
  if type == 'OS default'

    # use OS default curves

  else # default curve set

    # based on DAIKINREYQ 120 on BCL

    # Cooling Capacity Ratio Modifier Function of Low Temperature Curve
    vrf_cool_cap_f_of_low_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    vrf_cool_cap_f_of_low_temp.setName('vrf_cool_cap_f_of_low_temp')
    vrf_cool_cap_f_of_low_temp.setCoefficient1Constant(-1.69653019339465)
    vrf_cool_cap_f_of_low_temp.setCoefficient2x(0.207248180531939)
    vrf_cool_cap_f_of_low_temp.setCoefficient3xPOW2(-0.00343146229659024)
    vrf_cool_cap_f_of_low_temp.setCoefficient4y(0.016381597419714)
    vrf_cool_cap_f_of_low_temp.setCoefficient5yPOW2(-6.7387172629965e-05)
    vrf_cool_cap_f_of_low_temp.setCoefficient6xTIMESY(-0.000849848402870241)
    vrf_cool_cap_f_of_low_temp.setMinimumValueofx(13.9)
    vrf_cool_cap_f_of_low_temp.setMaximumValueofx(23.9)
    vrf_cool_cap_f_of_low_temp.setMinimumValueofy(-5.0)
    vrf_cool_cap_f_of_low_temp.setMaximumValueofy(43.3)
    vrf_cool_cap_f_of_low_temp.setMinimumCurveOutput(0.59)
    vrf_cool_cap_f_of_low_temp.setMaximumCurveOutput(1.33)

    # Cooling Capacity Ratio Boundary Curve
    vrf_cool_cap_ratio_boundary = OpenStudio::Model::CurveCubic.new(model)
    vrf_cool_cap_ratio_boundary.setName('vrf_cool_cap_ratio_boundary')
    vrf_cool_cap_ratio_boundary.setCoefficient1Constant(25.73)
    vrf_cool_cap_ratio_boundary.setCoefficient2x(-0.03150043)
    vrf_cool_cap_ratio_boundary.setCoefficient3xPOW2(-0.01416595)
    vrf_cool_cap_ratio_boundary.setCoefficient4xPOW3(0.0)
    vrf_cool_cap_ratio_boundary.setMinimumValueofx(11.0)
    vrf_cool_cap_ratio_boundary.setMaximumValueofx(30.0)

    # Cooling Capacity Ratio Modifier Function of High Temperature Curve
    vrf_cool_cap_f_of_high_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    vrf_cool_cap_f_of_high_temp.setName('vrf_cool_cap_f_of_high_temp')
    vrf_cool_cap_f_of_high_temp.setCoefficient1Constant(0.6867358)
    vrf_cool_cap_f_of_high_temp.setCoefficient2x(0.0207631)
    vrf_cool_cap_f_of_high_temp.setCoefficient3xPOW2(0.0005447)
    vrf_cool_cap_f_of_high_temp.setCoefficient4y(-0.0016218)
    vrf_cool_cap_f_of_high_temp.setCoefficient5yPOW2(-4.259e-07)
    vrf_cool_cap_f_of_high_temp.setCoefficient6xTIMESY(-0.0003392)
    vrf_cool_cap_f_of_high_temp.setMinimumValueofx(15.0)
    vrf_cool_cap_f_of_high_temp.setMaximumValueofx(24.0)
    vrf_cool_cap_f_of_high_temp.setMinimumValueofy(16.0)
    vrf_cool_cap_f_of_high_temp.setMaximumValueofy(43.0)

    # Cooling Energy Input Ratio Modifier Function of Low Temperature Curve
    vrf_cool_eir_f_of_low_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    vrf_cool_eir_f_of_low_temp.setName('vrf_cool_eir_f_of_low_temp')
    vrf_cool_eir_f_of_low_temp.setCoefficient1Constant(-1.61908214818635)
    vrf_cool_eir_f_of_low_temp.setCoefficient2x(0.185964818731756)
    vrf_cool_eir_f_of_low_temp.setCoefficient3xPOW2(-0.00389610393381592)
    vrf_cool_eir_f_of_low_temp.setCoefficient4y(-0.00901995326324613)
    vrf_cool_eir_f_of_low_temp.setCoefficient5yPOW2(0.00030340007815629)
    vrf_cool_eir_f_of_low_temp.setCoefficient6xTIMESY(0.000476048529099348)
    vrf_cool_eir_f_of_low_temp.setMinimumValueofx(13.9)
    vrf_cool_eir_f_of_low_temp.setMaximumValueofx(23.9)
    vrf_cool_eir_f_of_low_temp.setMinimumValueofy(-5.0)
    vrf_cool_eir_f_of_low_temp.setMaximumValueofy(43.3)
    vrf_cool_eir_f_of_low_temp.setMinimumCurveOutput(0.27)
    vrf_cool_eir_f_of_low_temp.setMaximumCurveOutput(1.15)

    # Cooling Energy Input Ratio Boundary Curve
    vrf_cool_eir_ratio_boundary = OpenStudio::Model::CurveCubic.new(model)
    vrf_cool_eir_ratio_boundary.setName('vrf_cool_eir_ratio_boundary')
    vrf_cool_eir_ratio_boundary.setCoefficient1Constant(25.73473775)
    vrf_cool_eir_ratio_boundary.setCoefficient2x(-0.03150043)
    vrf_cool_eir_ratio_boundary.setCoefficient3xPOW2(-0.01416595)
    vrf_cool_eir_ratio_boundary.setCoefficient4xPOW3(0.0)
    vrf_cool_eir_ratio_boundary.setMinimumValueofx(15.0)
    vrf_cool_eir_ratio_boundary.setMaximumValueofx(24.0)

    # Cooling Energy Input Ratio Modifier Function of High Temperature Curve
    vrf_cool_eir_f_of_high_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    vrf_cool_eir_f_of_high_temp.setName('vrf_cool_eir_f_of_high_temp')
    vrf_cool_eir_f_of_high_temp.setCoefficient1Constant(-1.4395110176)
    vrf_cool_eir_f_of_high_temp.setCoefficient2x(0.1619850459)
    vrf_cool_eir_f_of_high_temp.setCoefficient3xPOW2(-0.0034911781)
    vrf_cool_eir_f_of_high_temp.setCoefficient4y(0.0269442645)
    vrf_cool_eir_f_of_high_temp.setCoefficient5yPOW2(0.0001346163)
    vrf_cool_eir_f_of_high_temp.setCoefficient6xTIMESY(-0.0006714941)
    vrf_cool_eir_f_of_high_temp.setMinimumValueofx(15.0)
    vrf_cool_eir_f_of_high_temp.setMaximumValueofx(23.9)
    vrf_cool_eir_f_of_high_temp.setMinimumValueofy(16.8)
    vrf_cool_eir_f_of_high_temp.setMaximumValueofy(43.3)

    # Cooling Energy Input Ratio Modifier Function of Low Part-Load Ratio Curve
    vrf_cooling_eir_low_plr = OpenStudio::Model::CurveCubic.new(model)
    vrf_cooling_eir_low_plr.setName('vrf_cool_eir_f_of_low_temp')
    vrf_cooling_eir_low_plr.setCoefficient1Constant(0.0734992169827752)
    vrf_cooling_eir_low_plr.setCoefficient2x(0.334783365234032)
    vrf_cooling_eir_low_plr.setCoefficient3xPOW2(0.591613015486343)
    vrf_cooling_eir_low_plr.setCoefficient4xPOW3(0.0)
    vrf_cooling_eir_low_plr.setMinimumValueofx(0.25)
    vrf_cooling_eir_low_plr.setMaximumValueofx(1.0)
    vrf_cooling_eir_low_plr.setMinimumCurveOutput(0.0)
    vrf_cooling_eir_low_plr.setMaximumCurveOutput(1.0)

    # Cooling Energy Input Ratio Modifier Function of High Part-Load Ratio Curve
    vrf_cooling_eir_high_plr = OpenStudio::Model::CurveCubic.new(model)
    vrf_cooling_eir_high_plr.setName('vrf_cooling_eir_high_plr')
    vrf_cooling_eir_high_plr.setCoefficient1Constant(1.0)
    vrf_cooling_eir_high_plr.setCoefficient2x(0.0)
    vrf_cooling_eir_high_plr.setCoefficient3xPOW2(0.0)
    vrf_cooling_eir_high_plr.setCoefficient4xPOW3(0.0)
    vrf_cooling_eir_high_plr.setMinimumValueofx(1.0)
    vrf_cooling_eir_high_plr.setMaximumValueofx(1.5)

    # Cooling Combination Ratio Correction Factor Curve
    vrf_cooling_comb_ratio = OpenStudio::Model::CurveCubic.new(model)
    vrf_cooling_comb_ratio.setName('vrf_cooling_comb_ratio')
    vrf_cooling_comb_ratio.setCoefficient1Constant(0.24034)
    vrf_cooling_comb_ratio.setCoefficient2x(-0.21873)
    vrf_cooling_comb_ratio.setCoefficient3xPOW2(1.97941)
    vrf_cooling_comb_ratio.setCoefficient4xPOW3(-1.02636)
    vrf_cooling_comb_ratio.setMinimumValueofx(0.5)
    vrf_cooling_comb_ratio.setMaximumValueofx(2.0)
    vrf_cooling_comb_ratio.setMinimumCurveOutput(0.5)
    vrf_cooling_comb_ratio.setMaximumCurveOutput(1.056)

    # Cooling Part-Load Fraction Correlation Curve
    vrf_cooling_cplffplr = OpenStudio::Model::CurveCubic.new(model)
    vrf_cooling_cplffplr.setName('vrf_cooling_cplffplr')
    vrf_cooling_cplffplr.setCoefficient1Constant(0.85)
    vrf_cooling_cplffplr.setCoefficient2x(0.15)
    vrf_cooling_cplffplr.setCoefficient3xPOW2(0.0)
    vrf_cooling_cplffplr.setCoefficient4xPOW3(0.0)
    vrf_cooling_cplffplr.setMinimumValueofx(1.0)
    vrf_cooling_cplffplr.setMaximumValueofx(1.0)

    # Heating Capacity Ratio Modifier Function of Low Temperature Curve Name
    vrf_heat_cap_f_of_low_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    vrf_heat_cap_f_of_low_temp.setName('vrf_heat_cap_f_of_low_temp')
    vrf_heat_cap_f_of_low_temp.setCoefficient1Constant(0.983220174655636)
    vrf_heat_cap_f_of_low_temp.setCoefficient2x(0.0157167577703294)
    vrf_heat_cap_f_of_low_temp.setCoefficient3xPOW2(-0.000835032422884084)
    vrf_heat_cap_f_of_low_temp.setCoefficient4y(0.0522939264581759)
    vrf_heat_cap_f_of_low_temp.setCoefficient5yPOW2(-0.000531556035364549)
    vrf_heat_cap_f_of_low_temp.setCoefficient6xTIMESY(-0.00190605953116024)
    vrf_heat_cap_f_of_low_temp.setMinimumValueofx(16.1)
    vrf_heat_cap_f_of_low_temp.setMaximumValueofx(23.9)
    vrf_heat_cap_f_of_low_temp.setMinimumValueofy(-25.0)
    vrf_heat_cap_f_of_low_temp.setMaximumValueofy(13.3)
    vrf_heat_cap_f_of_low_temp.setMinimumCurveOutput(0.515151515151515)
    vrf_heat_cap_f_of_low_temp.setMaximumCurveOutput(1.2)

    # Heating Capacity Ratio Boundary Curve Name
    vrf_heat_cap_ratio_boundary = OpenStudio::Model::CurveCubic.new(model)
    vrf_heat_cap_ratio_boundary.setName('vrf_heat_cap_ratio_boundary')
    vrf_heat_cap_ratio_boundary.setCoefficient1Constant(58.577)
    vrf_heat_cap_ratio_boundary.setCoefficient2x(-3.0255)
    vrf_heat_cap_ratio_boundary.setCoefficient3xPOW2(0.0193)
    vrf_heat_cap_ratio_boundary.setCoefficient4xPOW3(0.0)
    vrf_heat_cap_ratio_boundary.setMinimumValueofx(15)
    vrf_heat_cap_ratio_boundary.setMaximumValueofx(23.9)

    # Heating Capacity Ratio Modifier Function of High Temperature Curve Name
    vrf_heat_cap_f_of_high_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    vrf_heat_cap_f_of_high_temp.setName('vrf_heat_cap_f_of_high_temp')
    vrf_heat_cap_f_of_high_temp.setCoefficient1Constant(2.5859872368)
    vrf_heat_cap_f_of_high_temp.setCoefficient2x(-0.0953227101)
    vrf_heat_cap_f_of_high_temp.setCoefficient3xPOW2(0.0009553288)
    vrf_heat_cap_f_of_high_temp.setCoefficient4y(0.0)
    vrf_heat_cap_f_of_high_temp.setCoefficient5yPOW2(0.0)
    vrf_heat_cap_f_of_high_temp.setCoefficient6xTIMESY(0.0)
    vrf_heat_cap_f_of_high_temp.setMinimumValueofx(21.1)
    vrf_heat_cap_f_of_high_temp.setMaximumValueofx(27.2)
    vrf_heat_cap_f_of_high_temp.setMinimumValueofy(-944)
    vrf_heat_cap_f_of_high_temp.setMaximumValueofy(15)

    # Heating Energy Input Ratio Modifier Function of Low Temperature Curve Name
    vrf_heat_eir_f_of_low_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    vrf_heat_eir_f_of_low_temp.setName('vrf_heat_eir_f_of_low_temp')
    vrf_heat_eir_f_of_low_temp.setCoefficient1Constant(0.756830029796909)
    vrf_heat_eir_f_of_low_temp.setCoefficient2x(0.0457499799042671)
    vrf_heat_eir_f_of_low_temp.setCoefficient3xPOW2(-0.00136357240431388)
    vrf_heat_eir_f_of_low_temp.setCoefficient4y(0.0554884599902023)
    vrf_heat_eir_f_of_low_temp.setCoefficient5yPOW2(-0.00120700875497686)
    vrf_heat_eir_f_of_low_temp.setCoefficient6xTIMESY(-0.00303329271420931)
    vrf_heat_eir_f_of_low_temp.setMinimumValueofx(16.1)
    vrf_heat_eir_f_of_low_temp.setMaximumValueofx(23.9)
    vrf_heat_eir_f_of_low_temp.setMinimumValueofy(-25.0)
    vrf_heat_eir_f_of_low_temp.setMaximumValueofy(13.3)
    vrf_heat_eir_f_of_low_temp.setMinimumCurveOutput(0.7)
    vrf_heat_eir_f_of_low_temp.setMaximumCurveOutput(1.184)

    # Heating Energy Input Ratio Boundary Curve Name
    vrf_heat_eir_boundary = OpenStudio::Model::CurveCubic.new(model)
    vrf_heat_eir_boundary.setName('vrf_heat_eir_boundary')
    vrf_heat_eir_boundary.setCoefficient1Constant(58.577)
    vrf_heat_eir_boundary.setCoefficient2x(-3.0255)
    vrf_heat_eir_boundary.setCoefficient3xPOW2(0.0193)
    vrf_heat_eir_boundary.setCoefficient4xPOW3(0.0)
    vrf_heat_eir_boundary.setMinimumValueofx(15.0)
    vrf_heat_eir_boundary.setMaximumValueofx(23.9)

    # Heating Energy Input Ratio Modifier Function of High Temperature Curve Name
    vrf_heat_eir_f_of_high_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    vrf_heat_eir_f_of_high_temp.setName('vrf_heat_eir_f_of_high_temp')
    vrf_heat_eir_f_of_high_temp.setCoefficient1Constant(1.3885703646)
    vrf_heat_eir_f_of_high_temp.setCoefficient2x(-0.0229771462)
    vrf_heat_eir_f_of_high_temp.setCoefficient3xPOW2(0.000537274)
    vrf_heat_eir_f_of_high_temp.setCoefficient4y(-0.0273936962)
    vrf_heat_eir_f_of_high_temp.setCoefficient5yPOW2(0.0004030426)
    vrf_heat_eir_f_of_high_temp.setCoefficient6xTIMESY(-5.9786e-05)
    vrf_heat_eir_f_of_high_temp.setMinimumValueofx(21.1)
    vrf_heat_eir_f_of_high_temp.setMaximumValueofx(27.2)
    vrf_heat_eir_f_of_high_temp.setMinimumValueofy(0.0)
    vrf_heat_eir_f_of_high_temp.setMaximumValueofy(1.0)

    # Heating Performance Curve Outdoor Temperature Type
    vrf_outdoor_unit.setHeatingPerformanceCurveOutdoorTemperatureType('WetBulbTemperature')

    # Heating Energy Input Ratio Modifier Function of Low Part-Load Ratio Curve Name
    vrf_heating_eir_low_plr = OpenStudio::Model::CurveCubic.new(model)
    vrf_heating_eir_low_plr.setName('vrf_heating_eir_low_plr')
    vrf_heating_eir_low_plr.setCoefficient1Constant(0.0724906507105475)
    vrf_heating_eir_low_plr.setCoefficient2x(0.658189977561701)
    vrf_heating_eir_low_plr.setCoefficient3xPOW2(0.269259536275246)
    vrf_heating_eir_low_plr.setCoefficient4xPOW3(0.0)
    vrf_heating_eir_low_plr.setMinimumValueofx(0.25)
    vrf_heating_eir_low_plr.setMaximumValueofx(1.0)
    vrf_heating_eir_low_plr.setMinimumCurveOutput(0.0)
    vrf_heating_eir_low_plr.setMaximumCurveOutput(1.0)

    # Heating Energy Input Ratio Modifier Function of High Part-Load Ratio Curve Name
    vrf_heating_eir_hi_plr = OpenStudio::Model::CurveCubic.new(model)
    vrf_heating_eir_hi_plr.setName('vrf_heating_eir_hi_plr')
    vrf_heating_eir_hi_plr.setCoefficient1Constant(1.0)
    vrf_heating_eir_hi_plr.setCoefficient2x(0.0)
    vrf_heating_eir_hi_plr.setCoefficient3xPOW2(0.0)
    vrf_heating_eir_hi_plr.setCoefficient4xPOW3(0.0)
    vrf_heating_eir_hi_plr.setMinimumValueofx(1.0)
    vrf_heating_eir_hi_plr.setMaximumValueofx(1.5)

    # Heating Combination Ratio Correction Factor Curve Name
    vrf_heating_comb_ratio = OpenStudio::Model::CurveCubic.new(model)
    vrf_heating_comb_ratio.setName('vrf_heating_comb_ratio')
    vrf_heating_comb_ratio.setCoefficient1Constant(0.62115)
    vrf_heating_comb_ratio.setCoefficient2x(-1.55798)
    vrf_heating_comb_ratio.setCoefficient3xPOW2(3.36817)
    vrf_heating_comb_ratio.setCoefficient4xPOW3(-1.4224)
    vrf_heating_comb_ratio.setMinimumValueofx(0.5)
    vrf_heating_comb_ratio.setMaximumValueofx(2.0)
    vrf_heating_comb_ratio.setMinimumCurveOutput(0.5)
    vrf_heating_comb_ratio.setMaximumCurveOutput(1.155)

    # Heating Part-Load Fraction Correlation Curve Name
    vrf_heating_cplffplr = OpenStudio::Model::CurveCubic.new(model)
    vrf_heating_cplffplr.setName('vrf_heating_cplffplr')
    vrf_heating_cplffplr.setCoefficient1Constant(0.85)
    vrf_heating_cplffplr.setCoefficient2x(0.15)
    vrf_heating_cplffplr.setCoefficient3xPOW2(0.0)
    vrf_heating_cplffplr.setCoefficient4xPOW3(0.0)
    vrf_heating_cplffplr.setMinimumValueofx(1.0)
    vrf_heating_cplffplr.setMaximumValueofx(1.0)

    # Defrost Energy Input Ratio Modifier Function of Temperature Curve
    vrf_defrost_eir_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    vrf_defrost_eir_f_of_temp.setName('vrf_defrost_eir_f_of_temp')
    vrf_defrost_eir_f_of_temp.setCoefficient1Constant(-1.61908214818635)
    vrf_defrost_eir_f_of_temp.setCoefficient2x(0.185964818731756)
    vrf_defrost_eir_f_of_temp.setCoefficient3xPOW2(-0.00389610393381592)
    vrf_defrost_eir_f_of_temp.setCoefficient4y(-0.00901995326324613)
    vrf_defrost_eir_f_of_temp.setCoefficient5yPOW2(0.00030340007815629)
    vrf_defrost_eir_f_of_temp.setCoefficient6xTIMESY(0.000476048529099348)
    vrf_defrost_eir_f_of_temp.setMinimumValueofx(13.9)
    vrf_defrost_eir_f_of_temp.setMaximumValueofx(23.9)
    vrf_defrost_eir_f_of_temp.setMinimumValueofy(-5.0)
    vrf_defrost_eir_f_of_temp.setMaximumValueofy(50.0)
    vrf_defrost_eir_f_of_temp.setMinimumCurveOutput(0.27)
    vrf_defrost_eir_f_of_temp.setMaximumCurveOutput(1.155)

    # set defrost control
    vrf_outdoor_unit.setDefrostStrategy('ReverseCycle')
    vrf_outdoor_unit.setDefrostControl('OnDemand')

  end

  vrf_outdoor_unit.setCoolingCapacityRatioModifierFunctionofLowTemperatureCurve(vrf_cool_cap_f_of_low_temp) unless vrf_cool_cap_f_of_low_temp.nil?
  vrf_outdoor_unit.setCoolingCapacityRatioBoundaryCurve(vrf_cool_cap_ratio_boundary) unless vrf_cool_cap_ratio_boundary.nil?
  vrf_outdoor_unit.setCoolingCapacityRatioModifierFunctionofHighTemperatureCurve(vrf_cool_cap_f_of_high_temp) unless vrf_cool_cap_f_of_high_temp.nil?
  vrf_outdoor_unit.setCoolingEnergyInputRatioModifierFunctionofLowTemperatureCurve(vrf_cool_eir_f_of_low_temp) unless vrf_cool_eir_f_of_low_temp.nil?
  vrf_outdoor_unit.setCoolingEnergyInputRatioBoundaryCurve(vrf_cool_eir_ratio_boundary) unless vrf_cool_eir_ratio_boundary.nil?
  vrf_outdoor_unit.setCoolingEnergyInputRatioModifierFunctionofHighTemperatureCurve(vrf_cool_eir_f_of_high_temp) unless vrf_cool_eir_f_of_high_temp.nil?
  vrf_outdoor_unit.setCoolingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurve(vrf_cooling_eir_low_plr) unless vrf_cooling_eir_low_plr.nil?
  vrf_outdoor_unit.setCoolingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurve(vrf_cooling_eir_high_plr) unless vrf_cooling_eir_high_plr.nil?
  vrf_outdoor_unit.setCoolingCombinationRatioCorrectionFactorCurve(vrf_cooling_comb_ratio) unless vrf_cooling_comb_ratio.nil?
  vrf_outdoor_unit.setCoolingPartLoadFractionCorrelationCurve(vrf_cooling_cplffplr) unless vrf_cooling_cplffplr.nil?
  vrf_outdoor_unit.setHeatingCapacityRatioModifierFunctionofLowTemperatureCurve(vrf_heat_cap_f_of_low_temp) unless vrf_heat_cap_f_of_low_temp.nil?
  vrf_outdoor_unit.setHeatingCapacityRatioBoundaryCurve(vrf_heat_cap_ratio_boundary) unless vrf_heat_cap_ratio_boundary.nil?
  vrf_outdoor_unit.setHeatingCapacityRatioModifierFunctionofHighTemperatureCurve(vrf_heat_cap_f_of_high_temp) unless vrf_heat_cap_f_of_high_temp.nil?
  vrf_outdoor_unit.setHeatingEnergyInputRatioModifierFunctionofLowTemperatureCurve(vrf_heat_eir_f_of_low_temp) unless vrf_heat_eir_f_of_low_temp.nil?
  vrf_outdoor_unit.setHeatingEnergyInputRatioBoundaryCurve(vrf_heat_eir_boundary) unless vrf_heat_eir_boundary.nil?
  vrf_outdoor_unit.setHeatingEnergyInputRatioModifierFunctionofHighTemperatureCurve(vrf_heat_eir_f_of_high_temp) unless vrf_heat_eir_f_of_high_temp.nil?
  vrf_outdoor_unit.setHeatingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurve(vrf_heating_eir_low_plr) unless vrf_heating_eir_low_plr.nil?
  vrf_outdoor_unit.setHeatingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurve(vrf_heating_eir_hi_plr) unless vrf_heating_eir_hi_plr.nil?
  vrf_outdoor_unit.setHeatingCombinationRatioCorrectionFactorCurve(vrf_heating_comb_ratio) unless vrf_heating_comb_ratio.nil?
  vrf_outdoor_unit.setHeatingPartLoadFractionCorrelationCurve(vrf_heating_cplffplr) unless vrf_heating_cplffplr.nil?
  vrf_outdoor_unit.setDefrostEnergyInputRatioModifierFunctionofTemperatureCurve(vrf_defrost_eir_f_of_temp) unless vrf_defrost_eir_f_of_temp.nil?

  return vrf_outdoor_unit
end
create_boiler_hot_water(model, hot_water_loop: nil, name: 'Boiler', fuel_type: 'NaturalGas', draft_type: 'Natural', nominal_thermal_efficiency: 0.80, eff_curve_temp_eval_var: 'LeavingBoiler', flow_mode: 'LeavingSetpointModulated', lvg_temp_dsgn_f: 180.0, out_temp_lmt_f: 203.0, min_plr: 0.0, max_plr: 1.2, opt_plr: 1.0, sizing_factor: nil) click to toggle source

Prototype BoilerHotWater object

@param model [OpenStudio::Model::Model] OpenStudio model object @param hot_water_loop [<OpenStudio::Model::PlantLoop>] a hot water loop served by the boiler @param name [String] the name of the boiler, or nil in which case it will be defaulted @param fuel_type [String] type of fuel serving the boiler @param draft_type [String] Boiler type Condensing, MechanicalNoncondensing, Natural (default) @param nominal_thermal_efficiency [Double] boiler nominal thermal efficiency @param eff_curve_temp_eval_var [String] LeavingBoiler or EnteringBoiler temperature for the boiler efficiency curve @param flow_mode [String] boiler flow mode @param lvg_temp_dsgn_f [Double] boiler leaving design temperature in degrees Fahrenheit

note that this field is deprecated in OS versions 3.0+

@param out_temp_lmt_f [Double] boiler outlet temperature limit in degrees Fahrenheit @param min_plr [Double] boiler minimum part load ratio @param max_plr [Double] boiler maximum part load ratio @param opt_plr [Double] boiler optimum part load ratio @param sizing_factor [Double] boiler oversizing factor @return [OpenStudio::Model::BoilerHotWater] the boiler object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.BoilerHotWater.rb, line 22
def create_boiler_hot_water(model,
                            hot_water_loop: nil,
                            name: 'Boiler',
                            fuel_type: 'NaturalGas',
                            draft_type: 'Natural',
                            nominal_thermal_efficiency: 0.80,
                            eff_curve_temp_eval_var: 'LeavingBoiler',
                            flow_mode: 'LeavingSetpointModulated',
                            lvg_temp_dsgn_f: 180.0, # 82.22 degrees Celsius
                            out_temp_lmt_f: 203.0, # 95.0 degrees Celsius
                            min_plr: 0.0,
                            max_plr: 1.2,
                            opt_plr: 1.0,
                            sizing_factor: nil)

  # create the boiler
  boiler = OpenStudio::Model::BoilerHotWater.new(model)
  if name.nil?
    if !hot_water_loop.nil?
      boiler.setName("#{hot_water_loop.name} Boiler")
    else
      boiler.setName('Boiler')
    end
  else
    boiler.setName(name)
  end

  if fuel_type.nil? || fuel_type == 'Gas'
    boiler.setFuelType('NaturalGas')
  elsif fuel_type == 'Propane' || fuel_type == 'PropaneGas'
    boiler.setFuelType('Propane')
  else
    boiler.setFuelType(fuel_type)
  end

  if nominal_thermal_efficiency.nil?
    boiler.setNominalThermalEfficiency(0.8)
  else
    boiler.setNominalThermalEfficiency(nominal_thermal_efficiency)
  end

  if eff_curve_temp_eval_var.nil?
    boiler.setEfficiencyCurveTemperatureEvaluationVariable('LeavingBoiler')
  else
    boiler.setEfficiencyCurveTemperatureEvaluationVariable(eff_curve_temp_eval_var)
  end

  if flow_mode.nil?
    boiler.setBoilerFlowMode('LeavingSetpointModulated')
  else
    boiler.setBoilerFlowMode(flow_mode)
  end

  if model.version < OpenStudio::VersionString.new('3.0.0')
    if lvg_temp_dsgn_f.nil?
      boiler.setDesignWaterOutletTemperature(OpenStudio.convert(180.0, 'F', 'C').get)
    else
      boiler.setDesignWaterOutletTemperature(OpenStudio.convert(lvg_temp_dsgn_f, 'F', 'C').get)
    end
  end

  if out_temp_lmt_f.nil?
    boiler.setWaterOutletUpperTemperatureLimit(OpenStudio.convert(203.0, 'F', 'C').get)
  else
    boiler.setWaterOutletUpperTemperatureLimit(OpenStudio.convert(out_temp_lmt_f, 'F', 'C').get)
  end

  # logic to set different defaults for condensing boilers if not specified
  if draft_type == 'Condensing'
    if model.version < OpenStudio::VersionString.new('3.0.0')
      # default to 120 degrees Fahrenheit (48.49 degrees Celsius)
      boiler.setDesignWaterOutletTemperature(OpenStudio.convert(120.0, 'F', 'C').get) if lvg_temp_dsgn_f.nil?
    end
    boiler.setNominalThermalEfficiency(0.96) if nominal_thermal_efficiency.nil?
  end

  if min_plr.nil?
    boiler.setMinimumPartLoadRatio(0.0)
  else
    boiler.setMinimumPartLoadRatio(min_plr)
  end

  if max_plr.nil?
    boiler.setMaximumPartLoadRatio(1.2)
  else
    boiler.setMaximumPartLoadRatio(max_plr)
  end

  if opt_plr.nil?
    boiler.setOptimumPartLoadRatio(1.0)
  else
    boiler.setOptimumPartLoadRatio(opt_plr)
  end

  boiler.setSizingFactor(sizing_factor) unless sizing_factor.nil?

  # add to supply side of hot water loop if specified
  hot_water_loop.addSupplyBranchForComponent(boiler) unless hot_water_loop.nil?

  return boiler
end
create_central_air_source_heat_pump(model, hot_water_loop, name: nil, cop: 3.65) click to toggle source

Prototype CentralAirSourceHeatPump object using PlantComponentUserDefined

@param model [OpenStudio::Model::Model] OpenStudio model object @param hot_water_loop [<OpenStudio::Model::PlantLoop>] a hot water loop served by the central air source heat pump @param name [String] the name of the central air source heat pump, or nil in which case it will be defaulted @param cop [Double] air source heat pump rated cop @return [OpenStudio::Model::PlantComponentUserDefined] a plant component representing the air source heat pump @todo update curve to better calculate based on the rated cop @todo refactor to use the new EnergyPlus central air source heat pump object when it becomes available

set hot_water_loop to an optional keyword argument, and add input keyword arguments for other characteristics
# File lib/openstudio-standards/prototypes/common/objects/Prototype.CentralAirSourceHeatPump.rb, line 14
  def create_central_air_source_heat_pump(model,
                                          hot_water_loop,
                                          name: nil,
                                          cop: 3.65)

    # create the PlantComponentUserDefined object as a proxy for the Central Air Source Heat Pump
    plant_comp = OpenStudio::Model::PlantComponentUserDefined.new(model)
    if name.nil?
      if !hot_water_loop.nil?
        name = "#{hot_water_loop.name} Central Air Source Heat Pump"
      else
        name = 'Central Air Source Heat Pump'
      end
    end

    # change equipment name for EMS validity
    plant_comp.setName(name.gsub(/[ +-.]/, '_'))

    # set plant component properties
    plant_comp.setPlantLoadingMode('MeetsLoadWithNominalCapacityHiOutLimit')
    plant_comp.setPlantLoopFlowRequestMode('NeedsFlowIfLoopIsOn')

    # plant design volume flow rate internal variable
    vdot_des_int_var = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(model, 'Plant Design Volume Flow Rate')
    vdot_des_int_var.setName("#{plant_comp.name}_Vdot_Des_Int_Var")
    vdot_des_int_var.setInternalDataIndexKeyName(hot_water_loop.handle.to_s)

    # inlet temperature internal variable
    tin_int_var = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(model, 'Inlet Temperature for Plant Connection 1')
    tin_int_var.setName("#{plant_comp.name}_Tin_Int_Var")
    tin_int_var.setInternalDataIndexKeyName(plant_comp.handle.to_s)

    # inlet mass flow rate internal variable
    mdot_int_var = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(model, 'Inlet Mass Flow Rate for Plant Connection 1')
    mdot_int_var.setName("#{plant_comp.name}_Mdot_Int_Var")
    mdot_int_var.setInternalDataIndexKeyName(plant_comp.handle.to_s)

    # inlet specific heat internal variable
    cp_int_var = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(model, 'Inlet Specific Heat for Plant Connection 1')
    cp_int_var.setName("#{plant_comp.name}_Cp_Int_Var")
    cp_int_var.setInternalDataIndexKeyName(plant_comp.handle.to_s)

    # inlet density internal variable
    rho_int_var = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(model, 'Inlet Density for Plant Connection 1')
    rho_int_var.setName("#{plant_comp.name}_rho_Int_Var")
    rho_int_var.setInternalDataIndexKeyName(plant_comp.handle.to_s)

    # load request internal variable
    load_int_var = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(model, 'Load Request for Plant Connection 1')
    load_int_var.setName("#{plant_comp.name}_Load_Int_Var")
    load_int_var.setInternalDataIndexKeyName(plant_comp.handle.to_s)

    # supply outlet node setpoint temperature sensor
    setpt_mgr_sch_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')
    setpt_mgr_sch_sen.setName("#{plant_comp.name}_Setpt_Mgr_Temp_Sen")
    hot_water_loop.supplyOutletNode.setpointManagers.each do |m|
      if m.to_SetpointManagerScheduled.is_initialized
        setpt_mgr_sch_sen.setKeyName(m.to_SetpointManagerScheduled.get.schedule.name.to_s)
      end
    end

    # outdoor air drybulb temperature sensor
    oa_dbt_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Site Outdoor Air Drybulb Temperature')
    oa_dbt_sen.setName("#{plant_comp.name}_OA_DBT_Sen")
    oa_dbt_sen.setKeyName('Environment')

    # minimum mass flow rate actuator
    mdot_min_act = plant_comp.minimumMassFlowRateActuator.get
    mdot_min_act.setName("#{plant_comp.name}_Mdot_Min_Act")

    # maximum mass flow rate actuator
    mdot_max_act = plant_comp.maximumMassFlowRateActuator.get
    mdot_max_act.setName("#{plant_comp.name}_Mdot_Max_Act")

    # design flow rate actuator
    vdot_des_act = plant_comp.designVolumeFlowRateActuator.get
    vdot_des_act.setName("#{plant_comp.name}_Vdot_Des_Act")

    # minimum loading capacity actuator
    cap_min_act = plant_comp.minimumLoadingCapacityActuator.get
    cap_min_act.setName("#{plant_comp.name}_Cap_Min_Act")

    # maximum loading capacity actuator
    cap_max_act = plant_comp.maximumLoadingCapacityActuator.get
    cap_max_act.setName("#{plant_comp.name}_Cap_Max_Act")

    # optimal loading capacity actuator
    cap_opt_act = plant_comp.optimalLoadingCapacityActuator.get
    cap_opt_act.setName("#{plant_comp.name}_Cap_Opt_Act")

    # outlet temperature actuator
    tout_act = plant_comp.outletTemperatureActuator.get
    tout_act.setName("#{plant_comp.name}_Tout_Act")

    # mass flow rate actuator
    mdot_req_act = plant_comp.massFlowRateActuator.get
    mdot_req_act.setName("#{plant_comp.name}_Mdot_Req_Act")

    # heat pump COP curve
    constant_coeff = 1.932 + (cop - 3.65)
    hp_cop_curve = OpenStudio::Model::CurveQuadratic.new(model)
    hp_cop_curve.setCoefficient1Constant(constant_coeff)
    hp_cop_curve.setCoefficient2x(0.227674286)
    hp_cop_curve.setCoefficient3xPOW2(-0.007313143)
    hp_cop_curve.setMinimumValueofx(1.67)
    hp_cop_curve.setMaximumValueofx(12.78)
    hp_cop_curve.setInputUnitTypeforX('Temperature')
    hp_cop_curve.setOutputUnitType('Dimensionless')

    # heat pump COP curve index variable
    hp_cop_curve_idx_var = OpenStudio::Model::EnergyManagementSystemCurveOrTableIndexVariable.new(model, hp_cop_curve)

    # high outlet temperature limit actuator
    tout_max_act = OpenStudio::Model::EnergyManagementSystemActuator.new(plant_comp, 'Plant Connection 1', 'High Outlet Temperature Limit')
    tout_max_act.setName("#{plant_comp.name}_Tout_Max_Act")

    # init program
    init_pgrm = plant_comp.plantInitializationProgram.get
    init_pgrm.setName("#{plant_comp.name}_Init_Pgrm")
    init_pgrm_body = <<-EMS
    SET Loop_Exit_Temp = #{hot_water_loop.sizingPlant.designLoopExitTemperature}
    SET Loop_Delta_Temp = #{hot_water_loop.sizingPlant.loopDesignTemperatureDifference}
    SET Cp = @CPHW Loop_Exit_Temp
    SET rho = @RhoH2O Loop_Exit_Temp
    SET #{vdot_des_act.handle} = #{vdot_des_int_var.handle}
    SET #{mdot_min_act.handle} = 0
    SET Mdot_Max = #{vdot_des_int_var.handle} * rho
    SET #{mdot_max_act.handle} = Mdot_Max
    SET Cap = Mdot_Max * Cp * Loop_Delta_Temp
    SET #{cap_min_act.handle} = 0
    SET #{cap_max_act.handle} = Cap
    SET #{cap_opt_act.handle} = 1 * Cap
    EMS
    init_pgrm.setBody(init_pgrm_body)

    # sim program
    sim_pgrm = plant_comp.plantSimulationProgram.get
    sim_pgrm.setName("#{plant_comp.name}_Sim_Pgrm")
    sim_pgrm_body = <<-EMS
    SET tmp = #{load_int_var.handle}
    SET tmp = #{tin_int_var.handle}
    SET tmp = #{mdot_int_var.handle}
    SET #{tout_max_act.handle} = 75.0
    IF #{load_int_var.handle} == 0
    SET #{tout_act.handle} = #{tin_int_var.handle}
    SET #{mdot_req_act.handle} = 0
    SET Elec = 0
    RETURN
    ENDIF
    IF #{load_int_var.handle} >= #{cap_max_act.handle}
    SET Qdot = #{cap_max_act.handle}
    SET Mdot = #{mdot_max_act.handle}
    SET #{mdot_req_act.handle} = Mdot
    SET #{tout_act.handle} = (Qdot / (Mdot * #{cp_int_var.handle})) + #{tin_int_var.handle}
    IF #{tout_act.handle} > #{tout_max_act.handle}
    SET #{tout_act.handle} = #{tout_max_act.handle}
    SET Qdot = Mdot * #{cp_int_var.handle} * (#{tout_act.handle} - #{tin_int_var.handle})
    ENDIF
    ELSE
    SET Qdot = #{load_int_var.handle}
    SET #{tout_act.handle} = #{setpt_mgr_sch_sen.handle}
    SET Mdot = Qdot / (#{cp_int_var.handle} * (#{tout_act.handle} - #{tin_int_var.handle}))
    SET #{mdot_req_act.handle} = Mdot
    ENDIF
    SET Tdb = #{oa_dbt_sen.handle}
    SET COP = @CurveValue #{hp_cop_curve_idx_var.handle} Tdb
    SET EIR = 1 / COP
    SET Pwr = Qdot * EIR
    SET Elec = Pwr * SystemTimestep * 3600
    EMS
    sim_pgrm.setBody(sim_pgrm_body)

    # init program calling manager
    init_mgr = plant_comp.plantInitializationProgramCallingManager.get
    init_mgr.setName("#{plant_comp.name}_Init_Pgrm_Mgr")

    # sim program calling manager
    sim_mgr = plant_comp.plantSimulationProgramCallingManager.get
    sim_mgr.setName("#{plant_comp.name}_Sim_Pgrm_Mgr")

    # metered output variable
    elec_mtr_out_var = OpenStudio::Model::EnergyManagementSystemMeteredOutputVariable.new(model, "#{plant_comp.name} Electricity Consumption")
    elec_mtr_out_var.setName("#{plant_comp.name} Electricity Consumption")
    elec_mtr_out_var.setEMSVariableName('Elec')
    elec_mtr_out_var.setUpdateFrequency('SystemTimestep')
    elec_mtr_out_var.setString(4, sim_pgrm.handle.to_s)
    elec_mtr_out_var.setResourceType('Electricity')
    elec_mtr_out_var.setGroupType('HVAC')
    elec_mtr_out_var.setEndUseCategory('Heating')
    elec_mtr_out_var.setEndUseSubcategory('')
    elec_mtr_out_var.setUnits('J')

    # add to supply side of hot water loop if specified
    hot_water_loop.addSupplyBranchForComponent(plant_comp) unless hot_water_loop.nil?

    # add operation scheme
    htg_op_scheme = OpenStudio::Model::PlantEquipmentOperationHeatingLoad.new(model)
    htg_op_scheme.addEquipment(1000000000, plant_comp)
    hot_water_loop.setPlantEquipmentOperationHeatingLoad(htg_op_scheme)

    return plant_comp
  end
create_coil_cooling_dx_single_speed(model, air_loop_node: nil, name: '1spd DX Clg Coil', schedule: nil, type: nil, cop: nil) click to toggle source

Prototype CoilCoolingDXSingleSpeed object Enters in default curves for coil by type of coil

@param model [OpenStudio::Model::Model] OpenStudio model object @param air_loop_node [<OpenStudio::Model::Node>] the coil will be placed on this node of the air loop @param name [String] the name of the system, or nil in which case it will be defaulted @param schedule [String] name of the availability schedule, or [<OpenStudio::Model::Schedule>] Schedule object, or nil in which case default to always on @param type [String] the type of single speed DX coil to reference the correct curve set @param cop [Double] rated cooling coefficient of performance @return [OpenStudio::Model::CoilCoolingDXTwoSpeed] the DX cooling coil

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilCoolingDXSingleSpeed.rb, line 14
def create_coil_cooling_dx_single_speed(model,
                                        air_loop_node: nil,
                                        name: '1spd DX Clg Coil',
                                        schedule: nil,
                                        type: nil,
                                        cop: nil)

  clg_coil = OpenStudio::Model::CoilCoolingDXSingleSpeed.new(model)

  # add to air loop if specified
  clg_coil.addToNode(air_loop_node) unless air_loop_node.nil?

  # set coil name
  clg_coil.setName(name)

  # set coil availability schedule
  if schedule.nil?
    # default always on
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  elsif schedule.class == String
    coil_availability_schedule = model_add_schedule(model, schedule)

    if coil_availability_schedule.nil? && schedule == 'alwaysOffDiscreteSchedule'
      coil_availability_schedule = model.alwaysOffDiscreteSchedule
    elsif coil_availability_schedule.nil?
      coil_availability_schedule = model.alwaysOnDiscreteSchedule
    end
  elsif !schedule.to_Schedule.empty?
    coil_availability_schedule = schedule
  else
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  end
  clg_coil.setAvailabilitySchedule(coil_availability_schedule)

  # set coil cop
  clg_coil.setRatedCOP(cop) unless cop.nil?

  clg_cap_f_of_temp = nil
  clg_cap_f_of_flow = nil
  clg_energy_input_ratio_f_of_temp = nil
  clg_energy_input_ratio_f_of_flow = nil
  clg_part_load_ratio = nil

  # curve sets
  case type
  when 'OS default'
    # use OS defaults

  when 'Heat Pump'
    # "PSZ-AC_Unitary_PackagecoolCapFT"
    clg_cap_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_cap_f_of_temp.setCoefficient1Constant(0.766956)
    clg_cap_f_of_temp.setCoefficient2x(0.0107756)
    clg_cap_f_of_temp.setCoefficient3xPOW2(-0.0000414703)
    clg_cap_f_of_temp.setCoefficient4y(0.00134961)
    clg_cap_f_of_temp.setCoefficient5yPOW2(-0.000261144)
    clg_cap_f_of_temp.setCoefficient6xTIMESY(0.000457488)
    clg_cap_f_of_temp.setMinimumValueofx(12.78)
    clg_cap_f_of_temp.setMaximumValueofx(23.89)
    clg_cap_f_of_temp.setMinimumValueofy(21.1)
    clg_cap_f_of_temp.setMaximumValueofy(46.1)

    clg_cap_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)
    clg_cap_f_of_flow.setCoefficient1Constant(0.8)
    clg_cap_f_of_flow.setCoefficient2x(0.2)
    clg_cap_f_of_flow.setCoefficient3xPOW2(0.0)
    clg_cap_f_of_flow.setMinimumValueofx(0.5)
    clg_cap_f_of_flow.setMaximumValueofx(1.5)

    clg_energy_input_ratio_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_energy_input_ratio_f_of_temp.setCoefficient1Constant(0.297145)
    clg_energy_input_ratio_f_of_temp.setCoefficient2x(0.0430933)
    clg_energy_input_ratio_f_of_temp.setCoefficient3xPOW2(-0.000748766)
    clg_energy_input_ratio_f_of_temp.setCoefficient4y(0.00597727)
    clg_energy_input_ratio_f_of_temp.setCoefficient5yPOW2(0.000482112)
    clg_energy_input_ratio_f_of_temp.setCoefficient6xTIMESY(-0.000956448)
    clg_energy_input_ratio_f_of_temp.setMinimumValueofx(12.78)
    clg_energy_input_ratio_f_of_temp.setMaximumValueofx(23.89)
    clg_energy_input_ratio_f_of_temp.setMinimumValueofy(21.1)
    clg_energy_input_ratio_f_of_temp.setMaximumValueofy(46.1)

    clg_energy_input_ratio_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)
    clg_energy_input_ratio_f_of_flow.setCoefficient1Constant(1.156)
    clg_energy_input_ratio_f_of_flow.setCoefficient2x(-0.1816)
    clg_energy_input_ratio_f_of_flow.setCoefficient3xPOW2(0.0256)
    clg_energy_input_ratio_f_of_flow.setMinimumValueofx(0.5)
    clg_energy_input_ratio_f_of_flow.setMaximumValueofx(1.5)

    clg_part_load_ratio = OpenStudio::Model::CurveQuadratic.new(model)
    clg_part_load_ratio.setCoefficient1Constant(0.85)
    clg_part_load_ratio.setCoefficient2x(0.15)
    clg_part_load_ratio.setCoefficient3xPOW2(0.0)
    clg_part_load_ratio.setMinimumValueofx(0.0)
    clg_part_load_ratio.setMaximumValueofx(1.0)

  when 'PSZ-AC'
    # Defaults to "DOE Ref DX Clg Coil Cool-Cap-fT"
    clg_cap_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_cap_f_of_temp.setCoefficient1Constant(0.9712123)
    clg_cap_f_of_temp.setCoefficient2x(-0.015275502)
    clg_cap_f_of_temp.setCoefficient3xPOW2(0.0014434524)
    clg_cap_f_of_temp.setCoefficient4y(-0.00039321)
    clg_cap_f_of_temp.setCoefficient5yPOW2(-0.0000068364)
    clg_cap_f_of_temp.setCoefficient6xTIMESY(-0.0002905956)
    clg_cap_f_of_temp.setMinimumValueofx(-100.0)
    clg_cap_f_of_temp.setMaximumValueofx(100.0)
    clg_cap_f_of_temp.setMinimumValueofy(-100.0)
    clg_cap_f_of_temp.setMaximumValueofy(100.0)

    clg_cap_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)
    clg_cap_f_of_flow.setCoefficient1Constant(1.0)
    clg_cap_f_of_flow.setCoefficient2x(0.0)
    clg_cap_f_of_flow.setCoefficient3xPOW2(0.0)
    clg_cap_f_of_flow.setMinimumValueofx(-100.0)
    clg_cap_f_of_flow.setMaximumValueofx(100.0)

    # "DOE Ref DX Clg Coil Cool-EIR-fT",
    clg_energy_input_ratio_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_energy_input_ratio_f_of_temp.setCoefficient1Constant(0.28687133)
    clg_energy_input_ratio_f_of_temp.setCoefficient2x(0.023902164)
    clg_energy_input_ratio_f_of_temp.setCoefficient3xPOW2(-0.000810648)
    clg_energy_input_ratio_f_of_temp.setCoefficient4y(0.013458546)
    clg_energy_input_ratio_f_of_temp.setCoefficient5yPOW2(0.0003389364)
    clg_energy_input_ratio_f_of_temp.setCoefficient6xTIMESY(-0.0004870044)
    clg_energy_input_ratio_f_of_temp.setMinimumValueofx(-100.0)
    clg_energy_input_ratio_f_of_temp.setMaximumValueofx(100.0)
    clg_energy_input_ratio_f_of_temp.setMinimumValueofy(-100.0)
    clg_energy_input_ratio_f_of_temp.setMaximumValueofy(100.0)

    clg_energy_input_ratio_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)
    clg_energy_input_ratio_f_of_flow.setCoefficient1Constant(1.0)
    clg_energy_input_ratio_f_of_flow.setCoefficient2x(0.0)
    clg_energy_input_ratio_f_of_flow.setCoefficient3xPOW2(0.0)
    clg_energy_input_ratio_f_of_flow.setMinimumValueofx(-100.0)
    clg_energy_input_ratio_f_of_flow.setMaximumValueofx(100.0)

    # "DOE Ref DX Clg Coil Cool-PLF-fPLR"
    clg_part_load_ratio = OpenStudio::Model::CurveQuadratic.new(model)
    clg_part_load_ratio.setCoefficient1Constant(0.90949556)
    clg_part_load_ratio.setCoefficient2x(0.09864773)
    clg_part_load_ratio.setCoefficient3xPOW2(-0.00819488)
    clg_part_load_ratio.setMinimumValueofx(0.0)
    clg_part_load_ratio.setMaximumValueofx(1.0)
    clg_part_load_ratio.setMinimumCurveOutput(0.7)
    clg_part_load_ratio.setMaximumCurveOutput(1.0)

  when 'Window AC'
    # Performance curves
    # From Frigidaire 10.7 EER unit in Winkler et. al. Lab Testing of Window ACs (2013)
    # @note These coefficients are in SI UNITS
    cool_cap_ft_coeffs_si = [0.6405, 0.01568, 0.0004531, 0.001615, -0.0001825, 0.00006614]
    cool_eir_ft_coeffs_si = [2.287, -0.1732, 0.004745, 0.01662, 0.000484, -0.001306]
    cool_cap_fflow_coeffs = [0.887, 0.1128, 0]
    cool_eir_fflow_coeffs = [1.763, -0.6081, 0]
    cool_plf_fplr_coeffs = [0.78, 0.22, 0]

    # Make the curves
    clg_cap_f_of_temp = create_curve_biquadratic(model, cool_cap_ft_coeffs_si, 'RoomAC-Cap-fT', 0, 100, 0, 100, nil, nil)
    clg_cap_f_of_flow = create_curve_quadratic(model, cool_cap_fflow_coeffs, 'RoomAC-Cap-fFF', 0, 2, 0, 2, is_dimensionless = true)
    clg_energy_input_ratio_f_of_temp = create_curve_biquadratic(model, cool_eir_ft_coeffs_si, 'RoomAC-EIR-fT', 0, 100, 0, 100, nil, nil)
    clg_energy_input_ratio_f_of_flow = create_curve_quadratic(model, cool_eir_fflow_coeffs, 'RoomAC-EIR-fFF', 0, 2, 0, 2, is_dimensionless = true)
    clg_part_load_ratio = create_curve_quadratic(model, cool_plf_fplr_coeffs, 'RoomAC-PLF-fPLR', 0, 1, 0, 1, is_dimensionless = true)

  when 'Residential Central AC'
    # Performance curves
    # These coefficients are in IP UNITS
    cool_cap_ft_coeffs_ip = [3.670270705, -0.098652414, 0.000955906, 0.006552414, -0.0000156, -0.000131877]
    cool_eir_ft_coeffs_ip = [-3.302695861, 0.137871531, -0.001056996, -0.012573945, 0.000214638, -0.000145054]
    cool_cap_fflow_coeffs = [0.718605468, 0.410099989, -0.128705457]
    cool_eir_fflow_coeffs = [1.32299905, -0.477711207, 0.154712157]
    cool_plf_fplr_coeffs = [0.8, 0.2, 0]

    # Convert coefficients from IP to SI
    cool_cap_ft_coeffs_si = convert_curve_biquadratic(cool_cap_ft_coeffs_ip)
    cool_eir_ft_coeffs_si = convert_curve_biquadratic(cool_eir_ft_coeffs_ip)

    # Make the curves
    clg_cap_f_of_temp = create_curve_biquadratic(model, cool_cap_ft_coeffs_si, 'AC-Cap-fT', 0, 100, 0, 100, nil, nil)
    clg_cap_f_of_flow = create_curve_quadratic(model, cool_cap_fflow_coeffs, 'AC-Cap-fFF', 0, 2, 0, 2, is_dimensionless = true)
    clg_energy_input_ratio_f_of_temp = create_curve_biquadratic(model, cool_eir_ft_coeffs_si, 'AC-EIR-fT', 0, 100, 0, 100, nil, nil)
    clg_energy_input_ratio_f_of_flow = create_curve_quadratic(model, cool_eir_fflow_coeffs, 'AC-EIR-fFF', 0, 2, 0, 2, is_dimensionless = true)
    clg_part_load_ratio = create_curve_quadratic(model, cool_plf_fplr_coeffs, 'AC-PLF-fPLR', 0, 1, 0, 1, is_dimensionless = true)

  when 'Residential Central ASHP'
    # Performance curves
    # These coefficients are in IP UNITS
    cool_cap_ft_coeffs_ip = [3.68637657, -0.098352478, 0.000956357, 0.005838141, -0.0000127, -0.000131702]
    cool_eir_ft_coeffs_ip = [-3.437356399, 0.136656369, -0.001049231, -0.0079378, 0.000185435, -0.0001441]
    cool_cap_fflow_coeffs = [0.718664047, 0.41797409, -0.136638137]
    cool_eir_fflow_coeffs = [1.143487507, -0.13943972, -0.004047787]
    cool_plf_fplr_coeffs = [0.8, 0.2, 0]

    # Convert coefficients from IP to SI
    cool_cap_ft_coeffs_si = convert_curve_biquadratic(cool_cap_ft_coeffs_ip)
    cool_eir_ft_coeffs_si = convert_curve_biquadratic(cool_eir_ft_coeffs_ip)

    # Make the curves
    clg_cap_f_of_temp = create_curve_biquadratic(model, cool_cap_ft_coeffs_si, 'Cool-Cap-fT', 0, 100, 0, 100, nil, nil)
    clg_cap_f_of_flow = create_curve_quadratic(model, cool_cap_fflow_coeffs, 'Cool-Cap-fFF', 0, 2, 0, 2, is_dimensionless = true)
    clg_energy_input_ratio_f_of_temp = create_curve_biquadratic(model, cool_eir_ft_coeffs_si, 'Cool-EIR-fT', 0, 100, 0, 100, nil, nil)
    clg_energy_input_ratio_f_of_flow = create_curve_quadratic(model, cool_eir_fflow_coeffs, 'Cool-EIR-fFF', 0, 2, 0, 2, is_dimensionless = true)
    clg_part_load_ratio = create_curve_quadratic(model, cool_plf_fplr_coeffs, 'Cool-PLF-fPLR', 0, 1, 0, 1, is_dimensionless = true)

  else # default curve set, type == 'Split AC' || 'PTAC'
    clg_cap_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_cap_f_of_temp.setCoefficient1Constant(0.942587793)
    clg_cap_f_of_temp.setCoefficient2x(0.009543347)
    clg_cap_f_of_temp.setCoefficient3xPOW2(0.00068377)
    clg_cap_f_of_temp.setCoefficient4y(-0.011042676)
    clg_cap_f_of_temp.setCoefficient5yPOW2(0.000005249)
    clg_cap_f_of_temp.setCoefficient6xTIMESY(-0.00000972)
    clg_cap_f_of_temp.setMinimumValueofx(12.77778)
    clg_cap_f_of_temp.setMaximumValueofx(23.88889)
    clg_cap_f_of_temp.setMinimumValueofy(23.88889)
    clg_cap_f_of_temp.setMaximumValueofy(46.11111)

    clg_cap_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)
    clg_cap_f_of_flow.setCoefficient1Constant(0.8)
    clg_cap_f_of_flow.setCoefficient2x(0.2)
    clg_cap_f_of_flow.setCoefficient3xPOW2(0)
    clg_cap_f_of_flow.setMinimumValueofx(0.5)
    clg_cap_f_of_flow.setMaximumValueofx(1.5)

    clg_energy_input_ratio_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_energy_input_ratio_f_of_temp.setCoefficient1Constant(0.342414409)
    clg_energy_input_ratio_f_of_temp.setCoefficient2x(0.034885008)
    clg_energy_input_ratio_f_of_temp.setCoefficient3xPOW2(-0.0006237)
    clg_energy_input_ratio_f_of_temp.setCoefficient4y(0.004977216)
    clg_energy_input_ratio_f_of_temp.setCoefficient5yPOW2(0.000437951)
    clg_energy_input_ratio_f_of_temp.setCoefficient6xTIMESY(-0.000728028)
    clg_energy_input_ratio_f_of_temp.setMinimumValueofx(12.77778)
    clg_energy_input_ratio_f_of_temp.setMaximumValueofx(23.88889)
    clg_energy_input_ratio_f_of_temp.setMinimumValueofy(23.88889)
    clg_energy_input_ratio_f_of_temp.setMaximumValueofy(46.11111)

    clg_energy_input_ratio_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)
    clg_energy_input_ratio_f_of_flow.setCoefficient1Constant(1.1552)
    clg_energy_input_ratio_f_of_flow.setCoefficient2x(-0.1808)
    clg_energy_input_ratio_f_of_flow.setCoefficient3xPOW2(0.0256)
    clg_energy_input_ratio_f_of_flow.setMinimumValueofx(0.5)
    clg_energy_input_ratio_f_of_flow.setMaximumValueofx(1.5)

    clg_part_load_ratio = OpenStudio::Model::CurveQuadratic.new(model)
    clg_part_load_ratio.setCoefficient1Constant(0.85)
    clg_part_load_ratio.setCoefficient2x(0.15)
    clg_part_load_ratio.setCoefficient3xPOW2(0.0)
    clg_part_load_ratio.setMinimumValueofx(0.0)
    clg_part_load_ratio.setMaximumValueofx(1.0)
    clg_part_load_ratio.setMinimumCurveOutput(0.7)
    clg_part_load_ratio.setMaximumCurveOutput(1.0)

  end

  clg_coil.setTotalCoolingCapacityFunctionOfTemperatureCurve(clg_cap_f_of_temp) unless clg_cap_f_of_temp.nil?
  clg_coil.setTotalCoolingCapacityFunctionOfFlowFractionCurve(clg_cap_f_of_flow) unless clg_cap_f_of_flow.nil?
  clg_coil.setEnergyInputRatioFunctionOfTemperatureCurve(clg_energy_input_ratio_f_of_temp) unless clg_energy_input_ratio_f_of_temp.nil?
  clg_coil.setEnergyInputRatioFunctionOfFlowFractionCurve(clg_energy_input_ratio_f_of_flow) unless clg_energy_input_ratio_f_of_flow.nil?
  clg_coil.setPartLoadFractionCorrelationCurve(clg_part_load_ratio) unless clg_part_load_ratio.nil?

  return clg_coil
end
create_coil_cooling_dx_two_speed(model, air_loop_node: nil, name: '2spd DX Clg Coil', schedule: nil, type: nil) click to toggle source

Prototype CoilCoolingDXTwoSpeed object Enters in default curves for coil by type of coil

@param model [OpenStudio::Model::Model] OpenStudio model object @param air_loop_node [<OpenStudio::Model::Node>] the coil will be placed on this node of the air loop @param name [String] the name of the system, or nil in which case it will be defaulted @param schedule [String] name of the availability schedule, or [<OpenStudio::Model::Schedule>] Schedule object, or nil in which case default to always on @param type [String] the type of two speed DX coil to reference the correct curve set @return [OpenStudio::Model::CoilCoolingDXTwoSpeed] the DX cooling coil

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilCoolingDXTwoSpeed.rb, line 13
def create_coil_cooling_dx_two_speed(model,
                                     air_loop_node: nil,
                                     name: '2spd DX Clg Coil',
                                     schedule: nil,
                                     type: nil)

  clg_coil = OpenStudio::Model::CoilCoolingDXTwoSpeed.new(model)

  # add to air loop if specified
  clg_coil.addToNode(air_loop_node) unless air_loop_node.nil?

  # set coil name
  clg_coil.setName(name)

  # set coil availability schedule
  if schedule.nil?
    # default always on
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  elsif schedule.class == String
    coil_availability_schedule = model_add_schedule(model, schedule)

    if coil_availability_schedule.nil? && schedule == 'alwaysOffDiscreteSchedule'
      coil_availability_schedule = model.alwaysOffDiscreteSchedule
    elsif coil_availability_schedule.nil?
      coil_availability_schedule = model.alwaysOnDiscreteSchedule
    end
  elsif !schedule.to_Schedule.empty?
    coil_availability_schedule = schedule
  else
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  end
  clg_coil.setAvailabilitySchedule(coil_availability_schedule)

  clg_cap_f_of_temp = nil
  clg_cap_f_of_flow = nil
  clg_energy_input_ratio_f_of_temp = nil
  clg_energy_input_ratio_f_of_flow = nil
  clg_part_load_ratio = nil
  clg_cap_f_of_temp_low_spd = nil
  clg_energy_input_ratio_f_of_temp_low_spd = nil

  # curve sets
  if type == 'OS default'
    # use OS defaults
  elsif type == 'Residential Minisplit HP'
    # Performance curves
    # These coefficients are in SI units
    cool_cap_ft_coeffs_si = [0.7531983499655835, 0.003618193903031667, 0.0, 0.006574385031351544, -6.87181191015432e-05, 0.0]
    cool_eir_ft_coeffs_si = [-0.06376924779982301, -0.0013360593470367282, 1.413060577993827e-05, 0.019433076486584752, -4.91395947154321e-05, -4.909341249475308e-05]
    cool_cap_fflow_coeffs = [1, 0, 0]
    cool_eir_fflow_coeffs = [1, 0, 0]
    cool_plf_fplr_coeffs = [0.89, 0.11, 0]

    # Make the curves
    clg_cap_f_of_temp = create_curve_biquadratic(model, cool_cap_ft_coeffs_si, 'Cool-Cap-fT', 0, 100, 0, 100, nil, nil)
    clg_cap_f_of_flow = create_curve_quadratic(model, cool_cap_fflow_coeffs, 'Cool-Cap-fFF', 0, 2, 0, 2, is_dimensionless = true)
    clg_energy_input_ratio_f_of_temp = create_curve_biquadratic(model, cool_eir_ft_coeffs_si, 'Cool-EIR-fT', 0, 100, 0, 100, nil, nil)
    clg_energy_input_ratio_f_of_flow = create_curve_quadratic(model, cool_eir_fflow_coeffs, 'Cool-EIR-fFF', 0, 2, 0, 2, is_dimensionless = true)
    clg_part_load_ratio = create_curve_quadratic(model, cool_plf_fplr_coeffs, 'Cool-PLF-fPLR', 0, 1, 0, 1, is_dimensionless = true)
    clg_cap_f_of_temp_low_spd = create_curve_biquadratic(model, cool_cap_ft_coeffs_si, 'Cool-Cap-fT', 0, 100, 0, 100, nil, nil)
    clg_energy_input_ratio_f_of_temp_low_spd = create_curve_biquadratic(model, cool_eir_ft_coeffs_si, 'Cool-EIR-fT', 0, 100, 0, 100, nil, nil)
    clg_coil.setRatedLowSpeedSensibleHeatRatio(0.73)
    clg_coil.setCondenserType('AirCooled')
  else # default curve set, type == 'PSZ-AC' || 'Split AC' || 'PTAC'
    clg_cap_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_cap_f_of_temp.setCoefficient1Constant(0.42415)
    clg_cap_f_of_temp.setCoefficient2x(0.04426)
    clg_cap_f_of_temp.setCoefficient3xPOW2(-0.00042)
    clg_cap_f_of_temp.setCoefficient4y(0.00333)
    clg_cap_f_of_temp.setCoefficient5yPOW2(-0.00008)
    clg_cap_f_of_temp.setCoefficient6xTIMESY(-0.00021)
    clg_cap_f_of_temp.setMinimumValueofx(17.0)
    clg_cap_f_of_temp.setMaximumValueofx(22.0)
    clg_cap_f_of_temp.setMinimumValueofy(13.0)
    clg_cap_f_of_temp.setMaximumValueofy(46.0)

    clg_cap_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)
    clg_cap_f_of_flow.setCoefficient1Constant(0.77136)
    clg_cap_f_of_flow.setCoefficient2x(0.34053)
    clg_cap_f_of_flow.setCoefficient3xPOW2(-0.11088)
    clg_cap_f_of_flow.setMinimumValueofx(0.75918)
    clg_cap_f_of_flow.setMaximumValueofx(1.13877)

    clg_energy_input_ratio_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_energy_input_ratio_f_of_temp.setCoefficient1Constant(1.23649)
    clg_energy_input_ratio_f_of_temp.setCoefficient2x(-0.02431)
    clg_energy_input_ratio_f_of_temp.setCoefficient3xPOW2(0.00057)
    clg_energy_input_ratio_f_of_temp.setCoefficient4y(-0.01434)
    clg_energy_input_ratio_f_of_temp.setCoefficient5yPOW2(0.00063)
    clg_energy_input_ratio_f_of_temp.setCoefficient6xTIMESY(-0.00038)
    clg_energy_input_ratio_f_of_temp.setMinimumValueofx(17.0)
    clg_energy_input_ratio_f_of_temp.setMaximumValueofx(22.0)
    clg_energy_input_ratio_f_of_temp.setMinimumValueofy(13.0)
    clg_energy_input_ratio_f_of_temp.setMaximumValueofy(46.0)

    clg_energy_input_ratio_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)
    clg_energy_input_ratio_f_of_flow.setCoefficient1Constant(1.20550)
    clg_energy_input_ratio_f_of_flow.setCoefficient2x(-0.32953)
    clg_energy_input_ratio_f_of_flow.setCoefficient3xPOW2(0.12308)
    clg_energy_input_ratio_f_of_flow.setMinimumValueofx(0.75918)
    clg_energy_input_ratio_f_of_flow.setMaximumValueofx(1.13877)

    clg_part_load_ratio = OpenStudio::Model::CurveQuadratic.new(model)
    clg_part_load_ratio.setCoefficient1Constant(0.77100)
    clg_part_load_ratio.setCoefficient2x(0.22900)
    clg_part_load_ratio.setCoefficient3xPOW2(0.0)
    clg_part_load_ratio.setMinimumValueofx(0.0)
    clg_part_load_ratio.setMaximumValueofx(1.0)

    clg_cap_f_of_temp_low_spd = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_cap_f_of_temp_low_spd.setCoefficient1Constant(0.42415)
    clg_cap_f_of_temp_low_spd.setCoefficient2x(0.04426)
    clg_cap_f_of_temp_low_spd.setCoefficient3xPOW2(-0.00042)
    clg_cap_f_of_temp_low_spd.setCoefficient4y(0.00333)
    clg_cap_f_of_temp_low_spd.setCoefficient5yPOW2(-0.00008)
    clg_cap_f_of_temp_low_spd.setCoefficient6xTIMESY(-0.00021)
    clg_cap_f_of_temp_low_spd.setMinimumValueofx(17.0)
    clg_cap_f_of_temp_low_spd.setMaximumValueofx(22.0)
    clg_cap_f_of_temp_low_spd.setMinimumValueofy(13.0)
    clg_cap_f_of_temp_low_spd.setMaximumValueofy(46.0)

    clg_energy_input_ratio_f_of_temp_low_spd = OpenStudio::Model::CurveBiquadratic.new(model)
    clg_energy_input_ratio_f_of_temp_low_spd.setCoefficient1Constant(1.23649)
    clg_energy_input_ratio_f_of_temp_low_spd.setCoefficient2x(-0.02431)
    clg_energy_input_ratio_f_of_temp_low_spd.setCoefficient3xPOW2(0.00057)
    clg_energy_input_ratio_f_of_temp_low_spd.setCoefficient4y(-0.01434)
    clg_energy_input_ratio_f_of_temp_low_spd.setCoefficient5yPOW2(0.00063)
    clg_energy_input_ratio_f_of_temp_low_spd.setCoefficient6xTIMESY(-0.00038)
    clg_energy_input_ratio_f_of_temp_low_spd.setMinimumValueofx(17.0)
    clg_energy_input_ratio_f_of_temp_low_spd.setMaximumValueofx(22.0)
    clg_energy_input_ratio_f_of_temp_low_spd.setMinimumValueofy(13.0)
    clg_energy_input_ratio_f_of_temp_low_spd.setMaximumValueofy(46.0)

    clg_coil.setRatedLowSpeedSensibleHeatRatio(OpenStudio::OptionalDouble.new(0.69))
    clg_coil.setBasinHeaterCapacity(10)
    clg_coil.setBasinHeaterSetpointTemperature(2.0)
  end

  clg_coil.setTotalCoolingCapacityFunctionOfTemperatureCurve(clg_cap_f_of_temp) unless clg_cap_f_of_temp.nil?
  clg_coil.setTotalCoolingCapacityFunctionOfFlowFractionCurve(clg_cap_f_of_flow) unless clg_cap_f_of_flow.nil?
  clg_coil.setEnergyInputRatioFunctionOfTemperatureCurve(clg_energy_input_ratio_f_of_temp) unless clg_energy_input_ratio_f_of_temp.nil?
  clg_coil.setEnergyInputRatioFunctionOfFlowFractionCurve(clg_energy_input_ratio_f_of_flow) unless clg_energy_input_ratio_f_of_flow.nil?
  clg_coil.setPartLoadFractionCorrelationCurve(clg_part_load_ratio) unless clg_part_load_ratio.nil?
  clg_coil.setLowSpeedTotalCoolingCapacityFunctionOfTemperatureCurve(clg_cap_f_of_temp_low_spd) unless clg_cap_f_of_temp_low_spd.nil?
  clg_coil.setLowSpeedEnergyInputRatioFunctionOfTemperatureCurve(clg_energy_input_ratio_f_of_temp_low_spd) unless clg_energy_input_ratio_f_of_temp_low_spd.nil?

  return clg_coil
end
create_coil_cooling_water(model, chilled_water_loop, air_loop_node: nil, name: 'Clg Coil', schedule: nil, design_inlet_water_temperature: nil, design_inlet_air_temperature: nil, design_outlet_air_temperature: nil) click to toggle source

Prototype CoilCoolingWater object

@param model [OpenStudio::Model::Model] OpenStudio model object @param chilled_water_loop [<OpenStudio::Model::PlantLoop>] the coil will be placed on the demand side of this plant loop @param air_loop_node [<OpenStudio::Model::Node>] the coil will be placed on this node of the air loop @param name [String] the name of the coil, or nil in which case it will be defaulted @param schedule [String] name of the availability schedule, or [<OpenStudio::Model::Schedule>] Schedule object, or nil in which case default to always on @param design_inlet_water_temperature [Double] design inlet water temperature in degrees Celsius, default is nil @param design_inlet_air_temperature [Double] design inlet air temperature in degrees Celsius, default is nil @param design_outlet_air_temperature [Double] design outlet air temperature in degrees Celsius, default is nil @return [OpenStudio::Model::CoilCoolingWater] the cooling coil

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilCoolingWater.rb, line 15
def create_coil_cooling_water(model,
                              chilled_water_loop,
                              air_loop_node: nil,
                              name: 'Clg Coil',
                              schedule: nil,
                              design_inlet_water_temperature: nil,
                              design_inlet_air_temperature: nil,
                              design_outlet_air_temperature: nil)

  clg_coil = OpenStudio::Model::CoilCoolingWater.new(model)

  # add to chilled water loop
  chilled_water_loop.addDemandBranchForComponent(clg_coil)

  # add to air loop if specified
  clg_coil.addToNode(air_loop_node) unless air_loop_node.nil?

  # set coil name
  if name.nil?
    clg_coil.setName('Clg Coil')
  else
    clg_coil.setName(name)
  end

  # set coil availability schedule
  if schedule.nil?
    # default always on
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  elsif schedule.class == String
    coil_availability_schedule = model_add_schedule(model, schedule)

    if coil_availability_schedule.nil? && schedule == 'alwaysOffDiscreteSchedule'
      coil_availability_schedule = model.alwaysOffDiscreteSchedule
    elsif coil_availability_schedule.nil?
      coil_availability_schedule = model.alwaysOnDiscreteSchedule
    end
  elsif !schedule.to_Schedule.empty?
    coil_availability_schedule = schedule
  else
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  end
  clg_coil.setAvailabilitySchedule(coil_availability_schedule)

  # rated temperatures
  if design_inlet_water_temperature.nil?
    clg_coil.autosizeDesignInletWaterTemperature
  else
    clg_coil.setDesignInletWaterTemperature(design_inlet_water_temperature)
  end
  clg_coil.setDesignInletAirTemperature(design_inlet_air_temperature) unless design_inlet_air_temperature.nil?
  clg_coil.setDesignOutletAirTemperature(design_outlet_air_temperature) unless design_outlet_air_temperature.nil?

  # defaults
  clg_coil.setHeatExchangerConfiguration('CrossFlow')

  # coil controller properties
  # @note These inputs will get overwritten if addToNode or addDemandBranchForComponent is called on the htg_coil object after this
  clg_coil_controller = clg_coil.controllerWaterCoil.get
  clg_coil_controller.setName("#{clg_coil.name} Controller")
  clg_coil_controller.setAction('Reverse')
  clg_coil_controller.setMinimumActuatedFlow(0.0)

  return clg_coil
end
create_coil_cooling_water_to_air_heat_pump_equation_fit(model, plant_loop, air_loop_node: nil, name: 'Water-to-Air HP Clg Coil', type: nil, cop: 3.4) click to toggle source

Prototype CoilCoolingWaterToAirHeatPumpEquationFit object Enters in default curves for coil by type of coil

@param model [OpenStudio::Model::Model] OpenStudio model object @param plant_loop [<OpenStudio::Model::PlantLoop>] the coil will be placed on the demand side of this plant loop @param air_loop_node [<OpenStudio::Model::Node>] the coil will be placed on this node of the air loop @param name [String] the name of the system, or nil in which case it will be defaulted @param type [String] the type of coil to reference the correct curve set @param cop [Double] rated cooling coefficient of performance @return [OpenStudio::Model::CoilCoolingWaterToAirHeatPumpEquationFit] the cooling coil

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilCoolingWaterToAirHeatPumpEquationFit.rb, line 14
def create_coil_cooling_water_to_air_heat_pump_equation_fit(model,
                                                            plant_loop,
                                                            air_loop_node: nil,
                                                            name: 'Water-to-Air HP Clg Coil',
                                                            type: nil,
                                                            cop: 3.4)

  clg_coil = OpenStudio::Model::CoilCoolingWaterToAirHeatPumpEquationFit.new(model)

  # add to air loop if specified
  clg_coil.addToNode(air_loop_node) unless air_loop_node.nil?

  # set coil name
  clg_coil.setName(name)

  # add to plant loop
  if plant_loop.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'No plant loop supplied for cooling coil')
    return false
  end
  plant_loop.addDemandBranchForComponent(clg_coil)

  # set coil cop
  if cop.nil?
    clg_coil.setRatedCoolingCoefficientofPerformance(3.4)
  else
    clg_coil.setRatedCoolingCoefficientofPerformance(cop)
  end

  # curve sets
  if type == 'OS default'
    # use OS default curves
  else # default curve set
    if model.version < OpenStudio::VersionString.new('3.2.0')
      clg_coil.setTotalCoolingCapacityCoefficient1(-4.30266987344639)
      clg_coil.setTotalCoolingCapacityCoefficient2(7.18536990534372)
      clg_coil.setTotalCoolingCapacityCoefficient3(-2.23946714486189)
      clg_coil.setTotalCoolingCapacityCoefficient4(0.139995928440879)
      clg_coil.setTotalCoolingCapacityCoefficient5(0.102660179888915)
      clg_coil.setSensibleCoolingCapacityCoefficient1(6.0019444814887)
      clg_coil.setSensibleCoolingCapacityCoefficient2(22.6300677244073)
      clg_coil.setSensibleCoolingCapacityCoefficient3(-26.7960783730934)
      clg_coil.setSensibleCoolingCapacityCoefficient4(-1.72374720346819)
      clg_coil.setSensibleCoolingCapacityCoefficient5(0.490644802367817)
      clg_coil.setSensibleCoolingCapacityCoefficient6(0.0693119353468141)
      clg_coil.setCoolingPowerConsumptionCoefficient1(-5.67775976415698)
      clg_coil.setCoolingPowerConsumptionCoefficient2(0.438988156976704)
      clg_coil.setCoolingPowerConsumptionCoefficient3(5.845277342193)
      clg_coil.setCoolingPowerConsumptionCoefficient4(0.141605667000125)
      clg_coil.setCoolingPowerConsumptionCoefficient5(-0.168727936032429)
    else
      if model.getCurveByName('Water to Air Heat Pump Total Cooling Capacity Curve').is_initialized
        total_cooling_capacity_curve = model.getCurveByName('Water to Air Heat Pump Total Cooling Capacity Curve').get
        total_cooling_capacity_curve = total_cooling_capacity_curve.to_CurveQuadLinear.get
      else
        total_cooling_capacity_curve = OpenStudio::Model::CurveQuadLinear.new(model)
        total_cooling_capacity_curve.setName('Water to Air Heat Pump Total Cooling Capacity Curve')
        total_cooling_capacity_curve.setCoefficient1Constant(-4.30266987344639)
        total_cooling_capacity_curve.setCoefficient2w(7.18536990534372)
        total_cooling_capacity_curve.setCoefficient3x(-2.23946714486189)
        total_cooling_capacity_curve.setCoefficient4y(0.139995928440879)
        total_cooling_capacity_curve.setCoefficient5z(0.102660179888915)
        total_cooling_capacity_curve.setMinimumValueofw(-100)
        total_cooling_capacity_curve.setMaximumValueofw(100)
        total_cooling_capacity_curve.setMinimumValueofx(-100)
        total_cooling_capacity_curve.setMaximumValueofx(100)
        total_cooling_capacity_curve.setMinimumValueofy(0)
        total_cooling_capacity_curve.setMaximumValueofy(100)
        total_cooling_capacity_curve.setMinimumValueofz(0)
        total_cooling_capacity_curve.setMaximumValueofz(100)
      end
      clg_coil.setTotalCoolingCapacityCurve(total_cooling_capacity_curve)

      if model.getCurveByName('Water to Air Heat Pump Sensible Cooling Capacity Curve').is_initialized
        sensible_cooling_capacity_curve = model.getCurveByName('Water to Air Heat Pump Sensible Cooling Capacity Curve').get
        sensible_cooling_capacity_curve = sensible_cooling_capacity_curve.to_CurveQuintLinear.get
      else
        sensible_cooling_capacity_curve = OpenStudio::Model::CurveQuintLinear.new(model)
        sensible_cooling_capacity_curve.setName('Water to Air Heat Pump Sensible Cooling Capacity Curve')
        sensible_cooling_capacity_curve.setCoefficient1Constant(6.0019444814887)
        sensible_cooling_capacity_curve.setCoefficient2v(22.6300677244073)
        sensible_cooling_capacity_curve.setCoefficient3w(-26.7960783730934)
        sensible_cooling_capacity_curve.setCoefficient4x(-1.72374720346819)
        sensible_cooling_capacity_curve.setCoefficient5y(0.490644802367817)
        sensible_cooling_capacity_curve.setCoefficient6z(0.0693119353468141)
        sensible_cooling_capacity_curve.setMinimumValueofw(-100)
        sensible_cooling_capacity_curve.setMaximumValueofw(100)
        sensible_cooling_capacity_curve.setMinimumValueofx(-100)
        sensible_cooling_capacity_curve.setMaximumValueofx(100)
        sensible_cooling_capacity_curve.setMinimumValueofy(0)
        sensible_cooling_capacity_curve.setMaximumValueofy(100)
        sensible_cooling_capacity_curve.setMinimumValueofz(0)
        sensible_cooling_capacity_curve.setMaximumValueofz(100)
      end
      clg_coil.setSensibleCoolingCapacityCurve(sensible_cooling_capacity_curve)

      if model.getCurveByName('Water to Air Heat Pump Cooling Power Consumption Curve').is_initialized
        cooling_power_consumption_curve = model.getCurveByName('Water to Air Heat Pump Cooling Power Consumption Curve').get
        cooling_power_consumption_curve = cooling_power_consumption_curve.to_CurveQuadLinear.get
      else
        cooling_power_consumption_curve = OpenStudio::Model::CurveQuadLinear.new(model)
        cooling_power_consumption_curve.setName('Water to Air Heat Pump Cooling Power Consumption Curve')
        cooling_power_consumption_curve.setCoefficient1Constant(-5.67775976415698)
        cooling_power_consumption_curve.setCoefficient2w(0.438988156976704)
        cooling_power_consumption_curve.setCoefficient3x(5.845277342193)
        cooling_power_consumption_curve.setCoefficient4y(0.141605667000125)
        cooling_power_consumption_curve.setCoefficient5z(-0.168727936032429)
        cooling_power_consumption_curve.setMinimumValueofw(-100)
        cooling_power_consumption_curve.setMaximumValueofw(100)
        cooling_power_consumption_curve.setMinimumValueofx(-100)
        cooling_power_consumption_curve.setMaximumValueofx(100)
        cooling_power_consumption_curve.setMinimumValueofy(0)
        cooling_power_consumption_curve.setMaximumValueofy(100)
        cooling_power_consumption_curve.setMinimumValueofz(0)
        cooling_power_consumption_curve.setMaximumValueofz(100)
      end
      clg_coil.setCoolingPowerConsumptionCurve(cooling_power_consumption_curve)
    end

    # part load fraction correlation curve added as a required curve in OS v3.7.0
    if model.version > OpenStudio::VersionString.new('3.6.1')
      if model.getCurveByName('Water to Air Heat Pump Part Load Fraction Correlation Curve').is_initialized
        part_load_correlation_curve = model.getCurveByName('Water to Air Heat Pump Part Load Fraction Correlation Curve').get
        part_load_correlation_curve = part_load_correlation_curve.to_CurveLinear.get
      else
        part_load_correlation_curve = OpenStudio::Model::CurveLinear.new(model)
        part_load_correlation_curve.setName('Water to Air Heat Pump Part Load Fraction Correlation Curve')
        part_load_correlation_curve.setCoefficient1Constant(0.833746458696111)
        part_load_correlation_curve.setCoefficient2x(0.166253541303889)
        part_load_correlation_curve.setMinimumValueofx(0)
        part_load_correlation_curve.setMaximumValueofx(1)
        part_load_correlation_curve.setMinimumCurveOutput(0)
        part_load_correlation_curve.setMaximumCurveOutput(1)
      end
      clg_coil.setPartLoadFractionCorrelationCurve(part_load_correlation_curve)
    end
  end

  return clg_coil
end
create_coil_heating_dx_single_speed(model, air_loop_node: nil, name: '1spd DX Htg Coil', schedule: nil, type: nil, cop: 3.3, defrost_strategy: 'ReverseCycle') click to toggle source

Prototype CoilHeatingDXSingleSpeed object Enters in default curves for coil by type of coil

@param model [OpenStudio::Model::Model] OpenStudio model object @param air_loop_node [<OpenStudio::Model::Node>] the coil will be placed on this node of the air loop @param name [String] the name of the system, or nil in which case it will be defaulted @param schedule [String] name of the availability schedule, or [<OpenStudio::Model::Schedule>] Schedule object, or nil in which case default to always on @param type [String] the type of single speed DX coil to reference the correct curve set @param cop [Double] rated heating coefficient of performance @param defrost_strategy [String] type of defrost strategy. options are reverse-cycle or resistive @return [OpenStudio::Model::CoilHeatingDXSingleSpeed] the DX heating coil

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilHeatingDXSingleSpeed.rb, line 15
def create_coil_heating_dx_single_speed(model,
                                        air_loop_node: nil,
                                        name: '1spd DX Htg Coil',
                                        schedule: nil,
                                        type: nil,
                                        cop: 3.3,
                                        defrost_strategy: 'ReverseCycle')

  htg_coil = OpenStudio::Model::CoilHeatingDXSingleSpeed.new(model)

  # add to air loop if specified
  htg_coil.addToNode(air_loop_node) unless air_loop_node.nil?

  # set coil name
  htg_coil.setName(name)

  # set coil availability schedule
  if schedule.nil?
    # default always on
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  elsif schedule.class == String
    coil_availability_schedule = model_add_schedule(model, schedule)

    if coil_availability_schedule.nil? && schedule == 'alwaysOffDiscreteSchedule'
      coil_availability_schedule = model.alwaysOffDiscreteSchedule
    elsif coil_availability_schedule.nil?
      coil_availability_schedule = model.alwaysOnDiscreteSchedule
    end
  elsif !schedule.to_Schedule.empty?
    coil_availability_schedule = schedule
  else
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  end
  htg_coil.setAvailabilitySchedule(coil_availability_schedule)

  # set coil cop
  if cop.nil?
    htg_coil.setRatedCOP(3.3)
  else
    htg_coil.setRatedCOP(cop)
  end

  htg_cap_f_of_temp = nil
  htg_cap_f_of_flow = nil
  htg_energy_input_ratio_f_of_temp = nil
  htg_energy_input_ratio_f_of_flow = nil
  htg_part_load_fraction = nil
  def_eir_f_of_temp = nil

  # curve sets
  if type == 'OS default'
    # use OS defaults
  elsif type == 'Residential Central Air Source HP'
    # Performance curves
    # These coefficients are in IP UNITS
    heat_cap_ft_coeffs_ip = [0.566333415, -0.000744164, -0.0000103, 0.009414634, 0.0000506, -0.00000675]
    heat_eir_ft_coeffs_ip = [0.718398423, 0.003498178, 0.000142202, -0.005724331, 0.00014085, -0.000215321]
    heat_cap_fflow_coeffs = [0.694045465, 0.474207981, -0.168253446]
    heat_eir_fflow_coeffs = [2.185418751, -1.942827919, 0.757409168]
    heat_plf_fplr_coeffs = [0.8, 0.2, 0]
    defrost_eir_coeffs = [0.1528, 0, 0, 0, 0, 0]

    # Convert coefficients from IP to SI
    heat_cap_ft_coeffs_si = convert_curve_biquadratic(heat_cap_ft_coeffs_ip)
    heat_eir_ft_coeffs_si = convert_curve_biquadratic(heat_eir_ft_coeffs_ip)

    htg_cap_f_of_temp = create_curve_biquadratic(model, heat_cap_ft_coeffs_si, 'Heat-Cap-fT', 0, 100, 0, 100, nil, nil)
    htg_cap_f_of_flow = create_curve_quadratic(model, heat_cap_fflow_coeffs, 'Heat-Cap-fFF', 0, 2, 0, 2, is_dimensionless = true)
    htg_energy_input_ratio_f_of_temp = create_curve_biquadratic(model, heat_eir_ft_coeffs_si, 'Heat-EIR-fT', 0, 100, 0, 100, nil, nil)
    htg_energy_input_ratio_f_of_flow = create_curve_quadratic(model, heat_eir_fflow_coeffs, 'Heat-EIR-fFF', 0, 2, 0, 2, is_dimensionless = true)
    htg_part_load_fraction = create_curve_quadratic(model, heat_plf_fplr_coeffs, 'Heat-PLF-fPLR', 0, 1, 0, 1, is_dimensionless = true)

    # Heating defrost curve for reverse cycle
    def_eir_f_of_temp = create_curve_biquadratic(model, defrost_eir_coeffs, 'DefrostEIR', -100, 100, -100, 100, nil, nil)
  elsif type == 'Residential Minisplit HP'
    # Performance curves
    # These coefficients are in SI UNITS
    heat_cap_ft_coeffs_si = [1.14715889038462, -0.010386676170938, 0, 0.00865384615384615, 0, 0]
    heat_eir_ft_coeffs_si = [0.9999941697687026, 0.004684593830254383, 5.901286675833333e-05, -0.0028624467783091973, 1.3041120194135802e-05, -0.00016172918478765433]
    heat_cap_fflow_coeffs = [1, 0, 0]
    heat_eir_fflow_coeffs = [1, 0, 0]
    heat_plf_fplr_coeffs = [0.89, 0.11, 0]
    defrost_eir_coeffs = [0.1528, 0, 0, 0, 0, 0]

    htg_cap_f_of_temp = create_curve_biquadratic(model, heat_cap_ft_coeffs_si, 'Heat-Cap-fT', -100, 100, -100, 100, nil, nil)
    htg_cap_f_of_flow = create_curve_quadratic(model, heat_cap_fflow_coeffs, 'Heat-Cap-fFF', 0, 2, 0, 2, is_dimensionless = true)
    htg_energy_input_ratio_f_of_temp = create_curve_biquadratic(model, heat_eir_ft_coeffs_si, 'Heat-EIR-fT', -100, 100, -100, 100, nil, nil)
    htg_energy_input_ratio_f_of_flow = create_curve_quadratic(model, heat_eir_fflow_coeffs, 'Heat-EIR-fFF', 0, 2, 0, 2, is_dimensionless = true)
    htg_part_load_fraction = create_curve_quadratic(model, heat_plf_fplr_coeffs, 'Heat-PLF-fPLR', 0, 1, 0.6, 1, is_dimensionless = true)

    # Heating defrost curve for reverse cycle
    def_eir_f_of_temp = create_curve_biquadratic(model, defrost_eir_coeffs, 'Defrost EIR', -100, 100, -100, 100, nil, nil)
  else # default curve set
    htg_cap_f_of_temp = OpenStudio::Model::CurveCubic.new(model)
    htg_cap_f_of_temp.setName("#{htg_coil.name} Htg Cap Func of Temp Curve")
    htg_cap_f_of_temp.setCoefficient1Constant(0.758746)
    htg_cap_f_of_temp.setCoefficient2x(0.027626)
    htg_cap_f_of_temp.setCoefficient3xPOW2(0.000148716)
    htg_cap_f_of_temp.setCoefficient4xPOW3(0.0000034992)
    htg_cap_f_of_temp.setMinimumValueofx(-20.0)
    htg_cap_f_of_temp.setMaximumValueofx(20.0)

    htg_cap_f_of_flow = OpenStudio::Model::CurveCubic.new(model)
    htg_cap_f_of_flow.setName("#{htg_coil.name} Htg Cap Func of Flow Frac Curve")
    htg_cap_f_of_flow.setCoefficient1Constant(0.84)
    htg_cap_f_of_flow.setCoefficient2x(0.16)
    htg_cap_f_of_flow.setCoefficient3xPOW2(0.0)
    htg_cap_f_of_flow.setCoefficient4xPOW3(0.0)
    htg_cap_f_of_flow.setMinimumValueofx(0.5)
    htg_cap_f_of_flow.setMaximumValueofx(1.5)

    htg_energy_input_ratio_f_of_temp = OpenStudio::Model::CurveCubic.new(model)
    htg_energy_input_ratio_f_of_temp.setName("#{htg_coil.name} EIR Func of Temp Curve")
    htg_energy_input_ratio_f_of_temp.setCoefficient1Constant(1.19248)
    htg_energy_input_ratio_f_of_temp.setCoefficient2x(-0.0300438)
    htg_energy_input_ratio_f_of_temp.setCoefficient3xPOW2(0.00103745)
    htg_energy_input_ratio_f_of_temp.setCoefficient4xPOW3(-0.000023328)
    htg_energy_input_ratio_f_of_temp.setMinimumValueofx(-20.0)
    htg_energy_input_ratio_f_of_temp.setMaximumValueofx(20.0)

    htg_energy_input_ratio_f_of_flow = OpenStudio::Model::CurveQuadratic.new(model)
    htg_energy_input_ratio_f_of_flow.setName("#{htg_coil.name} EIR Func of Flow Frac Curve")
    htg_energy_input_ratio_f_of_flow.setCoefficient1Constant(1.3824)
    htg_energy_input_ratio_f_of_flow.setCoefficient2x(-0.4336)
    htg_energy_input_ratio_f_of_flow.setCoefficient3xPOW2(0.0512)
    htg_energy_input_ratio_f_of_flow.setMinimumValueofx(0.0)
    htg_energy_input_ratio_f_of_flow.setMaximumValueofx(1.0)

    htg_part_load_fraction = OpenStudio::Model::CurveQuadratic.new(model)
    htg_part_load_fraction.setName("#{htg_coil.name} PLR Correlation Curve")
    htg_part_load_fraction.setCoefficient1Constant(0.85)
    htg_part_load_fraction.setCoefficient2x(0.15)
    htg_part_load_fraction.setCoefficient3xPOW2(0.0)
    htg_part_load_fraction.setMinimumValueofx(0.0)
    htg_part_load_fraction.setMaximumValueofx(1.0)

    unless defrost_strategy == 'Resistive'
      def_eir_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
      def_eir_f_of_temp.setName("#{htg_coil.name} Defrost EIR Func of Temp Curve")
      def_eir_f_of_temp.setCoefficient1Constant(0.297145)
      def_eir_f_of_temp.setCoefficient2x(0.0430933)
      def_eir_f_of_temp.setCoefficient3xPOW2(-0.000748766)
      def_eir_f_of_temp.setCoefficient4y(0.00597727)
      def_eir_f_of_temp.setCoefficient5yPOW2(0.000482112)
      def_eir_f_of_temp.setCoefficient6xTIMESY(-0.000956448)
      def_eir_f_of_temp.setMinimumValueofx(-23.33333)
      def_eir_f_of_temp.setMaximumValueofx(29.44444)
      def_eir_f_of_temp.setMinimumValueofy(-23.33333)
      def_eir_f_of_temp.setMaximumValueofy(29.44444)
    end
  end

  if type == 'PSZ-AC'
    htg_coil.setMinimumOutdoorDryBulbTemperatureforCompressorOperation(-12.2)
    htg_coil.setMaximumOutdoorDryBulbTemperatureforDefrostOperation(1.67)
    htg_coil.setCrankcaseHeaterCapacity(50.0)
    htg_coil.setMaximumOutdoorDryBulbTemperatureforCrankcaseHeaterOperation(4.4)
    htg_coil.setDefrostControl('OnDemand')

    def_eir_f_of_temp = OpenStudio::Model::CurveBiquadratic.new(model)
    def_eir_f_of_temp.setName("#{htg_coil.name} Defrost EIR Func of Temp Curve")
    def_eir_f_of_temp.setCoefficient1Constant(0.297145)
    def_eir_f_of_temp.setCoefficient2x(0.0430933)
    def_eir_f_of_temp.setCoefficient3xPOW2(-0.000748766)
    def_eir_f_of_temp.setCoefficient4y(0.00597727)
    def_eir_f_of_temp.setCoefficient5yPOW2(0.000482112)
    def_eir_f_of_temp.setCoefficient6xTIMESY(-0.000956448)
    def_eir_f_of_temp.setMinimumValueofx(-23.33333)
    def_eir_f_of_temp.setMaximumValueofx(29.44444)
    def_eir_f_of_temp.setMinimumValueofy(-23.33333)
    def_eir_f_of_temp.setMaximumValueofy(29.44444)
  end

  htg_coil.setTotalHeatingCapacityFunctionofTemperatureCurve(htg_cap_f_of_temp) unless htg_cap_f_of_temp.nil?
  htg_coil.setTotalHeatingCapacityFunctionofFlowFractionCurve(htg_cap_f_of_flow) unless htg_cap_f_of_flow.nil?
  htg_coil.setEnergyInputRatioFunctionofTemperatureCurve(htg_energy_input_ratio_f_of_temp) unless htg_energy_input_ratio_f_of_temp.nil?
  htg_coil.setEnergyInputRatioFunctionofFlowFractionCurve(htg_energy_input_ratio_f_of_flow) unless htg_energy_input_ratio_f_of_flow.nil?
  htg_coil.setPartLoadFractionCorrelationCurve(htg_part_load_fraction) unless htg_part_load_fraction.nil?
  htg_coil.setDefrostEnergyInputRatioFunctionofTemperatureCurve(def_eir_f_of_temp) unless def_eir_f_of_temp.nil?
  htg_coil.setDefrostStrategy(defrost_strategy)
  htg_coil.setDefrostControl('OnDemand')

  return htg_coil
end
create_coil_heating_electric(model, air_loop_node: nil, name: 'Electric Htg Coil', schedule: nil, nominal_capacity: nil, efficiency: 1.0) click to toggle source

Prototype CoilHeatingElectric object

@param model [OpenStudio::Model::Model] OpenStudio model object @param air_loop_node [<OpenStudio::Model::Node>] the coil will be placed on this node of the air loop @param name [String] the name of the system, or nil in which case it will be defaulted @param schedule [String] name of the availability schedule, or [<OpenStudio::Model::Schedule>] Schedule object, or nil in which case default to always on @param nominal_capacity [Double] rated nominal capacity @param efficiency [Double] rated heating efficiency @return [OpenStudio::Model::CoilHeatingElectric] the electric heating coil

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilHeatingElectric.rb, line 13
def create_coil_heating_electric(model,
                                 air_loop_node: nil,
                                 name: 'Electric Htg Coil',
                                 schedule: nil,
                                 nominal_capacity: nil,
                                 efficiency: 1.0)

  htg_coil = OpenStudio::Model::CoilHeatingElectric.new(model)

  # add to air loop if specified
  htg_coil.addToNode(air_loop_node) unless air_loop_node.nil?

  # set coil name
  htg_coil.setName(name)

  # set coil availability schedule
  if schedule.nil?
    # default always on
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  elsif schedule.class == String
    coil_availability_schedule = model_add_schedule(model, schedule)

    if coil_availability_schedule.nil? && schedule == 'alwaysOffDiscreteSchedule'
      coil_availability_schedule = model.alwaysOffDiscreteSchedule
    elsif coil_availability_schedule.nil?
      coil_availability_schedule = model.alwaysOnDiscreteSchedule
    end
  elsif !schedule.to_Schedule.empty?
    coil_availability_schedule = schedule
  else
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  end
  htg_coil.setAvailabilitySchedule(coil_availability_schedule)

  # set capacity
  htg_coil.setNominalCapacity(nominal_capacity) unless nominal_capacity.nil?

  # set efficiency
  htg_coil.setEfficiency(efficiency) unless efficiency.nil?

  return htg_coil
end
create_coil_heating_gas(model, air_loop_node: nil, name: 'Gas Htg Coil', schedule: nil, nominal_capacity: nil, efficiency: 0.80) click to toggle source

Prototype CoilHeatingGas object

@param model [OpenStudio::Model::Model] OpenStudio model object @param air_loop_node [<OpenStudio::Model::Node>] the coil will be placed on this node of the air loop @param name [String] the name of the system, or nil in which case it will be defaulted @param schedule [String] name of the availability schedule, or [<OpenStudio::Model::Schedule>] Schedule object, or nil in which case default to always on @param nominal_capacity [Double] rated nominal capacity @param efficiency [Double] rated heating efficiency @return [OpenStudio::Model::CoilHeatingGas] the gas heating coil

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilHeatingGas.rb, line 13
def create_coil_heating_gas(model,
                            air_loop_node: nil,
                            name: 'Gas Htg Coil',
                            schedule: nil,
                            nominal_capacity: nil,
                            efficiency: 0.80)

  htg_coil = OpenStudio::Model::CoilHeatingGas.new(model)

  # add to air loop if specified
  htg_coil.addToNode(air_loop_node) unless air_loop_node.nil?

  # set coil name
  htg_coil.setName(name)

  # set coil availability schedule
  if schedule.nil?
    # default always on
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  elsif schedule.class == String
    coil_availability_schedule = model_add_schedule(model, schedule)

    if coil_availability_schedule.nil? && schedule == 'alwaysOffDiscreteSchedule'
      coil_availability_schedule = model.alwaysOffDiscreteSchedule
    elsif coil_availability_schedule.nil?
      coil_availability_schedule = model.alwaysOnDiscreteSchedule
    end
  elsif !schedule.to_Schedule.empty?
    coil_availability_schedule = schedule
  else
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  end
  htg_coil.setAvailabilitySchedule(coil_availability_schedule)

  # set capacity
  htg_coil.setNominalCapacity(nominal_capacity) unless nominal_capacity.nil?

  # set efficiency
  htg_coil.setGasBurnerEfficiency(efficiency)

  # defaults
  if model.version < OpenStudio::VersionString.new('3.7.0')
    htg_coil.setParasiticElectricLoad(0.0)
    htg_coil.setParasiticGasLoad(0.0)
  else
    htg_coil.setOnCycleParasiticElectricLoad(0.0)
    htg_coil.setOffCycleParasiticGasLoad(0.0)
  end

  return htg_coil
end
create_coil_heating_water(model, hot_water_loop, air_loop_node: nil, name: 'Htg Coil', schedule: nil, rated_inlet_water_temperature: nil, rated_outlet_water_temperature: nil, rated_inlet_air_temperature: 16.6, rated_outlet_air_temperature: 32.2, controller_convergence_tolerance: 0.1) click to toggle source

Prototype CoilHeatingWater object

@param model [OpenStudio::Model::Model] OpenStudio model object @param hot_water_loop [<OpenStudio::Model::PlantLoop>] the coil will be placed on the demand side of this plant loop @param air_loop_node [<OpenStudio::Model::Node>] the coil will be placed on this node of the air loop @param name [String] the name of the coil, or nil in which case it will be defaulted @param schedule [String] name of the availability schedule, or [<OpenStudio::Model::Schedule>] Schedule object, or nil in which case default to always on @param rated_inlet_water_temperature [Double] rated inlet water temperature in degrees Celsius, default is hot water loop design exit temperature @param rated_outlet_water_temperature [Double] rated outlet water temperature in degrees Celsius, default is hot water loop design return temperature @param rated_inlet_air_temperature [Double] rated inlet air temperature in degrees Celsius, default is 16.6 (62F) @param rated_outlet_air_temperature [Double] rated outlet air temperature in degrees Celsius, default is 32.2 (90F) @param controller_convergence_tolerance [Double] controller convergence tolerance @return [OpenStudio::Model::CoilHeatingWater] the heating coil

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilHeatingWater.rb, line 17
def create_coil_heating_water(model,
                              hot_water_loop,
                              air_loop_node: nil,
                              name: 'Htg Coil',
                              schedule: nil,
                              rated_inlet_water_temperature: nil,
                              rated_outlet_water_temperature: nil,
                              rated_inlet_air_temperature: 16.6,
                              rated_outlet_air_temperature: 32.2,
                              controller_convergence_tolerance: 0.1)

  htg_coil = OpenStudio::Model::CoilHeatingWater.new(model)

  # add to hot water loop
  hot_water_loop.addDemandBranchForComponent(htg_coil)

  # add to air loop if specified
  htg_coil.addToNode(air_loop_node) unless air_loop_node.nil?

  # set coil name
  if name.nil?
    htg_coil.setName('Htg Coil')
  else
    htg_coil.setName(name)
  end

  # set coil availability schedule
  if schedule.nil?
    # default always on
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  elsif schedule.class == String
    coil_availability_schedule = model_add_schedule(model, schedule)

    if coil_availability_schedule.nil? && schedule == 'alwaysOffDiscreteSchedule'
      coil_availability_schedule = model.alwaysOffDiscreteSchedule
    elsif coil_availability_schedule.nil?
      coil_availability_schedule = model.alwaysOnDiscreteSchedule
    end
  elsif !schedule.to_Schedule.empty?
    coil_availability_schedule = schedule
  else
    coil_availability_schedule = model.alwaysOnDiscreteSchedule
  end
  htg_coil.setAvailabilitySchedule(coil_availability_schedule)

  # rated water temperatures, use hot water loop temperatures if defined
  if rated_inlet_water_temperature.nil?
    rated_inlet_water_temperature = hot_water_loop.sizingPlant.designLoopExitTemperature
    htg_coil.setRatedInletWaterTemperature(rated_inlet_water_temperature)
  else
    htg_coil.setRatedInletWaterTemperature(rated_inlet_water_temperature)
  end
  if rated_outlet_water_temperature.nil?
    rated_outlet_water_temperature = rated_inlet_water_temperature - hot_water_loop.sizingPlant.loopDesignTemperatureDifference
    htg_coil.setRatedOutletWaterTemperature(rated_outlet_water_temperature)
  else
    htg_coil.setRatedOutletWaterTemperature(rated_outlet_water_temperature)
  end

  # rated air temperatures
  if rated_inlet_air_temperature.nil?
    htg_coil.setRatedInletAirTemperature(16.6)
  else
    htg_coil.setRatedInletAirTemperature(rated_inlet_air_temperature)
  end
  if rated_outlet_air_temperature.nil?
    htg_coil.setRatedOutletAirTemperature(32.2)
  else
    htg_coil.setRatedOutletAirTemperature(rated_outlet_air_temperature)
  end

  # coil controller properties
  # @note These inputs will get overwritten if addToNode or addDemandBranchForComponent is called on the htg_coil object after this
  htg_coil_controller = htg_coil.controllerWaterCoil.get
  htg_coil_controller.setName("#{htg_coil.name} Controller")
  htg_coil_controller.setMinimumActuatedFlow(0.0)
  htg_coil_controller.setControllerConvergenceTolerance(controller_convergence_tolerance) unless controller_convergence_tolerance.nil?

  return htg_coil
end
create_coil_heating_water_to_air_heat_pump_equation_fit(model, plant_loop, air_loop_node: nil, name: 'Water-to-Air HP Htg Coil', type: nil, cop: 4.2) click to toggle source

Prototype CoilHeatingWaterToAirHeatPumpEquationFit object Enters in default curves for coil by type of coil

@param model [OpenStudio::Model::Model] OpenStudio model object @param plant_loop [<OpenStudio::Model::PlantLoop>] the coil will be placed on the demand side of this plant loop @param air_loop_node [<OpenStudio::Model::Node>] the coil will be placed on this node of the air loop @param name [String] the name of the system, or nil in which case it will be defaulted @param type [String] the type of coil to reference the correct curve set @param cop [Double] rated heating coefficient of performance @return [OpenStudio::Model::CoilHeatingWaterToAirHeatPumpEquationFit] the heating coil

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoilHeatingWaterToAirHeatPumpEquationFit.rb, line 14
def create_coil_heating_water_to_air_heat_pump_equation_fit(model,
                                                            plant_loop,
                                                            air_loop_node: nil,
                                                            name: 'Water-to-Air HP Htg Coil',
                                                            type: nil,
                                                            cop: 4.2)

  htg_coil = OpenStudio::Model::CoilHeatingWaterToAirHeatPumpEquationFit.new(model)

  # add to air loop if specified
  htg_coil.addToNode(air_loop_node) unless air_loop_node.nil?

  # set coil name
  htg_coil.setName(name)

  # add to plant loop
  if plant_loop.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'No plant loop supplied for heating coil')
    return false
  end
  plant_loop.addDemandBranchForComponent(htg_coil)

  # set coil cop
  if cop.nil?
    htg_coil.setRatedHeatingCoefficientofPerformance(4.2)
  else
    htg_coil.setRatedHeatingCoefficientofPerformance(cop)
  end

  # curve sets
  if type == 'OS default'
    # use OS default curves
  else # default curve set
    if model.version < OpenStudio::VersionString.new('3.2.0')
      htg_coil.setHeatingCapacityCoefficient1(0.237847462869254)
      htg_coil.setHeatingCapacityCoefficient2(-3.35823796081626)
      htg_coil.setHeatingCapacityCoefficient3(3.80640467406376)
      htg_coil.setHeatingCapacityCoefficient4(0.179200417311554)
      htg_coil.setHeatingCapacityCoefficient5(0.12860719846082)
      htg_coil.setHeatingPowerConsumptionCoefficient1(-3.79175529243238)
      htg_coil.setHeatingPowerConsumptionCoefficient2(3.38799239505527)
      htg_coil.setHeatingPowerConsumptionCoefficient3(1.5022612076303)
      htg_coil.setHeatingPowerConsumptionCoefficient4(-0.177653510577989)
      htg_coil.setHeatingPowerConsumptionCoefficient5(-0.103079864171839)
    else
      if model.getCurveByName('Water to Air Heat Pump Heating Capacity Curve').is_initialized
        heating_capacity_curve = model.getCurveByName('Water to Air Heat Pump Heating Capacity Curve').get
        heating_capacity_curve = heating_capacity_curve.to_CurveQuadLinear.get
      else
        heating_capacity_curve = OpenStudio::Model::CurveQuadLinear.new(model)
        heating_capacity_curve.setName('Water to Air Heat Pump Heating Capacity Curve')
        heating_capacity_curve.setCoefficient1Constant(0.237847462869254)
        heating_capacity_curve.setCoefficient2w(-3.35823796081626)
        heating_capacity_curve.setCoefficient3x(3.80640467406376)
        heating_capacity_curve.setCoefficient4y(0.179200417311554)
        heating_capacity_curve.setCoefficient5z(0.12860719846082)
        heating_capacity_curve.setMinimumValueofw(-100)
        heating_capacity_curve.setMaximumValueofw(100)
        heating_capacity_curve.setMinimumValueofx(-100)
        heating_capacity_curve.setMaximumValueofx(100)
        heating_capacity_curve.setMinimumValueofy(0)
        heating_capacity_curve.setMaximumValueofy(100)
        heating_capacity_curve.setMinimumValueofz(0)
        heating_capacity_curve.setMaximumValueofz(100)
      end
      htg_coil.setHeatingCapacityCurve(heating_capacity_curve)

      if model.getCurveByName('Water to Air Heat Pump Heating Power Consumption Curve').is_initialized
        heating_power_consumption_curve = model.getCurveByName('Water to Air Heat Pump Heating Power Consumption Curve').get
        heating_power_consumption_curve = heating_power_consumption_curve.to_CurveQuadLinear.get
      else
        heating_power_consumption_curve = OpenStudio::Model::CurveQuadLinear.new(model)
        heating_power_consumption_curve.setName('Water to Air Heat Pump Heating Power Consumption Curve')
        heating_power_consumption_curve.setCoefficient1Constant(-3.79175529243238)
        heating_power_consumption_curve.setCoefficient2w(3.38799239505527)
        heating_power_consumption_curve.setCoefficient3x(1.5022612076303)
        heating_power_consumption_curve.setCoefficient4y(-0.177653510577989)
        heating_power_consumption_curve.setCoefficient5z(-0.103079864171839)
        heating_power_consumption_curve.setMinimumValueofw(-100)
        heating_power_consumption_curve.setMaximumValueofw(100)
        heating_power_consumption_curve.setMinimumValueofx(-100)
        heating_power_consumption_curve.setMaximumValueofx(100)
        heating_power_consumption_curve.setMinimumValueofy(0)
        heating_power_consumption_curve.setMaximumValueofy(100)
        heating_power_consumption_curve.setMinimumValueofz(0)
        heating_power_consumption_curve.setMaximumValueofz(100)
      end
      htg_coil.setHeatingPowerConsumptionCurve(heating_power_consumption_curve)
    end

    # part load fraction correlation curve added as a required curve in OS v3.7.0
    if model.version > OpenStudio::VersionString.new('3.6.1')
      if model.getCurveByName('Water to Air Heat Pump Part Load Fraction Correlation Curve').is_initialized
        part_load_correlation_curve = model.getCurveByName('Water to Air Heat Pump Part Load Fraction Correlation Curve').get
        part_load_correlation_curve = part_load_correlation_curve.to_CurveLinear.get
      else
        part_load_correlation_curve = OpenStudio::Model::CurveLinear.new(model)
        part_load_correlation_curve.setName('Water to Air Heat Pump Part Load Fraction Correlation Curve')
        part_load_correlation_curve.setCoefficient1Constant(0.833746458696111)
        part_load_correlation_curve.setCoefficient2x(0.166253541303889)
        part_load_correlation_curve.setMinimumValueofx(0)
        part_load_correlation_curve.setMaximumValueofx(1)
        part_load_correlation_curve.setMinimumCurveOutput(0)
        part_load_correlation_curve.setMaximumCurveOutput(1)
      end
      htg_coil.setPartLoadFractionCorrelationCurve(part_load_correlation_curve)
    end
  end

  return htg_coil
end
create_curve_bicubic(model, coeffs, crv_name, min_x, max_x, min_y, max_y, min_out, max_out) click to toggle source

Create a bicubic curve of the form z = C1 + C2*x + C3*x^2 + C4*y + C5*y^2 + C6*x*y + C7*x^3 + C8*y^3 + C9*x^2*y + C10*x*y^2

@author Scott Horowitz, NREL @param model [OpenStudio::Model::Model] OpenStudio model object @param coeffs [Array<Double>] an array of 10 coefficients, in order @param crv_name [String] the name of the curve @param min_x [Double] the minimum value of independent variable X that will be used @param max_x [Double] the maximum value of independent variable X that will be used @param min_y [Double] the minimum value of independent variable Y that will be used @param max_y [Double] the maximum value of independent variable Y that will be used @param min_out [Double] the minimum value of dependent variable Z @param max_out [Double] the maximum value of dependent variable Z @return [OpenStudio::Model::CurveBicubic] a bicubic curve

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 519
def create_curve_bicubic(model, coeffs, crv_name, min_x, max_x, min_y, max_y, min_out, max_out)
  curve = OpenStudio::Model::CurveBicubic.new(model)
  curve.setName(crv_name)
  curve.setCoefficient1Constant(coeffs[0])
  curve.setCoefficient2x(coeffs[1])
  curve.setCoefficient3xPOW2(coeffs[2])
  curve.setCoefficient4y(coeffs[3])
  curve.setCoefficient5yPOW2(coeffs[4])
  curve.setCoefficient6xTIMESY(coeffs[5])
  curve.setCoefficient7xPOW3(coeffs[6])
  curve.setCoefficient8yPOW3(coeffs[7])
  curve.setCoefficient9xPOW2TIMESY(coeffs[8])
  curve.setCoefficient10xTIMESYPOW2(coeffs[9])
  curve.setMinimumValueofx(min_x) unless min_x.nil?
  curve.setMaximumValueofx(max_x) unless max_x.nil?
  curve.setMinimumValueofy(min_y) unless min_y.nil?
  curve.setMaximumValueofy(max_y) unless max_y.nil?
  curve.setMinimumCurveOutput(min_out) unless min_out.nil?
  curve.setMaximumCurveOutput(max_out) unless max_out.nil?
  return curve
end
create_curve_biquadratic(model, coeffs, crv_name, min_x, max_x, min_y, max_y, min_out, max_out) click to toggle source

Create a biquadratic curve of the form z = C1 + C2*x + C3*x^2 + C4*y + C5*y^2 + C6*x*y

@author Scott Horowitz, NREL @param model [OpenStudio::Model::Model] OpenStudio model object @param coeffs [Array<Double>] an array of 6 coefficients, in order @param crv_name [String] the name of the curve @param min_x [Double] the minimum value of independent variable X that will be used @param max_x [Double] the maximum value of independent variable X that will be used @param min_y [Double] the minimum value of independent variable Y that will be used @param max_y [Double] the maximum value of independent variable Y that will be used @param min_out [Double] the minimum value of dependent variable Z @param max_out [Double] the maximum value of dependent variable Z @return [OpenStudio::Model::CurveBiquadratic] a biquadratic curve

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 487
def create_curve_biquadratic(model, coeffs, crv_name, min_x, max_x, min_y, max_y, min_out, max_out)
  curve = OpenStudio::Model::CurveBiquadratic.new(model)
  curve.setName(crv_name)
  curve.setCoefficient1Constant(coeffs[0])
  curve.setCoefficient2x(coeffs[1])
  curve.setCoefficient3xPOW2(coeffs[2])
  curve.setCoefficient4y(coeffs[3])
  curve.setCoefficient5yPOW2(coeffs[4])
  curve.setCoefficient6xTIMESY(coeffs[5])
  curve.setMinimumValueofx(min_x) unless min_x.nil?
  curve.setMaximumValueofx(max_x) unless max_x.nil?
  curve.setMinimumValueofy(min_y) unless min_y.nil?
  curve.setMaximumValueofy(max_y) unless max_y.nil?
  curve.setMinimumCurveOutput(min_out) unless min_out.nil?
  curve.setMaximumCurveOutput(max_out) unless max_out.nil?
  return curve
end
create_curve_cubic(model, coeffs, crv_name, min_x, max_x, min_out, max_out) click to toggle source

Create a cubic curve of the form z = C1 + C2*x + C3*x^2 + C4*x^3

@author Scott Horowitz, NREL @param model [OpenStudio::Model::Model] OpenStudio model object @param coeffs [Array<Double>] an array of 4 coefficients, in order @param crv_name [String] the name of the curve @param min_x [Double] the minimum value of independent variable X that will be used @param max_x [Double] the maximum value of independent variable X that will be used @param min_out [Double] the minimum value of dependent variable Z @param max_out [Double] the maximum value of dependent variable Z @return [OpenStudio::Model::CurveCubic] a cubic curve

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 584
def create_curve_cubic(model, coeffs, crv_name, min_x, max_x, min_out, max_out)
  curve = OpenStudio::Model::CurveCubic.new(model)
  curve.setName(crv_name)
  curve.setCoefficient1Constant(coeffs[0])
  curve.setCoefficient2x(coeffs[1])
  curve.setCoefficient3xPOW2(coeffs[2])
  curve.setCoefficient4xPOW3(coeffs[3])
  curve.setMinimumValueofx(min_x) unless min_x.nil?
  curve.setMaximumValueofx(max_x) unless max_x.nil?
  curve.setMinimumCurveOutput(min_out) unless min_out.nil?
  curve.setMaximumCurveOutput(max_out) unless max_out.nil?
  return curve
end
create_curve_exponent(model, coeffs, crv_name, min_x, max_x, min_out, max_out) click to toggle source

Create an exponential curve of the form z = C1 + C2*x^C3

@author Scott Horowitz, NREL @param model [OpenStudio::Model::Model] OpenStudio model object @param coeffs [Array<Double>] an array of 3 coefficients, in order @param crv_name [String] the name of the curve @param min_x [Double] the minimum value of independent variable X that will be used @param max_x [Double] the maximum value of independent variable X that will be used @param min_out [Double] the minimum value of dependent variable Z @param max_out [Double] the maximum value of dependent variable Z @return [OpenStudio::Model::CurveExponent] an exponent curve

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 610
def create_curve_exponent(model, coeffs, crv_name, min_x, max_x, min_out, max_out)
  curve = OpenStudio::Model::CurveExponent.new(model)
  curve.setName(crv_name)
  curve.setCoefficient1Constant(coeffs[0])
  curve.setCoefficient2Constant(coeffs[1])
  curve.setCoefficient3Constant(coeffs[2])
  curve.setMinimumValueofx(min_x) unless min_x.nil?
  curve.setMaximumValueofx(max_x) unless max_x.nil?
  curve.setMinimumCurveOutput(min_out) unless min_out.nil?
  curve.setMaximumCurveOutput(max_out) unless max_out.nil?
  return curve
end
create_curve_quadratic(model, coeffs, crv_name, min_x, max_x, min_out, max_out, is_dimensionless = false) click to toggle source

Create a quadratic curve of the form z = C1 + C2*x + C3*x^2

@author Scott Horowitz, NREL @param model [OpenStudio::Model::Model] OpenStudio model object @param coeffs [Array<Double>] an array of 3 coefficients, in order @param crv_name [String] the name of the curve @param min_x [Double] the minimum value of independent variable X that will be used @param max_x [Double] the maximum value of independent variable X that will be used @param min_out [Double] the minimum value of dependent variable Z @param max_out [Double] the maximum value of dependent variable Z @param is_dimensionless [Boolean] if true, the X independent variable is considered unitless

and the resulting output dependent variable is considered unitless

@return [OpenStudio::Model::CurveQuadratic] a quadratic curve

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 555
def create_curve_quadratic(model, coeffs, crv_name, min_x, max_x, min_out, max_out, is_dimensionless = false)
  curve = OpenStudio::Model::CurveQuadratic.new(model)
  curve.setName(crv_name)
  curve.setCoefficient1Constant(coeffs[0])
  curve.setCoefficient2x(coeffs[1])
  curve.setCoefficient3xPOW2(coeffs[2])
  curve.setMinimumValueofx(min_x) unless min_x.nil?
  curve.setMaximumValueofx(max_x) unless max_x.nil?
  curve.setMinimumCurveOutput(min_out) unless min_out.nil?
  curve.setMaximumCurveOutput(max_out) unless max_out.nil?
  if is_dimensionless
    curve.setInputUnitTypeforX('Dimensionless')
    curve.setOutputUnitType('Dimensionless')
  end
  return curve
end
create_fan_constant_volume(model, fan_name: nil, fan_efficiency: nil, pressure_rise: nil, motor_efficiency: nil, motor_in_airstream_fraction: nil, end_use_subcategory: nil) click to toggle source

creates a constant volume fan

@param model [OpenStudio::Model::Model] OpenStudio model object @param fan_name [String] fan name @param fan_efficiency [Double] fan efficiency @param pressure_rise [Double] fan pressure rise in Pa @param motor_efficiency [Double] fan motor efficiency @param motor_in_airstream_fraction [Double] fraction of motor heat in airstream @param end_use_subcategory [String] end use subcategory name @return [OpenStudio::Model::FanConstantVolume] constant volume fan object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanConstantVolume.rb, line 101
def create_fan_constant_volume(model,
                               fan_name: nil,
                               fan_efficiency: nil,
                               pressure_rise: nil,
                               motor_efficiency: nil,
                               motor_in_airstream_fraction: nil,
                               end_use_subcategory: nil)
  fan = OpenStudio::Model::FanConstantVolume.new(model)
  PrototypeFan.apply_base_fan_variables(fan,
                                        fan_name: fan_name,
                                        fan_efficiency: fan_efficiency,
                                        pressure_rise: pressure_rise,
                                        end_use_subcategory: end_use_subcategory)
  fan.setMotorEfficiency(motor_efficiency) unless motor_efficiency.nil?
  fan.setMotorInAirstreamFraction(motor_in_airstream_fraction) unless motor_in_airstream_fraction.nil?
  return fan
end
create_fan_constant_volume_from_json(model, fan_json, fan_name: nil, fan_efficiency: nil, pressure_rise: nil, motor_efficiency: nil, motor_in_airstream_fraction: nil, end_use_subcategory: nil) click to toggle source

creates a constant volume fan from a json

@param model [OpenStudio::Model::Model] OpenStudio model object @param fan_json [Hash] hash of fan properties @param fan_name [String] fan name @param fan_efficiency [Double] fan efficiency @param pressure_rise [Double] fan pressure rise in Pa @param motor_efficiency [Double] fan motor efficiency @param motor_in_airstream_fraction [Double] fraction of motor heat in airstream @param end_use_subcategory [String] end use subcategory name @return [OpenStudio::Model::FanConstantVolume] constant volume fan object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanConstantVolume.rb, line 130
def create_fan_constant_volume_from_json(model,
                                         fan_json,
                                         fan_name: nil,
                                         fan_efficiency: nil,
                                         pressure_rise: nil,
                                         motor_efficiency: nil,
                                         motor_in_airstream_fraction: nil,
                                         end_use_subcategory: nil)
  # check values to use
  fan_efficiency ||= fan_json['fan_efficiency']
  pressure_rise ||= fan_json['pressure_rise']
  motor_efficiency ||= fan_json['motor_efficiency']
  motor_in_airstream_fraction ||= fan_json['motor_in_airstream_fraction']
  end_use_subcategory ||= fan_json['end_use_subcategory']

  # convert values
  pressure_rise = pressure_rise ? OpenStudio.convert(pressure_rise, 'inH_{2}O', 'Pa').get : nil

  # create fan
  fan = create_fan_constant_volume(model,
                                   fan_name: fan_name,
                                   fan_efficiency: fan_efficiency,
                                   pressure_rise: pressure_rise,
                                   motor_efficiency: motor_efficiency,
                                   motor_in_airstream_fraction: motor_in_airstream_fraction,
                                   end_use_subcategory: end_use_subcategory)
  return fan
end
create_fan_on_off(model, fan_name: nil, fan_efficiency: nil, pressure_rise: nil, motor_efficiency: nil, motor_in_airstream_fraction: nil, end_use_subcategory: nil) click to toggle source

creates an on off fan

@param model [OpenStudio::Model::Model] OpenStudio model object @param fan_name [String] fan name @param fan_efficiency [Double] fan efficiency @param pressure_rise [Double] fan pressure rise in Pa @param motor_efficiency [Double] fan motor efficiency @param motor_in_airstream_fraction [Double] fraction of motor heat in airstream @param end_use_subcategory [String] end use subcategory name @return [OpenStudio::Model::FanOnOff] on off fan object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanOnOff.rb, line 106
def create_fan_on_off(model,
                      fan_name: nil,
                      fan_efficiency: nil,
                      pressure_rise: nil,
                      motor_efficiency: nil,
                      motor_in_airstream_fraction: nil,
                      end_use_subcategory: nil)
  fan = OpenStudio::Model::FanOnOff.new(model)
  PrototypeFan.apply_base_fan_variables(fan,
                                        fan_name: fan_name,
                                        fan_efficiency: fan_efficiency,
                                        pressure_rise: pressure_rise,
                                        end_use_subcategory: end_use_subcategory)
  fan.setMotorEfficiency(motor_efficiency) unless motor_efficiency.nil?
  fan.setMotorInAirstreamFraction(motor_in_airstream_fraction) unless motor_in_airstream_fraction.nil?
  return fan
end
create_fan_on_off_from_json(model, fan_json, fan_name: nil, fan_efficiency: nil, pressure_rise: nil, motor_efficiency: nil, motor_in_airstream_fraction: nil, end_use_subcategory: nil) click to toggle source

creates a on off fan from a json

@param model [OpenStudio::Model::Model] OpenStudio model object @param fan_json [Hash] hash of fan properties @param fan_name [String] fan name @param fan_efficiency [Double] fan efficiency @param pressure_rise [Double] fan pressure rise in Pa @param motor_efficiency [Double] fan motor efficiency @param motor_in_airstream_fraction [Double] fraction of motor heat in airstream @param end_use_subcategory [String] end use subcategory name @return [OpenStudio::Model::FanOnOff] on off fan object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanOnOff.rb, line 135
def create_fan_on_off_from_json(model,
                                fan_json,
                                fan_name: nil,
                                fan_efficiency: nil,
                                pressure_rise: nil,
                                motor_efficiency: nil,
                                motor_in_airstream_fraction: nil,
                                end_use_subcategory: nil)
  # check values to use
  fan_efficiency ||= fan_json['fan_efficiency']
  pressure_rise ||= fan_json['pressure_rise']
  motor_efficiency ||= fan_json['motor_efficiency']
  motor_in_airstream_fraction ||= fan_json['motor_in_airstream_fraction']

  # convert values
  pressure_rise = pressure_rise ? OpenStudio.convert(pressure_rise, 'inH_{2}O', 'Pa').get : nil

  # create fan
  fan = create_fan_on_off(model,
                          fan_name: fan_name,
                          fan_efficiency: fan_efficiency,
                          pressure_rise: pressure_rise,
                          motor_efficiency: motor_efficiency,
                          motor_in_airstream_fraction: motor_in_airstream_fraction,
                          end_use_subcategory: end_use_subcategory)
  return fan
end
create_fan_variable_volume(model, fan_name: nil, fan_efficiency: nil, pressure_rise: nil, motor_efficiency: nil, motor_in_airstream_fraction: nil, fan_power_minimum_flow_rate_input_method: nil, fan_power_minimum_flow_rate_fraction: nil, fan_power_coefficient_1: nil, fan_power_coefficient_2: nil, fan_power_coefficient_3: nil, fan_power_coefficient_4: nil, fan_power_coefficient_5: nil, end_use_subcategory: nil) click to toggle source

creates a variable volume fan

@param model [OpenStudio::Model::Model] OpenStudio model object @param fan_name [String] fan name @param fan_efficiency [Double] fan efficiency @param pressure_rise [Double] fan pressure rise in Pa @param motor_efficiency [Double] fan motor efficiency @param motor_in_airstream_fraction [Double] fraction of motor heat in airstream @param fan_power_minimum_flow_rate_input_method [String] options are Fraction, FixedFlowRate @param fan_power_minimum_flow_rate_fraction [Double] minimum flow rate fraction @param end_use_subcategory [String] end use subcategory name @param fan_power_coefficient_1 [Double] fan power coefficient 1 @param fan_power_coefficient_2 [Double] fan power coefficient 2 @param fan_power_coefficient_3 [Double] fan power coefficient 3 @param fan_power_coefficient_4 [Double] fan power coefficient 4 @param fan_power_coefficient_5 [Double] fan power coefficient 5 @return [OpenStudio::Model::FanVariableVolume] variable volume fan object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanVariableVolume.rb, line 106
def create_fan_variable_volume(model,
                               fan_name: nil,
                               fan_efficiency: nil,
                               pressure_rise: nil,
                               motor_efficiency: nil,
                               motor_in_airstream_fraction: nil,
                               fan_power_minimum_flow_rate_input_method: nil,
                               fan_power_minimum_flow_rate_fraction: nil,
                               fan_power_coefficient_1: nil,
                               fan_power_coefficient_2: nil,
                               fan_power_coefficient_3: nil,
                               fan_power_coefficient_4: nil,
                               fan_power_coefficient_5: nil,
                               end_use_subcategory: nil)
  fan = OpenStudio::Model::FanVariableVolume.new(model)
  PrototypeFan.apply_base_fan_variables(fan,
                                        fan_name: fan_name,
                                        fan_efficiency: fan_efficiency,
                                        pressure_rise: pressure_rise,
                                        end_use_subcategory: end_use_subcategory)
  fan.setMotorEfficiency(motor_efficiency) unless motor_efficiency.nil?
  fan.setMotorInAirstreamFraction(motor_in_airstream_fraction) unless motor_in_airstream_fraction.nil?
  fan.setFanPowerMinimumFlowRateInputMethod(fan_power_minimum_flow_rate_input_method) unless fan_power_minimum_flow_rate_input_method.nil?
  fan.setFanPowerMinimumFlowFraction(fan_power_minimum_flow_rate_fraction) unless fan_power_minimum_flow_rate_fraction.nil?
  fan.setFanPowerCoefficient1(fan_power_coefficient_1) unless fan_power_coefficient_1.nil?
  fan.setFanPowerCoefficient2(fan_power_coefficient_2) unless fan_power_coefficient_2.nil?
  fan.setFanPowerCoefficient3(fan_power_coefficient_3) unless fan_power_coefficient_3.nil?
  fan.setFanPowerCoefficient4(fan_power_coefficient_4) unless fan_power_coefficient_4.nil?
  fan.setFanPowerCoefficient5(fan_power_coefficient_5) unless fan_power_coefficient_5.nil?
  return fan
end
create_fan_variable_volume_from_json(model, fan_json, fan_name: nil, fan_efficiency: nil, pressure_rise: nil, motor_efficiency: nil, motor_in_airstream_fraction: nil, fan_power_minimum_flow_rate_input_method: nil, fan_power_minimum_flow_rate_fraction: nil, end_use_subcategory: nil, fan_power_coefficient_1: nil, fan_power_coefficient_2: nil, fan_power_coefficient_3: nil, fan_power_coefficient_4: nil, fan_power_coefficient_5: nil) click to toggle source

creates a variable volume fan from a json

@param model [OpenStudio::Model::Model] OpenStudio model object @param fan_json [Hash] hash of fan properties @param fan_name [String] fan name @param fan_efficiency [Double] fan efficiency @param pressure_rise [Double] fan pressure rise in Pa @param motor_efficiency [Double] fan motor efficiency @param motor_in_airstream_fraction [Double] fraction of motor heat in airstream @param fan_power_minimum_flow_rate_input_method [String] options are Fraction, FixedFlowRate @param fan_power_minimum_flow_rate_fraction [Double] minimum flow rate fraction @param end_use_subcategory [String] end use subcategory name @param fan_power_coefficient_1 [Double] fan power coefficient 1 @param fan_power_coefficient_2 [Double] fan power coefficient 2 @param fan_power_coefficient_3 [Double] fan power coefficient 3 @param fan_power_coefficient_4 [Double] fan power coefficient 4 @param fan_power_coefficient_5 [Double] fan power coefficient 5 @return [OpenStudio::Model::FanVariableVolume] variable volume fan object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanVariableVolume.rb, line 156
def create_fan_variable_volume_from_json(model,
                                         fan_json,
                                         fan_name: nil,
                                         fan_efficiency: nil,
                                         pressure_rise: nil,
                                         motor_efficiency: nil,
                                         motor_in_airstream_fraction: nil,
                                         fan_power_minimum_flow_rate_input_method: nil,
                                         fan_power_minimum_flow_rate_fraction: nil,
                                         end_use_subcategory: nil,
                                         fan_power_coefficient_1: nil,
                                         fan_power_coefficient_2: nil,
                                         fan_power_coefficient_3: nil,
                                         fan_power_coefficient_4: nil,
                                         fan_power_coefficient_5: nil)
  # check values to use
  fan_efficiency ||= fan_json['fan_efficiency']
  pressure_rise ||= fan_json['pressure_rise']
  motor_efficiency ||= fan_json['motor_efficiency']
  motor_in_airstream_fraction ||= fan_json['motor_in_airstream_fraction']
  fan_power_minimum_flow_rate_input_method ||= fan_json['fan_power_minimum_flow_rate_input_method']
  fan_power_minimum_flow_rate_fraction ||= fan_json['fan_power_minimum_flow_rate_fraction']
  fan_power_coefficient_1 ||= fan_json['fan_power_coefficient_1']
  fan_power_coefficient_2 ||= fan_json['fan_power_coefficient_2']
  fan_power_coefficient_3 ||= fan_json['fan_power_coefficient_3']
  fan_power_coefficient_4 ||= fan_json['fan_power_coefficient_4']
  fan_power_coefficient_5 ||= fan_json['fan_power_coefficient_5']

  # convert values
  pressure_rise_pa = OpenStudio.convert(pressure_rise, 'inH_{2}O', 'Pa').get unless pressure_rise.nil?

  # create fan
  fan = create_fan_variable_volume(model,
                                   fan_name: fan_name,
                                   fan_efficiency: fan_efficiency,
                                   pressure_rise: pressure_rise_pa,
                                   motor_efficiency: motor_efficiency,
                                   motor_in_airstream_fraction: motor_in_airstream_fraction,
                                   fan_power_minimum_flow_rate_input_method: fan_power_minimum_flow_rate_input_method,
                                   fan_power_minimum_flow_rate_fraction: fan_power_minimum_flow_rate_fraction,
                                   end_use_subcategory: end_use_subcategory,
                                   fan_power_coefficient_1: fan_power_coefficient_1,
                                   fan_power_coefficient_2: fan_power_coefficient_2,
                                   fan_power_coefficient_3: fan_power_coefficient_3,
                                   fan_power_coefficient_4: fan_power_coefficient_4,
                                   fan_power_coefficient_5: fan_power_coefficient_5)
  return fan
end
create_fan_zone_exhaust(model, fan_name: nil, fan_efficiency: nil, pressure_rise: nil, system_availability_manager_coupling_mode: nil, end_use_subcategory: nil) click to toggle source

creates a FanZoneExhaust

@param model [OpenStudio::Model::Model] OpenStudio model object @param fan_name [String] fan name @param fan_efficiency [Double] fan efficiency @param pressure_rise [Double] fan pressure rise in Pa @param system_availability_manager_coupling_mode [String] coupling mode, options are Coupled, Decoupled @param end_use_subcategory [String] end use subcategory name @return [OpenStudio::Model::FanZoneExhaust] the exhaust fan

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanZoneExhaust.rb, line 72
def create_fan_zone_exhaust(model,
                            fan_name: nil,
                            fan_efficiency: nil,
                            pressure_rise: nil,
                            system_availability_manager_coupling_mode: nil,
                            end_use_subcategory: nil)
  fan = OpenStudio::Model::FanZoneExhaust.new(model)
  PrototypeFan.apply_base_fan_variables(fan,
                                        fan_name: fan_name,
                                        fan_efficiency: fan_efficiency,
                                        pressure_rise: pressure_rise,
                                        end_use_subcategory: end_use_subcategory)
  fan.setSystemAvailabilityManagerCouplingMode(system_availability_manager_coupling_mode) unless system_availability_manager_coupling_mode.nil?
  return fan
end
create_fan_zone_exhaust_from_json(model, fan_json, fan_name: nil, fan_efficiency: nil, pressure_rise: nil, system_availability_manager_coupling_mode: nil, end_use_subcategory: nil) click to toggle source

creates a FanZoneExhaust from a json

@param model [OpenStudio::Model::Model] OpenStudio model object @param fan_json [Hash] hash of fan properties @param fan_name [String] fan name @param fan_efficiency [Double] fan efficiency @param pressure_rise [Double] fan pressure rise in Pa @param system_availability_manager_coupling_mode [String] coupling mode, options are Coupled, Decoupled @param end_use_subcategory [String] end use subcategory name @return [OpenStudio::Model::FanZoneExhaust] the exhaust fan

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanZoneExhaust.rb, line 37
def create_fan_zone_exhaust_from_json(model,
                                      fan_json,
                                      fan_name: nil,
                                      fan_efficiency: nil,
                                      pressure_rise: nil,
                                      system_availability_manager_coupling_mode: nil,
                                      end_use_subcategory: nil)

  # check values to use
  fan_efficiency ||= fan_json['fan_efficiency']
  pressure_rise ||= fan_json['pressure_rise']
  system_availability_manager_coupling_mode ||= fan_json['system_availability_manager_coupling_mode']

  # convert values
  pressure_rise = pressure_rise ? OpenStudio.convert(pressure_rise, 'inH_{2}O', 'Pa').get : nil

  # create fan
  fan = create_fan_zone_exhaust(model,
                                fan_name: fan_name,
                                fan_efficiency: fan_efficiency,
                                pressure_rise: pressure_rise,
                                system_availability_manager_coupling_mode: system_availability_manager_coupling_mode,
                                end_use_subcategory: end_use_subcategory)
  return fan
end
define_space_multiplier() click to toggle source

@return [Hash] space multiplier map

# File lib/openstudio-standards/standards/Standards.Model.rb, line 11
def define_space_multiplier
  return @space_multiplier_map
end
eer_to_cop(eer) click to toggle source

Convert from EER to COP

@param eer [Double] Energy Efficiency Ratio (EER) @return [Double] Coefficient of Performance (COP)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 374
def eer_to_cop(eer)
  return eer / OpenStudio.convert(1.0, 'W', 'Btu/h').get
end
eer_to_cop_no_fan(eer, capacity_w = nil) click to toggle source

Convert from EER to COP @ref [References::USDOEPrototypeBuildings] If capacity is not supplied, use DOE Prototype Building method. @ref [References::ASHRAE9012013] If capacity is supplied, use the 90.1-2013 method

@param eer [Double] Energy Efficiency Ratio (EER) @param capacity_w [Double] the heating capacity at AHRI rating conditions, in W @return [Double] Coefficient of Performance (COP)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 331
def eer_to_cop_no_fan(eer, capacity_w = nil)
  if capacity_w.nil?
    # From Thornton et al. 2011
    # r is the ratio of supply fan power to total equipment power at the rating condition,
    # assumed to be 0.12 for the reference buildings per Thornton et al. 2011.
    r = 0.12
    cop = (eer / OpenStudio.convert(1.0, 'W', 'Btu/h').get + r) / (1 - r)
  else
    # The 90.1-2013 method
    # Convert the capacity to Btu/hr
    capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get
    cop = 7.84E-8 * eer * capacity_btu_per_hr + 0.338 * eer
  end

  return cop
end
ems_friendly_name(name) click to toggle source

converts existing string to ems friendly string

@param name [String] original name @return [String] the resulting EMS friendly string

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 872
def ems_friendly_name(name)
  # replace white space and special characters with underscore
  # \W is equivalent to [^a-zA-Z0-9_]
  new_name = name.to_s.gsub(/\W/, '_')

  # prepend ems_ in case the name starts with a number
  new_name = 'ems_' + new_name

  return new_name
end
enthalpy_recovery_ratio_design_to_typical_adjustment(enthalpy_recovery_ratio, climate_zone) click to toggle source

Adjust ERR from design conditions to ERR for typical conditions. This is only applies to the 2B and 3B climate zones. In these climate zones a 50% ERR at typical condition leads a ERR > 50%, the ERR is thus scaled down.

@param enthalpy_recovery_ratio [Double] Enthalpy Recovery Ratio (ERR) @param climate_zone [String] climate zone @return [Double] adjusted ERR

# File lib/openstudio-standards/standards/Standards.HeatExchangerSensLat.rb, line 59
def enthalpy_recovery_ratio_design_to_typical_adjustment(enthalpy_recovery_ratio, climate_zone)
  if climate_zone.include? '2B'
    enthalpy_recovery_ratio /= 0.65 / 0.55
  elsif climate_zone.include? '3B'
    enthalpy_recovery_ratio /= 0.62 / 0.55
  end

  return enthalpy_recovery_ratio
end
fan_constant_volume_airloop_fan_pressure_rise(fan_constant_volume) click to toggle source

Determine the prototype fan pressure rise for a constant volume fan on an AirLoopHVAC based on system airflow. Defaults to the logic from ASHRAE 90.1-2004 prototypes.

@param fan_constant_volume [OpenStudio::Model::FanConstantVolume] constant volume fan object @return [Double] pressure rise in inches H20

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanConstantVolume.rb, line 64
def fan_constant_volume_airloop_fan_pressure_rise(fan_constant_volume)
  # Get the max flow rate from the fan.
  maximum_flow_rate_m3_per_s = nil
  if fan_constant_volume.maximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_constant_volume.maximumFlowRate.get
  elsif fan_constant_volume.autosizedMaximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_constant_volume.autosizedMaximumFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.FanConstantVolume', "For #{fan_constant_volume.name} max flow rate is not available, cannot apply prototype assumptions.")
    return false
  end

  # Convert max flow rate to cfm
  maximum_flow_rate_cfm = OpenStudio.convert(maximum_flow_rate_m3_per_s, 'm^3/s', 'cfm').get

  # Determine the pressure rise
  pressure_rise_in_h2o = if maximum_flow_rate_cfm < 7437
                           2.5
                         elsif maximum_flow_rate_cfm >= 7437 && maximum_flow_rate_cfm < 20_000
                           4.46
                         else # Over 20,000 cfm
                           4.09
                         end

  return pressure_rise_in_h2o
end
fan_constant_volume_apply_prototype_fan_pressure_rise(fan_constant_volume) click to toggle source

Sets the fan pressure rise based on the Prototype buildings inputs which are governed by the flow rate coming through the fan and whether the fan lives inside a unit heater, PTAC, etc.

@param fan_constant_volume [OpenStudio::Model::FanConstantVolume] constant volume fan object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanConstantVolume.rb, line 11
def fan_constant_volume_apply_prototype_fan_pressure_rise(fan_constant_volume)
  # Don't modify unit heater fans
  return true if fan_constant_volume.name.to_s.include?('UnitHeater Fan')

  # Get the max flow rate from the fan.
  maximum_flow_rate_m3_per_s = nil
  if fan_constant_volume.maximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_constant_volume.maximumFlowRate.get
  elsif fan_constant_volume.autosizedMaximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_constant_volume.autosizedMaximumFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.FanConstantVolume', "For #{fan_constant_volume.name} max flow rate is not available, cannot apply prototype assumptions.")
    return false
  end

  # Convert max flow rate to cfm
  maximum_flow_rate_cfm = OpenStudio.convert(maximum_flow_rate_m3_per_s, 'm^3/s', 'cfm').get

  # Pressure rise will be determined based on the
  # following logic.
  pressure_rise_in_h2o = 0.0

  # If the fan lives inside of a zone hvac equipment
  if fan_constant_volume.containingZoneHVACComponent.is_initialized
    zone_hvac = fan_constant_volume.containingZoneHVACComponent.get
    if zone_hvac.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
      pressure_rise_in_h2o = 1.33
    elsif zone_hvac.to_ZoneHVACFourPipeFanCoil.is_initialized
      pressure_rise_in_h2o = 1.33
    elsif zone_hvac.to_ZoneHVACUnitHeater.is_initialized
      pressure_rise_in_h2o = 0.2
    else # This type of fan should not exist in the prototype models
      return false
    end
  # If the fan lives on an airloop
  elsif fan_constant_volume.airLoopHVAC.is_initialized
    pressure_rise_in_h2o = fan_constant_volume_airloop_fan_pressure_rise(fan_constant_volume)
  end

  # Set the fan pressure rise
  pressure_rise_pa = OpenStudio.convert(pressure_rise_in_h2o, 'inH_{2}O', 'Pa').get
  fan_constant_volume.setPressureRise(pressure_rise_pa)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.FanConstantVolume', "For Prototype: #{fan_constant_volume.name}: #{maximum_flow_rate_cfm.round}cfm; Pressure Rise = #{pressure_rise_in_h2o}in w.c.")

  return true
end
fan_on_off_airloop_or_unitary_fan_pressure_rise(fan_on_off) click to toggle source

Determine the prototype fan pressure rise for an on off fan on an AirLoopHVAC or inside a unitary system based on system airflow. Defaults to the logic from ASHRAE 90.1-2004 prototypes.

@param fan_on_off [OpenStudio::Model::FanOnOff] on off fan object @return [Double] pressure rise in inches H20

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanOnOff.rb, line 69
def fan_on_off_airloop_or_unitary_fan_pressure_rise(fan_on_off)
  # Get the max flow rate from the fan.
  maximum_flow_rate_m3_per_s = nil
  if fan_on_off.maximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_on_off.maximumFlowRate.get
  elsif fan_on_off.autosizedMaximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_on_off.autosizedMaximumFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.FanOnOff', "For #{fan_on_off.name} max flow rate is not available, cannot apply prototype assumptions.")
    return false
  end

  # Convert max flow rate to cfm
  maximum_flow_rate_cfm = OpenStudio.convert(maximum_flow_rate_m3_per_s, 'm^3/s', 'cfm').get

  # Determine the pressure rise
  pressure_rise_in_h2o = if maximum_flow_rate_cfm < 7437
                           2.5
                         elsif maximum_flow_rate_cfm >= 7437 && maximum_flow_rate_cfm < 20_000
                           4.46
                         else # Over 20,000 cfm
                           4.09
                         end

  return pressure_rise_in_h2o
end
fan_on_off_apply_prototype_fan_pressure_rise(fan_on_off) click to toggle source

Sets the fan pressure rise based on the Prototype buildings inputs which are governed by the flow rate coming through the fan and whether the fan lives inside a unit heater, PTAC, etc.

@param fan_on_off [OpenStudio::Model::FanOnOff] on off fan object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanOnOff.rb, line 12
def fan_on_off_apply_prototype_fan_pressure_rise(fan_on_off)
  # Get the max flow rate from the fan.
  maximum_flow_rate_m3_per_s = nil
  if fan_on_off.maximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_on_off.maximumFlowRate.get
  elsif fan_on_off.autosizedMaximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_on_off.autosizedMaximumFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.FanOnOff', "For #{fan_on_off.name} max flow rate is not available, cannot apply prototype assumptions.")
    return false
  end

  # Convert max flow rate to cfm
  maximum_flow_rate_cfm = OpenStudio.convert(maximum_flow_rate_m3_per_s, 'm^3/s', 'cfm').get

  # Pressure rise will be determined based on the
  # following logic.
  pressure_rise_in_h2o = 0.0

  # If the fan lives inside of a zone hvac equipment
  if fan_on_off.containingZoneHVACComponent.is_initialized
    zone_hvac = fan_on_off.containingZoneHVACComponent.get
    if zone_hvac.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
      pressure_rise_in_h2o = 1.33
    elsif zone_hvac.to_ZoneHVACFourPipeFanCoil.is_initialized
      pressure_rise_in_h2o = 1.087563267
    elsif zone_hvac.to_ZoneHVACUnitHeater.is_initialized
      pressure_rise_in_h2o = 0.2
    else # This type of fan should not exist in the prototype models
      return false
    end
  end

  # If the fan lives on an airloop
  if fan_on_off.airLoopHVAC.is_initialized
    pressure_rise_in_h2o = fan_on_off_airloop_or_unitary_fan_pressure_rise(fan_on_off)
  end

  # If the fan lives inside a unitary system
  if fan_on_off.airLoopHVAC.empty? && fan_on_off.containingZoneHVACComponent.empty?
    pressure_rise_in_h2o = fan_on_off_airloop_or_unitary_fan_pressure_rise(fan_on_off)
  end

  # Set the fan pressure rise
  pressure_rise_pa = OpenStudio.convert(pressure_rise_in_h2o, 'inH_{2}O', 'Pa').get
  fan_on_off.setPressureRise(pressure_rise_pa)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.FanOnOff', "For Prototype: #{fan_on_off.name}: #{maximum_flow_rate_cfm.round}cfm; Pressure Rise = #{pressure_rise_in_h2o}in w.c.")

  return true
end
fan_variable_volume_airloop_fan_pressure_rise(fan_variable_volume) click to toggle source

Determine the prototype fan pressure rise for a variable volume fan on an AirLoopHVAC based on system airflow. Defaults to the logic from ASHRAE 90.1-2004 prototypes.

@param fan_variable_volume [OpenStudio::Model::FanVariableVolume] variable volume fan object @return [Double] pressure rise in inches H20

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanVariableVolume.rb, line 62
def fan_variable_volume_airloop_fan_pressure_rise(fan_variable_volume)
  # Get the max flow rate from the fan.
  maximum_flow_rate_m3_per_s = nil
  if fan_variable_volume.maximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_variable_volume.maximumFlowRate.get
  elsif fan_variable_volume.autosizedMaximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_variable_volume.autosizedMaximumFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.FanVariableVolume', "For #{fan_variable_volume.name} max flow rate is not available, cannot apply prototype assumptions.")
    return false
  end

  # Convert max flow rate to cfm
  maximum_flow_rate_cfm = OpenStudio.convert(maximum_flow_rate_m3_per_s, 'm^3/s', 'cfm').get

  # Determine the pressure rise
  pressure_rise_in_h2o = if maximum_flow_rate_cfm < 4648
                           4.0
                         elsif maximum_flow_rate_cfm >= 4648 && maximum_flow_rate_cfm < 20_000
                           6.32
                         else # Over 20,000 cfm
                           5.58
                         end

  return pressure_rise_in_h2o
end
fan_variable_volume_apply_prototype_fan_pressure_rise(fan_variable_volume) click to toggle source

Sets the fan pressure rise based on the Prototype buildings inputs which are governed by the flow rate coming through the fan and whether the fan lives inside a unit heater, PTAC, etc.

@param fan_variable_volume [OpenStudio::Model::FanVariableVolume] variable volume fan object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanVariableVolume.rb, line 12
def fan_variable_volume_apply_prototype_fan_pressure_rise(fan_variable_volume)
  # Get the max flow rate from the fan.
  maximum_flow_rate_m3_per_s = nil
  if fan_variable_volume.maximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_variable_volume.maximumFlowRate.get
  elsif fan_variable_volume.autosizedMaximumFlowRate.is_initialized
    maximum_flow_rate_m3_per_s = fan_variable_volume.autosizedMaximumFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.FanVariableVolume', "For #{fan_variable_volume.name} max flow rate is not available, cannot apply prototype assumptions.")
    return false
  end

  # Convert max flow rate to cfm
  maximum_flow_rate_cfm = OpenStudio.convert(maximum_flow_rate_m3_per_s, 'm^3/s', 'cfm').get

  # Pressure rise will be determined based on the
  # following logic.
  pressure_rise_in_h2o = 0.0

  # If the fan lives inside of a zone hvac equipment
  if fan_variable_volume.containingZoneHVACComponent.is_initialized
    zone_hvac = fan_variable_volume.ZoneHVACComponent.get
    if zone_hvac.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
      pressure_rise_in_h2o = 1.33
    elsif zone_hvac.to_ZoneHVACFourPipeFanCoil.is_initialized
      pressure_rise_in_h2o = 1.33
    elsif zone_hvac.to_ZoneHVACUnitHeater.is_initialized
      pressure_rise_in_h2o = 0.2
    else # This type of fan should not exist in the prototype models
      return false
    end
  # If the fan lives on an airloop
  elsif fan_variable_volume.airLoopHVAC.is_initialized
    pressure_rise_in_h2o = fan_variable_volume_airloop_fan_pressure_rise(fan_variable_volume)
  end

  # Set the fan pressure rise
  pressure_rise_pa = OpenStudio.convert(pressure_rise_in_h2o, 'inH_{2}O', 'Pa').get
  fan_variable_volume.setPressureRise(pressure_rise_pa)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.FanVariableVolume', "For Prototype: #{fan_variable_volume.name}: #{maximum_flow_rate_cfm.round}cfm; Pressure Rise = #{pressure_rise_in_h2o}in w.c.")

  return true
end
fan_variable_volume_cooling_system_type(fan_variable_volume) click to toggle source

Determine if the cooling system is DX, CHW, evaporative, or a mixture.

@param fan_variable_volume [OpenStudio::Model::FanVariableVolume] variable volume fan object @return [String] the cooling system type. Possible options are:

dx, chw, evaporative, mixed, unknown.
# File lib/openstudio-standards/standards/Standards.FanVariableVolume.rb, line 187
def fan_variable_volume_cooling_system_type(fan_variable_volume)
  clg_sys_type = 'unknown'

  # Get the air loop this fan is connected to
  air_loop = fan_variable_volume.airLoopHVAC
  return clg_sys_type unless air_loop.is_initialized

  air_loop = air_loop.get

  # Check the types of coils on the AirLoopHVAC
  has_dx = false
  has_chw = false
  has_evap = false
  air_loop.supplyComponents.each do |sc|
    # CoilCoolingDXSingleSpeed
    if sc.to_CoilCoolingDXSingleSpeed.is_initialized
      has_dx = true
    # CoilCoolingDXTwoSpeed
    elsif sc.to_CoilCoolingDXTwoSpeed.is_initialized
      has_dx = true
    # CoilCoolingMultiSpeed
    elsif sc.to_CoilCoolingDXMultiSpeed.is_initialized
      has_dx = true
    # CoilCoolingWater
    elsif sc.to_CoilCoolingWater.is_initialized
      has_chw = true
    # CoilCoolingWaterToAirHeatPumpEquationFit
    elsif sc.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized
      has_dx = true
    # UnitarySystem
    elsif sc.to_AirLoopHVACUnitarySystem.is_initialized
      unitary = sc.to_AirLoopHVACUnitarySystem.get
      if unitary.coolingCoil.is_initialized
        clg_coil = unitary.coolingCoil.get
        # CoilCoolingDXSingleSpeed
        if clg_coil.to_CoilCoolingDXSingleSpeed.is_initialized
          has_dx = true
        # CoilCoolingDXTwoSpeed
        elsif clg_coil.to_CoilCoolingDXTwoSpeed.is_initialized
          has_dx = true
        # CoilCoolingWater
        elsif clg_coil.to_CoilCoolingWater.is_initialized
          has_chw = true
        # CoilCoolingWaterToAirHeatPumpEquationFit
        elsif clg_coil.to_CoilCoolingWaterToAirHeatPumpEquationFit.is_initialized
          has_dx = true
        end
      end
    # UnitaryHeatPumpAirToAir
    elsif sc.to_AirLoopHVACUnitaryHeatPumpAirToAir.is_initialized
      unitary = sc.to_AirLoopHVACUnitaryHeatPumpAirToAir.get
      clg_coil = unitary.coolingCoil
      # CoilCoolingDXSingleSpeed
      if clg_coil.to_CoilCoolingDXSingleSpeed.is_initialized
        has_dx = true
      # CoilCoolingDXTwoSpeed
      elsif clg_coil.to_CoilCoolingDXTwoSpeed.is_initialized
        has_dx = true
      # CoilCoolingWater
      elsif clg_coil.to_CoilCoolingWater.is_initialized
        has_chw = true
      end
    # EvaporativeCoolerDirectResearchSpecial
    elsif sc.to_EvaporativeCoolerDirectResearchSpecial.is_initialized
      has_evap = true
    # EvaporativeCoolerIndirectResearchSpecial
    elsif sc.to_EvaporativeCoolerIndirectResearchSpecial.is_initialized
      has_evap = true
    elsif sc.to_CoilCoolingCooledBeam.is_initialized ||
          sc.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.is_initialized ||
          sc.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.is_initialized ||
          sc.to_AirLoopHVACUnitarySystem.is_initialized
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.FanVariableVolume', "#{air_loop.name} has a cooling coil named #{sc.name}, whose type is not yet covered by cooling system type checks.")
    end
  end

  # Determine the type
  if (has_chw && has_dx && has_evap) ||
     (has_chw && has_dx) ||
     (has_chw && has_evap) ||
     (has_dx && has_evap)
    clg_sys_type = 'mixed'
  elsif has_chw
    clg_sys_type = 'chw'
  elsif has_dx
    clg_sys_type = 'dx'
  elsif has_evap
    clg_sys_type = 'evap'
  end

  return clg_sys_type
end
fan_variable_volume_part_load_fan_power_limitation?(fan_variable_volume) click to toggle source

Determines whether there is a requirement to have a VSD or some other method to reduce fan power at low part load ratios.

@param fan_variable_volume [OpenStudio::Model::FanVariableVolume] variable volume fan object @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.FanVariableVolume.rb, line 117
def fan_variable_volume_part_load_fan_power_limitation?(fan_variable_volume)
  part_load_control_required = false

  # Check if the fan is on a multizone or single zone system.
  # If not on an AirLoop (for example, in unitary system or zone equipment), assumed to be a single zone fan
  mz_fan = false
  if fan_variable_volume.airLoopHVAC.is_initialized
    air_loop = fan_variable_volume.airLoopHVAC.get
    mz_fan = air_loop_hvac_multizone_vav_system?(air_loop)
  end

  # No part load fan power control is required for single zone VAV systems
  unless mz_fan
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.FanVariableVolume', "For #{fan_variable_volume.name}: No part load fan power control is required for single zone VAV systems.")
    return part_load_control_required
  end

  # Determine the motor and capacity size limits
  hp_limit = fan_variable_volume_part_load_fan_power_limitation_hp_limit(fan_variable_volume)
  cap_limit_btu_per_hr = fan_variable_volume_part_load_fan_power_limitation_capacity_limit(fan_variable_volume)

  # Check against limits
  if hp_limit && cap_limit_btu_per_hr
    air_loop = fan_variable_volume.airLoopHVAC
    unless air_loop.is_initialized
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.FanVariableVolume', "For #{fan_variable_volume.name}: Could not find the air loop to get cooling capacity for determining part load fan power control requirement.")
      return part_load_control_required
    end
    air_loop = air_loop.get
    clg_cap_w = air_loop_hvac_total_cooling_capacity(air_loop)
    clg_cap_btu_per_hr = OpenStudio.convert(clg_cap_w, 'W', 'Btu/hr').get
    fan_hp = fan_motor_horsepower(fan_variable_volume)
    if fan_hp >= hp_limit && clg_cap_btu_per_hr >= cap_limit_btu_per_hr
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.FanVariableVolume', "For #{fan_variable_volume.name}: part load fan power control is required for #{fan_hp.round(1)} HP fan, #{clg_cap_btu_per_hr.round} Btu/hr cooling capacity.")
      part_load_control_required = true
    end
  elsif hp_limit
    fan_hp = fan_motor_horsepower(fan_variable_volume)
    if fan_hp >= hp_limit
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.FanVariableVolume', "For #{fan_variable_volume.name}: Part load fan power control is required for #{fan_hp.round(1)} HP fan.")
      part_load_control_required = true
    end
  end

  return part_load_control_required
end
fan_variable_volume_part_load_fan_power_limitation_capacity_limit(fan_variable_volume) click to toggle source

The threhold capacity below which part load control is not required.

@param fan_variable_volume [OpenStudio::Model::FanVariableVolume] variable volume fan object @return [Double] the limit, in Btu/hr. Return nil for no limit by default.

# File lib/openstudio-standards/standards/Standards.FanVariableVolume.rb, line 177
def fan_variable_volume_part_load_fan_power_limitation_capacity_limit(fan_variable_volume)
  cap_limit_btu_per_hr = nil # No minimum limit
  return cap_limit_btu_per_hr
end
fan_variable_volume_part_load_fan_power_limitation_hp_limit(fan_variable_volume) click to toggle source

The threhold horsepower below which part load control is not required.

@param fan_variable_volume [OpenStudio::Model::FanVariableVolume] variable volume fan object @return [Double] the limit, in horsepower. Return nil for no limit by default.

# File lib/openstudio-standards/standards/Standards.FanVariableVolume.rb, line 168
def fan_variable_volume_part_load_fan_power_limitation_hp_limit(fan_variable_volume)
  hp_limit = nil # No minimum limit
  return hp_limit
end
fan_variable_volume_set_control_type(fan_variable_volume, control_type) click to toggle source

Modify the fan curve coefficients to reflect a specific type of control.

@param fan_variable_volume [OpenStudio::Model::FanVariableVolume] variable volume fan object @param control_type [String] valid choices are:

Multi Zone VAV with discharge dampers,
Multi Zone VAV with VSD and SP Setpoint Reset,
Multi Zone VAV with AF or BI Riding Curve,
Multi Zone VAV with AF or BI with Inlet Vanes,
Multi Zone VAV with FC Riding Curve,
Multi Zone VAV with FC with Inlet Vanes,
Multi Zone VAV with Vane-axial with Variable Pitch Blades,
Multi Zone VAV with VSD and Fixed SP Setpoint,
Multi Zone VAV with VSD and Static Pressure Reset,
Single Zone VAV Fan

@return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.FanVariableVolume.rb, line 21
def fan_variable_volume_set_control_type(fan_variable_volume, control_type)
  # Determine the coefficients
  coeff_a = nil
  coeff_b = nil
  coeff_c = nil
  coeff_d = nil
  min_pct_pwr = nil
  case control_type

  # add 'Multi Zone VAV with discharge dampers' and change the minimum fan power fraction of "Multi Zone VAV with VSD and Static Pressure Reset"
  when 'Multi Zone VAV with discharge dampers'
    coeff_a = 0.18984763
    coeff_b = 0.31447014
    coeff_c = 0.49568211
    coeff_d = 0.0
    min_pct_pwr = 0.25
  when 'Multi Zone VAV with VSD and SP Setpoint Reset'
    coeff_a = 0.04076
    coeff_b = 0.0881
    coeff_c = -0.0729
    coeff_d = 0.9437
    min_pct_pwr = 0.25
  when 'Multi Zone VAV with AF or BI Riding Curve'
    coeff_a = 0.1631
    coeff_b = 1.5901
    coeff_c = -0.8817
    coeff_d = 0.1281
    min_pct_pwr = 0.7
  when 'Multi Zone VAV with AF or BI with Inlet Vanes'
    coeff_a = 0.9977
    coeff_b = -0.659
    coeff_c = 0.9547
    coeff_d = -0.2936
    min_pct_pwr = 0.5
  when 'Multi Zone VAV with FC Riding Curve'
    coeff_a = 0.1224
    coeff_b = 0.612
    coeff_c = 0.5983
    coeff_d = -0.3334
    min_pct_pwr = 0.3
  when 'Multi Zone VAV with FC with Inlet Vanes'
    coeff_a = 0.3038
    coeff_b = -0.7608
    coeff_c = 2.2729
    coeff_d = -0.8169
    min_pct_pwr = 0.3
  when 'Multi Zone VAV with Vane-axial with Variable Pitch Blades'
    coeff_a = 0.1639
    coeff_b = -0.4016
    coeff_c = 1.9909
    coeff_d = -0.7541
    min_pct_pwr = 0.2
  when 'Multi Zone VAV with VSD and Fixed SP Setpoint'
    coeff_a = 0.0013
    coeff_b = 0.1470
    coeff_c = 0.9506
    coeff_d = -0.0998
    min_pct_pwr = 0.2
  when 'Multi Zone VAV with VSD and Static Pressure Reset'
    coeff_a = 0.04076
    coeff_b = 0.0881
    coeff_c = -0.0729
    coeff_d = 0.9437
    min_pct_pwr = 0.1
  when 'Single Zone VAV Fan'
    coeff_a = 0.027828
    coeff_b = 0.026583
    coeff_c = -0.087069
    coeff_d = 1.030920
    min_pct_pwr = 0.1
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.FanVariableVolume', "Fan control type '#{control_type}' not recognized, fan power coefficients will not be changed.")
    return false
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.FanVariableVolume', "For #{fan_variable_volume.name}: Set fan curve coefficients to reflect control type of '#{control_type}'.")

  # Set the coefficients
  fan_variable_volume.setFanPowerCoefficient1(coeff_a)
  fan_variable_volume.setFanPowerCoefficient2(coeff_b)
  fan_variable_volume.setFanPowerCoefficient3(coeff_c)
  fan_variable_volume.setFanPowerCoefficient4(coeff_d)

  # Set the fan minimum power
  fan_variable_volume.setFanPowerMinimumFlowRateInputMethod('Fraction')
  fan_variable_volume.setFanPowerMinimumFlowFraction(min_pct_pwr)

  # Append the control type to the fan name
  # self.setName("#{self.name} #{control_type}")
  return true
end
fan_zone_exhaust_apply_prototype_fan_pressure_rise(fan_zone_exhaust) click to toggle source

Sets the fan pressure rise based on the Prototype buildings inputs

@param fan_zone_exhaust [OpenStudio::Model::FanZoneExhaust] the exhaust fan @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.FanZoneExhaust.rb, line 10
def fan_zone_exhaust_apply_prototype_fan_pressure_rise(fan_zone_exhaust)
  # Do not modify dummy exhaust fans
  return true if fan_zone_exhaust.name.to_s.downcase.include? 'dummy'

  # All exhaust fans are assumed to have a pressure rise of
  # 0.5 in w.c. in the prototype building models.
  pressure_rise_in_h2o = 0.5

  # Set the pressure rise
  pressure_rise_pa = OpenStudio.convert(pressure_rise_in_h2o, 'inH_{2}O', 'Pa').get
  fan_zone_exhaust.setPressureRise(pressure_rise_pa)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.FanZoneExhaust', "For Prototype: #{fan_zone_exhaust.name}: Pressure Rise = #{pressure_rise_in_h2o}in w.c.")

  return true
end
find_exposed_conditioned_roof_surfaces(model) click to toggle source

This method is similar to the ‘find_exposed_conditioned_vertical_surfaces’ above only it is for roofs. Again, it distinguishes between plenum and non plenum roof area but collects and returns both.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Hash] hash of exposed roof information

# File lib/openstudio-standards/standards/Standards.Surface.rb, line 99
def find_exposed_conditioned_roof_surfaces(model)
  exposed_surfaces = []
  plenum_surfaces = []
  exp_plenum_area = 0
  total_exp_area = 0
  exp_nonplenum_area = 0
  sub_surfaces_info = []
  sub_surface_area = 0
  # Sort through each space and determine if it conditioned.  Conditioned meaning it is either heated, cooled, or both.
  model.getSpaces.sort.each do |space|
    cooled = OpenstudioStandards::Space.space_cooled?(space)
    heated = OpenstudioStandards::Space.space_heated?(space)
    # If the space is conditioned sort through the surfaces looking for outdoor roofs.
    if heated || cooled
      space.surfaces.sort.each do |surface|
        # Assume a roof is of type 'RoofCeiling' and has an 'Outdoors' boundary condition.
        next unless surface.surfaceType == 'RoofCeiling'
        next unless surface.outsideBoundaryCondition == 'Outdoors'

        # Determine if the roof is adjacent to a plenum.
        sub_surface_info = []
        if OpenstudioStandards::Space.space_plenum?(space)
          # If the roof is adjacent to a plenum add it to the plenum roof array and the plenum roof area counter
          # (accounting for space multipliers).
          plenum_surfaces << surface
          exp_plenum_area += surface.grossArea * space.multiplier
        else
          # If the roof is not adjacent to a plenum add it to the non-plenum roof array and the non-plenum roof area
          # counter (accounting for space multipliers).
          exposed_surfaces << surface
          exp_nonplenum_area += surface.grossArea * space.multiplier
          surface.subSurfaces.sort.each do |sub_surface|
            sub_surface_area += sub_surface.grossArea.to_f * space.multiplier
            sub_surface_info << {
              'subsurface_name' => sub_surface.nameString,
              'subsurface_type' => sub_surface.subSurfaceType,
              'gross_area_m2' => sub_surface.grossArea.to_f,
              'construction_name' => sub_surface.construction.get.nameString
            }
          end
          unless sub_surface_info.empty?
            sub_surfaces_info << {
              'surface_name' => surface.nameString,
              'subsurfaces' => sub_surface_info
            }
          end
        end
        # Regardless of if the roof is adjacent to a plenum or not add it to the total roof area counter (accounting
        # for space multipliers).
        total_exp_area += surface.grossArea * space.multiplier
      end
    end
  end
  srr = 999
  unless exp_nonplenum_area < 0.1
    srr = sub_surface_area / exp_nonplenum_area
  end
  # Put the information into a hash and return it to whomever called this method.
  exp_surf_info = {
    'total_exp_roof_area_m2' => total_exp_area,
    'exp_plenum_roof_area_m2' => exp_plenum_area,
    'exp_nonplenum_roof_area_m2' => exp_nonplenum_area,
    'exp_plenum_roofs' => plenum_surfaces,
    'exp_nonplenum_roofs' => exposed_surfaces,
    'srr' => srr,
    'sub_surfaces' => sub_surfaces_info
  }
  return exp_surf_info
end
find_exposed_conditioned_vertical_surfaces(model, max_angle: 91, min_angle: 89) click to toggle source

This method searches through a model a returns vertical exterior surfaces which help enclose a conditioned space. It distinguishes between walls adjacent to plenums and wall adjacent to other conditioned spaces (as attics in OpenStudio are considered plenums and conditioned spaces though many would not agree). It returns a hash of the total exposed wall area adjacent to conditioned spaces (including plenums), the total exposed plenum wall area, the total exposed non-plenum area (adjacent to conditioned spaces), the exposed plenum walls and the exposed non-plenum walls (adjacent to conditioned spaces). @author Chris Kirney @note 2018-09-12

@param model [OpenStudio::Model::Model] OpenStudio model object @param max_angle [Double] maximum angle to consider surface @param min_angle [Double] minimum angle to consider surface @return [Hash] hash of exposed surface information

# File lib/openstudio-standards/standards/Standards.Surface.rb, line 17
def find_exposed_conditioned_vertical_surfaces(model, max_angle: 91, min_angle: 89)
  exposed_surfaces = []
  plenum_surfaces = []
  exp_plenum_area = 0
  total_exp_area = 0
  exp_nonplenum_area = 0
  sub_surfaces_info = []
  sub_surface_area = 0
  # Sort through each space
  model.getSpaces.sort.each do |space|
    # Is the space heated or cooled?
    cooled = OpenstudioStandards::Space.space_cooled?(space)
    heated = OpenstudioStandards::Space.space_heated?(space)
    # Assume conditioned means the space is heated, cooled, or both.
    if heated || cooled
      # If the space is conditioned then go through each surface and determine if it a vertial exterior wall.
      space.surfaces.sort.each do |surface|
        # I define an exterior wall as one that is called a wall and that has a boundary contion of Outdoors.
        # Note that this will not include foundation walls.
        next unless surface.surfaceType == 'Wall'
        next unless surface.outsideBoundaryCondition == 'Outdoors'

        # Determine if the wall is vertical which I define as being between 89 and 91 degrees from horizontal.
        tilt_radian = surface.tilt
        tilt_degrees = OpenStudio.convert(tilt_radian, 'rad', 'deg').get
        sub_surface_info = []
        if tilt_degrees <= max_angle && tilt_degrees >= min_angle
          # If the wall is vertical determine if it is adjacent to a plenum.  If yes include it in the array of
          # plenum walls and add it to the plenum wall area counter (accounting for space multipliers).
          if OpenstudioStandards::Space.space_plenum?(space)
            plenum_surfaces << surface
            exp_plenum_area += surface.grossArea * space.multiplier
          else
            # If not a plenum then include it in the array of non-plenum walls and add it to the non-plenum area
            # counter (accounting for space multipliers).
            exposed_surfaces << surface
            exp_nonplenum_area += surface.grossArea * space.multiplier
            surface.subSurfaces.sort.each do |sub_surface|
              sub_surface_area += sub_surface.grossArea.to_f * space.multiplier
              sub_surface_info << {
                'subsurface_name' => sub_surface.nameString,
                'subsurface_type' => sub_surface.subSurfaceType,
                'gross_area_m2' => sub_surface.grossArea.to_f,
                'construction_name' => sub_surface.construction.get.nameString
              }
            end
            unless sub_surface_info.empty?
              sub_surfaces_info << {
                'surface_name' => surface.nameString,
                'subsurfaces' => sub_surface_info
              }
            end
          end
          # Regardless of if the wall is adjacent to a plenum or not add it to the exposed wall area adjacent to
          # conditioned spaces (accounting for space multipliers).
          total_exp_area += surface.grossArea * space.multiplier
        end
      end
    end
  end
  fdwr = 999
  unless exp_nonplenum_area < 0.1
    fdwr = sub_surface_area / exp_nonplenum_area
  end
  # Add everything into a hash and return that hash to whomever called the method.
  exp_surf_info = {
    'total_exp_wall_area_m2' => total_exp_area,
    'exp_plenum_wall_area_m2' => exp_plenum_area,
    'exp_nonplenum_wall_area_m2' => exp_nonplenum_area,
    'exp_plenum_walls' => plenum_surfaces,
    'exp_nonplenum_walls' => exposed_surfaces,
    'fdwr' => fdwr,
    'sub_surfaces' => sub_surfaces_info
  }
  return exp_surf_info
end
find_highest_roof_centre(model) click to toggle source

This method finds the centroid of the highest roof(s). It cycles through each space and finds which surfaces are described as roofceiling whose outside boundary condition is outdoors. Of those surfaces that do it looks for the highest one(s) and finds the centroid of those.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Hash] It returns the following hash:

roof_cent = {
  top_spaces:  array of spaces which contain the highest roofs,
  roof_centroid:  global x, y, and z coords of the centroid of the highest roof surfaces,
  roof_area:  area of the highst roof surfaces}
Each element of the top_spaces is a hash containing the following:
  top_space = {
    space:  OpenStudio space containing the surface,
    x:  global x coord of the centroid of roof surface(s),
    y:  global y coord of the centroid of roof surface(s),
    z:  global z coord of the centroid of roof surface(s),
    area_m2:  area of the roof surface(s)}
# File lib/openstudio-standards/standards/Standards.Surface.rb, line 186
def find_highest_roof_centre(model)
  # Initialize some variables
  tol = 6
  max_height = -1000000000000000
  top_spaces = []
  spaces_info = []
  roof_centroid = [0, 0, 0]
  # Go through each space looking for outdoor roofs
  model.getSpaces.sort.each do |space|
    outdoor_roof = false
    space_max = -1000000000000000
    max_surf = nil
    space_surfaces = space.surfaces
    # Go through each surface in the space.  If it is an outdoor roofceiling then continue.  Otherwise go to the next
    # space.
    space_surfaces.each do |surface|
      outdoor_roof = true if surface.surfaceType.to_s.upcase == 'ROOFCEILING' && surface.outsideBoundaryCondition.to_s.upcase == 'OUTDOORS'
      # Is this surface the highest roof on this space?
      if surface.centroid.z.to_f.round(tol) > space_max
        space_max = surface.centroid.z.to_f.round(tol)
        max_surf = surface
      end
    end
    # If no outdoor roofceiling go to the next space.
    next if outdoor_roof == false

    z_origin = space.zOrigin.to_f
    ceiling_centroid = [0, 0, 0]

    # Go through the surfaces and look for ones that are the highest.  Any that are the highest get added to the
    # centroid calculation.
    space_surfaces.each do |sp_surface|
      if max_surf.centroid.z.to_f.round(tol) == sp_surface.centroid.z.to_f.round(tol)
        ceiling_centroid[0] += sp_surface.centroid.x.to_f * sp_surface.grossArea.to_f
        ceiling_centroid[1] += sp_surface.centroid.y.to_f * sp_surface.grossArea.to_f
        ceiling_centroid[2] += sp_surface.grossArea.to_f
      end
    end

    # Calculate the centroid of the highest surface/surfaces for this space.
    ceiling_centroid[0] /= ceiling_centroid[2]
    ceiling_centroid[1] /= ceiling_centroid[2]

    # Put the info into an array containing hashes of spaces with outdoor roofceilings
    spaces_info << {
      space: space,
      x: ceiling_centroid[0] + space.xOrigin.to_f,
      y: ceiling_centroid[1] + space.yOrigin.to_f,
      z: max_surf.centroid.z.to_f + z_origin,
      area_m2: ceiling_centroid[2]
    }
    # This is to determine which are the global highest outdoor roofceilings
    if max_height.round(tol) < (max_surf.centroid.z.to_f + z_origin).round(tol)
      max_height = (max_surf.centroid.z.to_f + z_origin).round(tol)
    end
  end
  # Go through the roofceilings and find the highest one(s) and calculate the centroid.
  spaces_info.each do |space_info|
    # If the outdoor roofceiling is one of the highest ones add it to an array of hashes and get the info needed to
    # calculate the centroid
    if space_info[:z].to_f.round(tol) == max_height.round(tol)
      top_spaces << space_info
      roof_centroid[0] += space_info[:x] * space_info[:area_m2]
      roof_centroid[1] += space_info[:y] * space_info[:area_m2]
      roof_centroid[2] += space_info[:area_m2]
    end
  end
  # calculate the centroid of the highest outdoor roofceiling(s) and add the info to a hash to return to whomever
  # called this method.
  roof_centroid[0] /= roof_centroid[2]
  roof_centroid[1] /= roof_centroid[2]
  roof_cent = {
    top_spaces: top_spaces,
    roof_centroid: [roof_centroid[0], roof_centroid[1], max_height],
    roof_area: roof_centroid[2]
  }
  return roof_cent
end
fluid_cooler_apply_minimum_power_per_flow(fluid_cooler, equipment_type: 'Closed Cooling Tower') click to toggle source

Set the fluid cooler fan power such that the tower hits the minimum performance (gpm/hp) specified by the standard. Note that in this case hp is motor nameplate hp, per 90.1. This method assumes that the fan brake horsepower is 90% of the motor nameplate hp. This method determines the minimum motor efficiency for the nameplate motor hp and sets the actual fan power by multiplying the brake horsepower by the efficiency. Thus the fan power used as an input to the simulation divided by the design flow rate will not (and should not) exactly equal the minimum tower performance.

@param fluid_cooler [OpenStudio::Model::FluidCoolerSingleSpeed,

OpenStudio::Model::FluidCoolerTwoSpeed,
OpenStudio::Model::EvaporativeFluidCoolerSingleSpeed,
OpenStudio::Model::EvaporativeFluidCoolerTwoSpeed] the fluid cooler

@param equipment_type [String] heat rejection equipment type enumeration used for lookup query,

options are 'Closed Cooling Tower', modeled as an EvaporativeFluidCooler,
or 'Dry Cooler', modeled as a FluidCooler

@return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.FluidCooler.rb, line 25
def fluid_cooler_apply_minimum_power_per_flow(fluid_cooler, equipment_type: 'Closed Cooling Tower')
  # Get the design water flow rate
  if fluid_cooler.designWaterFlowRate.is_initialized
    design_water_flow_m3_per_s = fluid_cooler.designWaterFlowRate.get
  elsif fluid_cooler.autosizedDesignWaterFlowRate.is_initialized
    design_water_flow_m3_per_s = fluid_cooler.autosizedDesignWaterFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.FluidCooler', "For #{fluid_cooler.name} design water flow rate is not available, cannot apply efficiency standard.")
    return false
  end
  design_water_flow_gpm = OpenStudio.convert(design_water_flow_m3_per_s, 'm^3/s', 'gal/min').get

  # Get the table of fluid cooler efficiencies
  heat_rejection = standards_data['heat_rejection']

  # Define the criteria to find the fluid cooler properties
  # in the hvac standards data set.
  search_criteria = {}
  search_criteria['template'] = template

  # Closed cooling towers are fluidcooler objects.
  search_criteria['equipment_type'] = equipment_type

  # @todo Standards replace this with a mechanism to store this
  # data in the fluid cooler object itself.
  # For now, retrieve the fan type from the name
  name = fluid_cooler.name.get
  if name.include?('Centrifugal')
    fan_type = 'Centrifugal'
  elsif name.include?('Propeller or Axial')
    fan_type = 'Propeller or Axial'
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.FluidCooler', "Cannot find fan type for #{fluid_cooler.name}. Assuming propeller or axial.")
    fan_type = 'Propeller or Axial'
  end
  unless fan_type.nil?
    search_criteria['fan_type'] = fan_type
  end

  # Get the fluid cooler properties
  ct_props = model_find_object(heat_rejection, search_criteria)
  unless ct_props
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.FluidCooler', "For #{fluid_cooler.name}, cannot find heat rejection properties, cannot apply standard efficiencies or curves.")
    return false
  end

  # Get fluid cooler efficiency
  min_gpm_per_hp = ct_props['minimum_performance_gpm_per_hp']
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.FluidCooler', "For #{fluid_cooler.name}, design water flow = #{design_water_flow_gpm.round} gpm, minimum performance = #{min_gpm_per_hp} gpm/hp (nameplate).")

  # Calculate the allowed fan brake horsepower
  # per method used in PNNL prototype buildings.
  # Assumes that the fan brake horsepower is 90%
  # of the fan nameplate rated motor power.
  fan_motor_nameplate_hp = design_water_flow_gpm / min_gpm_per_hp
  fan_bhp = 0.9 * fan_motor_nameplate_hp

  # Lookup the minimum motor efficiency
  motors = standards_data['motors']

  # Assuming all fan motors are 4-pole Enclosed
  search_criteria = {
    'template' => template,
    'number_of_poles' => 4.0,
    'type' => 'Enclosed'
  }

  motor_properties = model_find_object(motors, search_criteria, fan_motor_nameplate_hp)
  if motor_properties.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.FluidCooler', "For #{fluid_cooler.name}, could not find motor properties using search criteria: #{search_criteria}, motor_hp = #{motor_hp} hp.")
    return false
  end

  fan_motor_eff = motor_properties['nominal_full_load_efficiency']
  nominal_hp = motor_properties['maximum_capacity'].to_f.round(1)
  # Round to nearest whole HP for niceness
  if nominal_hp >= 2
    nominal_hp = nominal_hp.round
  end

  # Calculate the fan motor power
  fan_motor_actual_power_hp = fan_bhp / fan_motor_eff
  # Convert to W
  fan_motor_actual_power_w = fan_motor_actual_power_hp * 745.7 # 745.7 W/HP

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.FluidCooler', "For #{fluid_cooler.name}, allowed fan motor nameplate hp = #{fan_motor_nameplate_hp.round(1)} hp, fan brake horsepower = #{fan_bhp.round(1)}, and fan motor actual power = #{fan_motor_actual_power_hp.round(1)} hp (#{fan_motor_actual_power_w.round} W) at #{fan_motor_eff} motor efficiency.")

  # Append the efficiency to the name
  fluid_cooler.setName("#{fluid_cooler.name} #{min_gpm_per_hp.to_f.round(1)} gpm/hp")

  # Hard size the design fan power.
  # Leave the water flow and air flow autosized.
  if fluid_cooler.to_FluidCoolerSingleSpeed.is_initialized
    fluid_cooler.setDesignAirFlowRateFanPower(fan_motor_actual_power_w)
  elsif fluid_cooler.to_FluidCoolerTwoSpeed.is_initialized
    fluid_cooler.setHighFanSpeedFanPower(fan_motor_actual_power_w)
    fluid_cooler.setLowFanSpeedFanPower(0.3 * fan_motor_actual_power_w)
  elsif fluid_cooler.to_EvaporativeFluidCoolerSingleSpeed.is_initialized
    fluid_cooler.setFanPoweratDesignAirFlowRate(fan_motor_actual_power_w)
  elsif fluid_cooler.to_EvaporativeFluidCoolerTwoSpeed.is_initialized
    fluid_cooler.setHighFanSpeedFanPower(fan_motor_actual_power_w)
    fluid_cooler.setLowFanSpeedFanPower(0.3 * fan_motor_actual_power_w)
  end

  return true
end
get_avg_of_other_zones(value_hash, ref_zone) click to toggle source

For a multizone system, get straight average of hash values excluding the reference zone @author Doug Maddox, PNNL @param value_hash [Hash<String>] of zoneName:Value @param ref_zone [String] name of reference zone

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2154
def get_avg_of_other_zones(value_hash, ref_zone)
  num_others = value_hash.size - 1
  value_sum = 0
  value_hash.each do |key, val|
    value_sum += val unless key == ref_zone
  end
  if num_others == 0
    value_avg = value_hash[ref_zone]
  else
    value_avg = value_sum / num_others
  end
  return value_avg
end
get_default_surface_cons_from_surface_type(surface_category, surface_type, cons_set) click to toggle source

Get appropriate construction object based on type of surface or subsurface @author: Doug Maddox, PNNL @param: surface_category [String type of surface: this is not an OpenStudio string @param: surface_type [String SubSurfaceType: this is an OpenStudio string @param: cons_set [object] DefaultSubSurfaceConstructions object @return: [object] Construction object

# File lib/openstudio-standards/standards/Standards.PlanarSurface.rb, line 208
def get_default_surface_cons_from_surface_type(surface_category, surface_type, cons_set)
  # Get DefaultSurfaceContstructions or DefaultSubSurfaceConstructions object
  if surface_category == 'ExteriorSurface'
    cons_list = cons_set.defaultExteriorSurfaceConstructions.get
  elsif surface_category == 'GroundSurface'
    cons_list = cons_set.defaultGroundContactSurfaceConstructions.get
  elsif surface_category == 'ExteriorSubSurface'
    cons_list = cons_set.defaultExteriorSubSurfaceConstructions.get
  else
    cons_list = nil
  end

  cons = nil
  case surface_type
  when 'FixedWindow'
    if cons_list.fixedWindowConstruction.is_initialized
      cons = cons_list.fixedWindowConstruction.get
    end
  when 'OperableWindow'
    if cons_list.operableWindowConstruction.is_initialized
      cons = cons_list.operableWindowConstruction.get
    end
  when 'Door'
    if cons_list.doorConstruction.is_initialized
      cons = cons_list.doorConstruction.get
    end
  when 'GlassDoor'
    if cons_list.glassDoorConstruction.is_initialized
      cons = cons_list.glassDoorConstruction.get
    end
  when 'OverheadDoor'
    if cons_list.overheadDoorConstruction.is_initialized
      cons = cons_list.overheadDoorConstruction.get
    end
  when 'Skylight'
    if cons_list.skylightConstruction.is_initialized
      cons = cons_list.skylightConstruction.get
    end
  when 'TubularDaylightDome'
    if cons_list.tubularDaylightDomeConstruction.is_initialized
      cons = cons_list.tubularDaylightDomeConstruction.get
    end
  when 'TubularDaylightDiffuser'
    if cons_list.tubularDaylightDiffuserConstruction.is_initialized
      cons = cons_list.tubularDaylightDiffuserConstruction.get
    end
  when 'Floor'
    if cons_list.floorConstruction.is_initialized
      cons = cons_list.floorConstruction.get
    end
  when 'Wall'
    if cons_list.wallConstruction.is_initialized
      cons = cons_list.wallConstruction.get
    end
  when 'Roof'
    if cons_list.roofConstruction.is_initialized
      cons = cons_list.roofConstruction.get
    end
  end

  return cons
end
get_fan_object_for_airloop(model, air_loop) click to toggle source

Get the supply fan object for an air loop @author Doug Maddox, PNNL @param model [object] @param air_loop [object] @return [object] supply fan of zone equipment component

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1201
def get_fan_object_for_airloop(model, air_loop)
  if !air_loop.supplyFan.empty?
    fan_component = air_loop.supplyFan.get
  else
    # Check if system has unitary wrapper
    air_loop.supplyComponents.each do |component|
      # Get the object type, getting the internal coil
      # type if inside a unitary system.
      obj_type = component.iddObjectType.valueName.to_s
      fan_component = nil
      case obj_type
      when 'OS_AirLoopHVAC_UnitaryHeatCool_VAVChangeoverBypass'
        component = component.to_AirLoopHVACUnitaryHeatCoolVAVChangeoverBypass.get
        fan_component = component.supplyFan.get
      when 'OS_AirLoopHVAC_UnitaryHeatPump_AirToAir'
        component = component.to_AirLoopHVACUnitaryHeatPumpAirToAir.get
        fan_component = component.supplyFan.get
      when 'OS_AirLoopHVAC_UnitaryHeatPump_AirToAir_MultiSpeed'
        component = component.to_AirLoopHVACUnitaryHeatPumpAirToAirMultiSpeed.get
        fan_component = component.supplyFan.get
      when 'OS_AirLoopHVAC_UnitarySystem'
        component = component.to_AirLoopHVACUnitarySystem.get
        fan_component = component.supplyFan.get
      end

      if !fan_component.nil?
        break
      end
    end
  end

  # Get the fan object for this fan
  fan_obj_type = fan_component.iddObjectType.valueName.to_s
  case fan_obj_type
  when 'OS_Fan_OnOff'
    fan_obj = fan_component.to_FanOnOff.get
  when 'OS_Fan_ConstantVolume'
    fan_obj = fan_component.to_FanConstantVolume.get
  when 'OS_Fan_SystemModel'
    fan_obj = fan_component.to_FanSystemModel.get
  when 'OS_Fan_VariableVolume'
    fan_obj = fan_component.to_FanVariableVolume.get
  end
  return fan_obj
end
get_fan_schedule_for_each_zone(model) click to toggle source

Store fan operation schedule for each zone before deleting HVAC objects @author Doug Maddox, PNNL @param model [object] @return [Hash] of zoneName:fan_schedule_8760

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1126
def get_fan_schedule_for_each_zone(model)
  fan_sch_names = {}

  # Start with air loops
  model.getAirLoopHVACs.sort.each do |air_loop_hvac|
    fan_schedule_8760 = []
    # Check for availability managers
    # Assume only AvailabilityManagerScheduled will control fan schedule
    # @todo also check AvailabilityManagerScheduledOn
    avail_mgrs = air_loop_hvac.availabilityManagers
    # if avail_mgrs.is_initialized
    if !avail_mgrs.nil?
      avail_mgrs.each do |avail_mgr|
        # avail_mgr = avail_mgr.get
        # Check each type of AvailabilityManager
        # If the current one matches, get the fan schedule
        if avail_mgr.to_AvailabilityManagerScheduled.is_initialized
          avail_mgr = avail_mgr.to_AvailabilityManagerScheduled.get
          fan_schedule = avail_mgr.schedule
          # fan_sch_translator = ScheduleTranslator.new(model, fan_schedule)
          # fan_sch_ruleset = fan_sch_translator.translate
          fan_schedule_8760 = OpenstudioStandards::Schedules.schedule_get_hourly_values(fan_schedule)
        end
      end
    end
    if fan_schedule_8760.empty?
      # If there are no availability managers, then use the schedule in the supply fan object
      # Note: testing showed that the fan object schedule is not used by OpenStudio
      # Instead, get the fan schedule from the air_loop_hvac object
      # fan_object = nil
      # fan_object = get_fan_object_for_airloop(model, air_loop_hvac)
      fan_object = 'nothing'
      if !fan_object.nil?
        # fan_schedule = fan_object.availabilitySchedule
        fan_schedule = air_loop_hvac.availabilitySchedule
      else
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Failed to retreive fan object for AirLoop #{air_loop_hvac.name}")
      end
      fan_schedule_8760 = OpenstudioStandards::Schedules.schedule_get_hourly_values(fan_schedule)
    end

    # Assign this schedule to each zone on this air loop
    air_loop_hvac.thermalZones.each do |zone|
      fan_sch_names[zone.name.get] = fan_schedule_8760
    end
  end

  # Handle Zone equipment
  model.getThermalZones.sort.each do |zone|
    if !fan_sch_names.key?(zone.name.get)
      # This zone was not assigned a schedule via air loop
      # Check for zone equipment fans
      zone.equipment.each do |zone_equipment|
        next if zone_equipment.to_FanZoneExhaust.is_initialized

        # get fan schedule
        fan_object = zone_hvac_get_fan_object(zone_equipment)
        if !fan_object.nil?
          fan_schedule = fan_object.availabilitySchedule
          fan_schedule_8760 = OpenstudioStandards::Schedules.schedule_get_hourly_values(fan_schedule)
          fan_sch_names[zone.name.get] = fan_schedule_8760
          break
        end
      end
    end
  end

  return fan_sch_names
end
get_group_heat_types(model, zones) click to toggle source

Get list of heat types across a list of zones @param zones [array of objects] array of zone objects @return [String concatenated string showing different fuel types in a group of zones

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1093
def get_group_heat_types(model, zones)
  heat_list = ''
  has_district_heat = false
  has_fuel_heat = false
  has_electric_heat = false
  zones.each do |zone|
    if OpenstudioStandards::ThermalZone.thermal_zone_district_heat?(zone)
      has_district_heat = true
    end
    if OpenstudioStandards::ThermalZone.thermal_zone_fossil_heat?(zone)
      has_fuel_heat = true
    end
    if OpenstudioStandards::ThermalZone.thermal_zone_electric_heat?(zone)
      has_electric_heat = true
    end
  end

  if has_district_heat
    heat_list = 'districtheating'
  end
  if has_fuel_heat
    heat_list += '_fuel'
  end
  if has_electric_heat
    heat_list += '_electric'
  end
  return heat_list
end
get_outdoor_subsurface_ratio(model, surface_type = 'Wall') click to toggle source

This method return the building ratio of subsurface_area / surface_type_area where surface_type can be “Wall” or “RoofCeiling”

@param model [OpenStudio::Model::Model] OpenStudio model object @param surface_type [String] surface type @return [Double] surface ratio

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5387
def get_outdoor_subsurface_ratio(model, surface_type = 'Wall')
  surface_area = 0.0
  sub_surface_area = 0
  all_surfaces = []
  all_sub_surfaces = []
  model.getSpaces.sort.each do |space|
    zone = space.thermalZone
    zone_multiplier = nil
    next if zone.empty?

    zone_multiplier = zone.get.multiplier
    space.surfaces.sort.each do |surface|
      if (surface.outsideBoundaryCondition == 'Outdoors') && (surface.surfaceType == surface_type)
        surface_area += surface.grossArea * zone_multiplier
        surface.subSurfaces.sort.each do |sub_surface|
          sub_surface_area += sub_surface.grossArea * sub_surface.multiplier * zone_multiplier
        end
      end
    end
  end
  return fdwr = (sub_surface_area / surface_area)
end
get_weekday_values_from_8760(model, values, value_includes_holiday = true) click to toggle source

Return Array of weekday values from Array of all day values @author Xuechen (Jerry) Lei, PNNL @param model [OpenStudio::Model::Model] OpenStudio model object @param values [Array] hourly time-series values of all days @param value_includes_holiday [Boolean] whether the input values include a day of holiday at the end of the array

@return [Array] hourly time-series values in weekdays

# File lib/openstudio-standards/standards/Standards.ScheduleRuleset.rb, line 12
def get_weekday_values_from_8760(model, values, value_includes_holiday = true)
  start_day = model.getYearDescription.dayofWeekforStartDay
  start_day_map = {
    'Sunday' => 0,
    'Monday' => 1,
    'Tuesday' => 2,
    'Wednesday' => 3,
    'Thursday' => 4,
    'Friday' => 5,
    'Saturday' => 6
  }
  start_day_num = start_day_map[start_day]
  weekday_values = []
  day_of_week = start_day_num
  num_of_days = values.size / 24
  if value_includes_holiday
    num_of_days -= 1
  end

  for day_i in 1..num_of_days do
    if day_of_week >= 1 && day_of_week <= 5
      weekday_values += values.slice!(0, 24)
    end
    day_of_week += 1
    # reset day of week
    if day_of_week == 7
      day_of_week = 0
    end
  end

  return weekday_values
end
get_wtd_avg_of_other_zones(value_hash, area_hash, ref_zone) click to toggle source

For a multizone system, get area weighted average of hash values excluding the reference zone @author Doug Maddox, PNNL @param value_hash [Hash<String>] of zoneName:Value @param area_hash [Hash<String>] of zoneName:Area @param ref_zone [String] name of reference zone

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2173
def get_wtd_avg_of_other_zones(value_hash, area_hash, ref_zone)
  num_others = value_hash.size - 1
  value_sum = 0
  area_sum = 0
  value_hash.each do |key, val|
    value_sum += val * area_hash[key] unless key == ref_zone
    area_sum += area_hash[key] unless key == ref_zone
  end
  if num_others == 0
    value_avg = value_hash[ref_zone]
  else
    value_avg = value_sum / area_sum
  end
  return value_avg
end
headered_pumps_variable_speed_set_control_type(headered_pumps_variable_speed, control_type) click to toggle source

Set the pump curve coefficients based on the specified control type.

@param headered_pumps_variable_speed [OpenStudio::Model::HeaderedPumpsVariableSpeed] headered variable speed pumps object @param control_type [String] valid choices are Riding Curve, VSD No Reset, VSD DP Reset @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.HeaderedPumpsVariableSpeed.rb, line 11
def headered_pumps_variable_speed_set_control_type(headered_pumps_variable_speed, control_type)
  # Determine the coefficients
  coeff_a = nil
  coeff_b = nil
  coeff_c = nil
  coeff_d = nil
  case control_type
  when 'Constant Flow'
    coeff_a = 0.0
    coeff_b = 1.0
    coeff_c = 0.0
    coeff_d = 0.0
  when 'Riding Curve'
    coeff_a = 0.0
    coeff_b = 3.2485
    coeff_c = -4.7443
    coeff_d = 2.5294
  when 'VSD No Reset'
    coeff_a = 0.0
    coeff_b = 0.5726
    coeff_c = -0.301
    coeff_d = 0.7347
  when 'VSD DP Reset'
    coeff_a = 0.0
    coeff_b = 0.0205
    coeff_c = 0.4101
    coeff_d = 0.5753
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.HeaderedPumpsVariableSpeed', "Pump control type '#{control_type}' not recognized, pump coefficients will not be changed.")
    return false
  end

  # Set the coefficients
  headered_pumps_variable_speed.setCoefficient1ofthePartLoadPerformanceCurve(coeff_a)
  headered_pumps_variable_speed.setCoefficient2ofthePartLoadPerformanceCurve(coeff_b)
  headered_pumps_variable_speed.setCoefficient3ofthePartLoadPerformanceCurve(coeff_c)
  headered_pumps_variable_speed.setCoefficient4ofthePartLoadPerformanceCurve(coeff_d)
  headered_pumps_variable_speed.setPumpControlType('Intermittent')

  # Append the control type to the pump name
  # self.setName("#{self.name} #{control_type}")

  return true
end
heat_exchanger_air_to_air_sensible_and_latent_apply_effectiveness(heat_exchanger_air_to_air_sensible_and_latent) click to toggle source

Sets the minimum effectiveness of the heat exchanger per the standard.

@param heat_exchanger_air_to_air_sensible_and_latent [OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent] the heat exchanger @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.HeatExchangerSensLat.rb, line 8
def heat_exchanger_air_to_air_sensible_and_latent_apply_effectiveness(heat_exchanger_air_to_air_sensible_and_latent)
  # Assumed to be sensible and latent at all flow
  full_htg_sens_eff, full_htg_lat_eff, part_htg_sens_eff, part_htg_lat_eff, full_cool_sens_eff, full_cool_lat_eff, part_cool_sens_eff, part_cool_lat_eff = heat_exchanger_air_to_air_sensible_and_latent_minimum_effectiveness(heat_exchanger_air_to_air_sensible_and_latent)

  heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat100HeatingAirFlow(full_htg_sens_eff)
  heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat100HeatingAirFlow(full_htg_lat_eff)
  heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat100CoolingAirFlow(full_cool_sens_eff)
  heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat100CoolingAirFlow(full_cool_lat_eff)
  if heat_exchanger_air_to_air_sensible_and_latent.model.version < OpenStudio::VersionString.new('3.8.0')
    heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75HeatingAirFlow(part_htg_sens_eff)
    heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75HeatingAirFlow(part_htg_lat_eff)
    heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75CoolingAirFlow(part_cool_sens_eff)
    heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75CoolingAirFlow(part_cool_lat_eff)
  else
    heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75HeatingAirFlow(part_htg_sens_eff) unless part_htg_sens_eff.zero?
    heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75HeatingAirFlow(part_htg_lat_eff) unless part_htg_lat_eff.zero?
    heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75CoolingAirFlow(part_cool_sens_eff) unless part_cool_sens_eff.zero?
    heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75CoolingAirFlow(part_cool_lat_eff) unless part_cool_lat_eff.zero?
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.HeatExchangerSensLat', "For #{heat_exchanger_air_to_air_sensible_and_latent.name}: Set sensible and latent effectiveness.")

  return true
end
heat_exchanger_air_to_air_sensible_and_latent_apply_prototype_efficiency(heat_exchanger_air_to_air_sensible_and_latent) click to toggle source

Sets the minimum effectiveness of the heat exchanger per the DOE prototype assumptions, which assume that an enthalpy wheel is used, which exceeds the 50% effectiveness minimum actually defined by 90.1.

@param heat_exchanger_air_to_air_sensible_and_latent [OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent] hx @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.HeatExchangerAirToAirSensibleAndLatent.rb, line 81
def heat_exchanger_air_to_air_sensible_and_latent_apply_prototype_efficiency(heat_exchanger_air_to_air_sensible_and_latent)
  heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat100HeatingAirFlow(0.7)
  heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat100HeatingAirFlow(0.6)
  heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75HeatingAirFlow(0.7)
  heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75HeatingAirFlow(0.6)
  heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat100CoolingAirFlow(0.75)
  heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat100CoolingAirFlow(0.6)
  heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75CoolingAirFlow(0.75)
  heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75CoolingAirFlow(0.6)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.HeatExchangerAirToAirSensibleAndLatent', "For #{heat_exchanger_air_to_air_sensible_and_latent.name}: Changed sensible and latent effectiveness to ~70% per DOE Prototype assumptions for an enthalpy wheel.")

  return true
end
heat_exchanger_air_to_air_sensible_and_latent_apply_prototype_efficiency_enthalpy_recovery_ratio(heat_exchanger_air_to_air_sensible_and_latent, enthalpy_recovery_ratio, design_conditions, climate_zone) click to toggle source

Set sensible and latent effectiveness at 100 and 75 heating and cooling airflow; The values are calculated by using ERR, which is introduced in 90.1-2016 Addendum CE

This function is only used for nontransient dwelling units (Mid-rise and High-rise Apartment) @param heat_exchanger_air_to_air_sensible_and_latent [OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent] heat exchanger air to air sensible and latent @param enthalpy_recovery_ratio [String] enthalpy recovery ratio @param design_conditions [String] enthalpy recovery ratio design conditions: ‘heating’ or ‘cooling’ @param climate_zone [String] climate zone

# File lib/openstudio-standards/prototypes/common/objects/Prototype.HeatExchangerAirToAirSensibleAndLatent.rb, line 104
def heat_exchanger_air_to_air_sensible_and_latent_apply_prototype_efficiency_enthalpy_recovery_ratio(heat_exchanger_air_to_air_sensible_and_latent, enthalpy_recovery_ratio, design_conditions, climate_zone)
  # Assumed to be sensible and latent at all flow
  if enthalpy_recovery_ratio.nil?
    full_htg_sens_eff = 0.0
    full_htg_lat_eff = 0.0
    part_htg_sens_eff = 0.0
    part_htg_lat_eff = 0.0
    full_cool_sens_eff = 0.0
    full_cool_lat_eff = 0.0
    part_cool_sens_eff = 0.0
    part_cool_lat_eff = 0.0
  else
    enthalpy_recovery_ratio = enthalpy_recovery_ratio_design_to_typical_adjustment(enthalpy_recovery_ratio, climate_zone)
    full_htg_sens_eff, full_htg_lat_eff, part_htg_sens_eff, part_htg_lat_eff, full_cool_sens_eff, full_cool_lat_eff, part_cool_sens_eff, part_cool_lat_eff = heat_exchanger_air_to_air_sensible_and_latent_enthalpy_recovery_ratio_to_effectiveness(enthalpy_recovery_ratio, design_conditions)
  end

  heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat100HeatingAirFlow(full_htg_sens_eff)
  heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat100HeatingAirFlow(full_htg_lat_eff)
  heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat100CoolingAirFlow(full_cool_sens_eff)
  heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat100CoolingAirFlow(full_cool_lat_eff)
  if model.version < OpenStudio::VersionString.new('3.8.0')
    heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75HeatingAirFlow(part_htg_sens_eff)
    heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75HeatingAirFlow(part_htg_lat_eff)
    heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75CoolingAirFlow(part_cool_sens_eff)
    heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75CoolingAirFlow(part_cool_lat_eff)
  else
    heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75HeatingAirFlow(part_htg_sens_eff) unless part_htg_sens_eff.zero?
    heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75HeatingAirFlow(part_htg_lat_eff) unless part_htg_lat_eff.zero?
    heat_exchanger_air_to_air_sensible_and_latent.setSensibleEffectivenessat75CoolingAirFlow(part_cool_sens_eff) unless part_cool_sens_eff.zero?
    heat_exchanger_air_to_air_sensible_and_latent.setLatentEffectivenessat75CoolingAirFlow(part_cool_lat_eff) unless part_cool_lat_eff.zero?
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.HeatExchangerSensLat', "For #{heat_exchanger_air_to_air_sensible_and_latent.name}: Set sensible and latent effectiveness calculated by using ERR.")
  return true
end
heat_exchanger_air_to_air_sensible_and_latent_apply_prototype_nominal_electric_power(heat_exchanger_air_to_air_sensible_and_latent) click to toggle source

Sets the motor power to account for the extra fan energy from the increase in fan total static pressure

@return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.HeatExchangerAirToAirSensibleAndLatent.rb, line 15
def heat_exchanger_air_to_air_sensible_and_latent_apply_prototype_nominal_electric_power(heat_exchanger_air_to_air_sensible_and_latent)
  # Get the nominal supply air flow rate
  supply_air_flow_m3_per_s = nil
  if heat_exchanger_air_to_air_sensible_and_latent.nominalSupplyAirFlowRate.is_initialized
    supply_air_flow_m3_per_s = heat_exchanger_air_to_air_sensible_and_latent.nominalSupplyAirFlowRate.get
  elsif heat_exchanger_air_to_air_sensible_and_latent.autosizedNominalSupplyAirFlowRate.is_initialized
    supply_air_flow_m3_per_s = heat_exchanger_air_to_air_sensible_and_latent.autosizedNominalSupplyAirFlowRate.get
  else
    # Get the min OA flow rate from the OA
    # system if the ERV was not on the system during sizing.
    # This prevents us from having to perform a second sizing run.
    controller_oa = nil
    oa_system = nil
    # Get the air loop
    air_loop = heat_exchanger_air_to_air_sensible_and_latent.airLoopHVAC
    if air_loop.empty?
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.HeatExchangerAirToAirSensibleAndLatent', "For #{heat_exchanger_air_to_air_sensible_and_latent.name}, cannot get the air loop and therefore cannot get the min OA flow.")
      return false
    end
    air_loop = air_loop.get
    # Get the OA system
    if air_loop.airLoopHVACOutdoorAirSystem.is_initialized
      oa_system = air_loop.airLoopHVACOutdoorAirSystem.get
      controller_oa = oa_system.getControllerOutdoorAir
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.HeatExchangerAirToAirSensibleAndLatent', "For #{heat_exchanger_air_to_air_sensible_and_latent.name}, cannot find the min OA flow because it has no OA intake.")
      return false
    end
    # Get the min OA flow rate from the OA
    if controller_oa.minimumOutdoorAirFlowRate.is_initialized
      supply_air_flow_m3_per_s = controller_oa.minimumOutdoorAirFlowRate.get
    elsif controller_oa.autosizedMinimumOutdoorAirFlowRate.is_initialized
      supply_air_flow_m3_per_s = controller_oa.autosizedMinimumOutdoorAirFlowRate.get
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.HeatExchangerAirToAirSensibleAndLatent', "For #{heat_exchanger_air_to_air_sensible_and_latent.name}, ERV minimum OA flow rate is not available, cannot apply prototype nominal power assumption.")
      return false
    end
  end

  # Convert the flow rate to cfm
  supply_air_flow_cfm = OpenStudio.convert(supply_air_flow_m3_per_s, 'm^3/s', 'cfm').get

  # Calculate the motor power for the rotary wheel per:
  # Power (W) = (Nominal Supply Air Flow Rate (CFM) * 0.3386) + 49.5
  # power = (supply_air_flow_cfm * 0.3386) + 49.5

  # Calculate the motor power for the rotary wheel per:
  # Power (W) = (Minimum Outdoor Air Flow Rate (m^3/s) * 212.5 / 0.5) + (Minimum Outdoor Air Flow Rate (m^3/s) * 162.5 / 0.5) + 50
  # This power is largely the added fan power from the extra static pressure drop from the enthalpy wheel.
  # It is included as motor power so it is only added when the enthalpy wheel is active, rather than a universal increase to the fan total static pressure.
  # From p.96 of https://www.pnnl.gov/main/publications/external/technical_reports/PNNL-20405.pdf
  default_fan_efficiency = heat_exchanger_air_to_air_sensible_and_latent_prototype_default_fan_efficiency
  power = (supply_air_flow_m3_per_s * 212.5 / default_fan_efficiency) + (supply_air_flow_m3_per_s * 0.9 * 162.5 / default_fan_efficiency) + 50
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.HeatExchangerAirToAirSensibleAndLatent', "For #{heat_exchanger_air_to_air_sensible_and_latent.name}, ERV power is calculated to be #{power.round} W, based on a min OA flow of #{supply_air_flow_cfm.round} cfm.  This power represents mostly the added fan energy from the extra static pressure, and is active only when the ERV is operating.")

  # Set the power for the HX
  heat_exchanger_air_to_air_sensible_and_latent.setNominalElectricPower(power)

  return true
end
heat_exchanger_air_to_air_sensible_and_latent_enthalpy_recovery_ratio_to_effectiveness(enthalpy_recovery_ratio, design_conditions) click to toggle source

Calculate a heat exchanger’s effectiveness for a specific ERR and design conditions. Regressions were determined based available manufacturer data.

@param enthalpy_recovery_ratio [float] Enthalpy Recovery Ratio (ERR) @param design_conditions [String] design_conditions for effectiveness calculation, either ‘cooling’ or ‘heating’ @return [Array] heating and cooling heat exchanger effectiveness at 100% and 75% nominal airflow

# File lib/openstudio-standards/standards/Standards.HeatExchangerSensLat.rb, line 75
def heat_exchanger_air_to_air_sensible_and_latent_enthalpy_recovery_ratio_to_effectiveness(enthalpy_recovery_ratio, design_conditions)
  case design_conditions
    when 'cooling'
      full_htg_sens_eff = (20.707 * enthalpy_recovery_ratio**2 + 41.354 * enthalpy_recovery_ratio + 40.755) / 100
      full_htg_lat_eff = (127.45 * enthalpy_recovery_ratio - 18.625) / 100
      part_htg_sens_eff = (-0.1214 * enthalpy_recovery_ratio + 1.111) * full_htg_sens_eff
      part_htg_lat_eff = (-0.3405 * enthalpy_recovery_ratio + 1.2732) * full_htg_lat_eff
      full_cool_sens_eff = (70.689 * enthalpy_recovery_ratio + 30.789) / 100
      full_cool_lat_eff = (48.054 * enthalpy_recovery_ratio**2 + 83.082 * enthalpy_recovery_ratio - 12.881) / 100
      part_cool_sens_eff = (-0.1214 * enthalpy_recovery_ratio + 1.111) * full_cool_sens_eff
      part_cool_lat_eff = (-0.3982 * enthalpy_recovery_ratio  + 1.3151) * full_cool_lat_eff
    when 'heating'
      full_htg_sens_eff = enthalpy_recovery_ratio
      full_htg_lat_eff = 0.0
      part_htg_sens_eff = (-0.1214 * enthalpy_recovery_ratio + 1.111) * full_htg_sens_eff
      part_htg_lat_eff = 0.0
      full_cool_sens_eff = enthalpy_recovery_ratio * (70.689 * enthalpy_recovery_ratio + 30.789) / (20.707 * enthalpy_recovery_ratio**2 + 41.354 * enthalpy_recovery_ratio + 40.755)
      full_cool_lat_eff = 0.0
      part_cool_sens_eff = (-0.1214 * enthalpy_recovery_ratio + 1.111) * full_cool_sens_eff
      part_cool_lat_eff = 0.0
  end

  return full_htg_sens_eff, full_htg_lat_eff, part_htg_sens_eff, part_htg_lat_eff, full_cool_sens_eff, full_cool_lat_eff, part_cool_sens_eff, part_cool_lat_eff
end
heat_exchanger_air_to_air_sensible_and_latent_minimum_effectiveness(heat_exchanger_air_to_air_sensible_and_latent) click to toggle source

Defines the minimum sensible and latent effectiveness of the heat exchanger. Assumed to apply to sensible and latent effectiveness at all flow rates.

@param heat_exchanger_air_to_air_sensible_and_latent [OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent] the heat exchanger @return [Array] List of full and part load heat echanger effectiveness

# File lib/openstudio-standards/standards/Standards.HeatExchangerSensLat.rb, line 38
def heat_exchanger_air_to_air_sensible_and_latent_minimum_effectiveness(heat_exchanger_air_to_air_sensible_and_latent)
  full_htg_sens_eff = 0.5
  full_htg_lat_eff = 0.5
  part_htg_sens_eff = 0.5
  part_htg_lat_eff = 0.5
  full_cool_sens_eff = 0.5
  full_cool_lat_eff = 0.5
  part_cool_sens_eff = 0.5
  part_cool_lat_eff = 0.5

  return full_htg_sens_eff, full_htg_lat_eff, part_htg_sens_eff, part_htg_lat_eff, full_cool_sens_eff, full_cool_lat_eff, part_cool_sens_eff, part_cool_lat_eff
end
heat_exchanger_air_to_air_sensible_and_latent_prototype_default_fan_efficiency() click to toggle source

Default fan efficiency assumption for the prm added fan power

@return [Double] default fan efficiency

# File lib/openstudio-standards/prototypes/common/objects/Prototype.HeatExchangerAirToAirSensibleAndLatent.rb, line 7
def heat_exchanger_air_to_air_sensible_and_latent_prototype_default_fan_efficiency
  default_fan_efficiency = 0.5
  return default_fan_efficiency
end
hspf_to_cop(hspf) click to toggle source

Convert from HSPF to COP (with fan) for heat pump heating coils @ref ASHRAE RP-1197

@param hspf [Double] heating seasonal performance factor (HSPF) @return [Double] Coefficient of Performance (COP)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 318
def hspf_to_cop(hspf)
  cop = -0.0255 * hspf * hspf + 0.6239 * hspf

  return cop
end
hspf_to_cop_no_fan(hspf) click to toggle source

Convert from HSPF to COP (no fan) for heat pump heating coils @ref [References::ASHRAE9012013] Appendix G

@param hspf [Double] heating seasonal performance factor (HSPF) @return [Double] Coefficient of Performance (COP)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 307
def hspf_to_cop_no_fan(hspf)
  cop = -0.0296 * hspf * hspf + 0.7134 * hspf

  return cop
end
interior_lighting_get_prm_data(space_type) click to toggle source
# File lib/openstudio-standards/standards/Standards.SpaceType.rb, line 34
def interior_lighting_get_prm_data(space_type)
  standards_space_type = if space_type.is_a? String
                           space_type
                         elsif space_type.standardsSpaceType.is_initialized
                           space_type.standardsSpaceType.get
                         end

  # populate search hash
  search_criteria = {
    'template' => template,
    'lpd_space_type' => standards_space_type
  }

  # lookup space type properties
  interior_lighting_properties = model_find_object(standards_data['prm_interior_lighting'], search_criteria)

  if interior_lighting_properties.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.SpaceType', "Interior lighting PRM properties lookup failed: #{search_criteria}. Trying to search with primary_space_type. It is highly recommended to update the standard space type to one of the lighting types listed in: https://pnnl.github.io/BEM-for-PRM/user_guide/model_requirements/standards_space_type/")
    search_criteria = {
      'template' => template,
      'primary_space_type' => standards_space_type
    }
    interior_lighting_properties = model_find_object(standards_data['prm_interior_lighting'], search_criteria)
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.SpaceType', "Interior Lighting PRM properties lookup failed: #{search_criteria}")
    interior_lighting_properties = {}
  end

  return interior_lighting_properties
end
kw_per_ton_to_cop(kw_per_ton) click to toggle source

A helper method to convert from kW/ton to COP

@param kw_per_ton [Double] kW of input power per ton of cooling @return [Double] Coefficient of Performance (COP)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 398
def kw_per_ton_to_cop(kw_per_ton)
  return 3.517 / kw_per_ton
end
load_hvac_map(hvac_map_file) click to toggle source

Loads a JSON file containing the space type map into a hash

@param hvac_map_file [String] path to JSON file, relative to the /data folder @return [Hash] returns a hash that contains the space type map

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 221
def load_hvac_map(hvac_map_file)
  # Load the geometry .osm from relative to the data folder
  rel_path_to_hvac_map = "../../../../../data/#{hvac_map_file}"

  # Load the JSON depending on whether running from normal gem location
  # or from the embedded location in the OpenStudio CLI
  if File.dirname(__FILE__)[0] == ':'
    # running from embedded location in OpenStudio CLI
    hvac_map_string = load_resource_relative(rel_path_to_hvac_map)
    hvac_map = JSON.parse(hvac_map_string)
  else
    abs_path = File.join(File.dirname(__FILE__), rel_path_to_hvac_map)
    hvac_map = JSON.parse(File.read(abs_path)) if File.exist?(abs_path)
  end

  return hvac_map
end
load_initial_osm(osm_file) click to toggle source

Loads a osm as a starting point.

@param osm_file [String] path to the .osm file, relative to the /data folder @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5414
def load_initial_osm(osm_file)
  # Load the geometry .osm
  unless File.exist?(osm_file)
    raise("The initial osm path: #{osm_file} does not exist.")
  end

  osm_model_path = OpenStudio::Path.new(osm_file.to_s)
  # Upgrade version if required.
  version_translator = OpenStudio::OSVersion::VersionTranslator.new
  model = version_translator.loadModel(osm_model_path).get
  validate_initial_model(model)
  return model
end
load_standards_database(data_directories = []) click to toggle source

Loads the openstudio standards dataset for this standard. For standards subclassed from other standards, the lowest-level data will override data supplied at a higher level. For example, data from ASHRAE 90.1-2004 will be overridden by data from ComStock ASHRAE 90.1-2004.

@param data_directories [Array<String>] array of file paths that contain standards data @return [Hash] a hash of standards data

# File lib/openstudio-standards/standards/standard.rb, line 86
def load_standards_database(data_directories = [])
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.standard', "Loading OpenStudio Standards data for #{template}")
  @standards_data = {}

  # Load the JSON files from each directory
  data_directories.each do |data_dir|
    if __dir__[0] == ':' # Running from OpenStudio CLI
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.standard', "Loading JSON files from OpenStudio CLI embedded directory #{data_dir}")
      EmbeddedScripting.allFileNamesAsString.split(';').each do |file|
        # Skip files outside of the specified directory
        next unless file.start_with?("#{data_dir}/data")

        # Skip files that are not JSON
        next unless File.basename(file).match(/.*\.json/)

        # Read the JSON file
        data = JSON.parse(EmbeddedScripting.getFileAsString(file))
        data.each_pair do |key, objs|
          # Override the template in inherited files to match the instantiated template
          objs.each do |obj|
            if obj.key?('template')
              obj['template'] = template
            end
          end
          if @standards_data[key].nil?
            OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.standard', "Adding #{key} from #{File.basename(file)}")
          else
            OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.standard', "Overriding #{key} with #{File.basename(file)}")
          end
          @standards_data[key] = objs
        end
      end
    else
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.standard', "Loading JSON files from #{data_dir}")
      files = Dir.glob("#{data_dir}/data/*.json").select { |e| File.file? e }
      files.each do |file|
        data = JSON.parse(File.read(file))
        data.each_pair do |key, objs|
          # Override the template in inherited files to match the instantiated template
          objs.each do |obj|
            if obj.key?('template')
              obj['template'] = template
            end
          end
          if @standards_data[key].nil?
            OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.standard', "Adding #{key} from #{File.basename(file)}")
          else
            OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.standard', "Overriding #{key} with #{File.basename(file)}")
          end
          @standards_data[key] = objs
        end
      end
    end
  end

  # Check that standards data was loaded
  if @standards_data.keys.size.zero?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.standard', "OpenStudio Standards JSON data was not loaded correctly for #{template}.")
  end
  return @standards_data
end
make_ruleset_sched_from_8760(model, values, sch_name, sch_type_limits) click to toggle source

Create a ScheduleRuleset object from an 8760 sequential array of values for a Values array will actually include 24 extra values if model year is a leap year Values array will also include 24 values at end of array representing the holiday day schedule @author Doug Maddox, PNNL @param model [Object] @param values [Array<Double>] array of annual values (8760 +/ 24) + holiday values (24) @param sch_name [String] name of schedule to be created @param sch_type_limits [Object] ScheduleTypeLimits object @return [Object] ScheduleRuleset

# File lib/openstudio-standards/standards/Standards.ScheduleRuleset.rb, line 54
def make_ruleset_sched_from_8760(model, values, sch_name, sch_type_limits)
  # Build array of arrays: each top element is a week, each sub element is an hour of week
  all_week_values = []
  hr_of_yr = -1
  (0..51).each do |iweek|
    week_values = []
    (0..167).each do |hr_of_wk|
      hr_of_yr += 1
      week_values[hr_of_wk] = values[hr_of_yr]
    end
    all_week_values << week_values
  end

  # Extra week for days 365 and 366 (if applicable) of year
  # since 52 weeks is 364 days
  hr_of_yr += 1
  last_hr = values.size - 1
  iweek = 52
  week_values = []
  hr_of_wk = -1
  (hr_of_yr..last_hr).each do |ihr_of_yr|
    hr_of_wk += 1
    week_values[hr_of_wk] = values[ihr_of_yr]
  end
  all_week_values << week_values

  # Build ruleset schedules for first week
  yd = model.getYearDescription
  start_date = yd.makeDate(1, 1)
  one_day = OpenStudio::Time.new(1.0)
  seven_days = OpenStudio::Time.new(7.0)
  end_date = start_date + seven_days - one_day

  # Create new ruleset schedule
  sch_ruleset = OpenStudio::Model::ScheduleRuleset.new(model)
  sch_ruleset.setName(sch_name)
  sch_ruleset.setScheduleTypeLimits(sch_type_limits)

  # Make week schedule for first week
  num_week_scheds = 1
  week_sch_name = sch_name + '_ws' + num_week_scheds.to_s
  week_1_rules = make_week_ruleset_sched_from_168(model, sch_ruleset, all_week_values[1], start_date, end_date, week_sch_name)
  week_n_rules = week_1_rules
  all_week_rules = []
  all_week_rules << week_1_rules
  iweek_previous_week_rule = 0

  # temporary loop for debugging
  week_n_rules.each do |sch_rule|
    day_rule = sch_rule.daySchedule
    xtest = 1
  end

  # For each subsequent week, check if it is same as previous
  # If same, then append to Schedule:Rule of previous week
  # If different, then create new Schedule:Rule
  (1..51).each do |iweek|
    is_a_match = true
    start_date = end_date + one_day
    end_date += seven_days
    (0..167).each do |ihr|
      if all_week_values[iweek][ihr] != all_week_values[iweek_previous_week_rule][ihr]
        is_a_match = false
        break
      end
    end
    if is_a_match
      # Update the end date for the Rules of the previous week to include this week
      all_week_rules[iweek_previous_week_rule].each do |sch_rule|
        sch_rule.setEndDate(end_date)
      end
    else
      # Create a new week schedule for this week
      num_week_scheds += 1
      week_sch_name = sch_name + '_ws' + num_week_scheds.to_s
      week_n_rules = make_week_ruleset_sched_from_168(model, sch_ruleset, all_week_values[iweek], start_date, end_date, week_sch_name)
      all_week_rules << week_n_rules
      # Set this week as the reference for subsequent weeks
      iweek_previous_week_rule = iweek
    end
  end

  # temporary loop for debugging
  week_n_rules.each do |sch_rule|
    day_rule = sch_rule.daySchedule
    xtest = 1
  end

  # Need to handle week 52 with days 365 and 366
  # For each of these days, check if it matches a day from the previous week
  iweek = 52
  # First handle day 365
  end_date += one_day
  start_date = end_date
  match_was_found = false
  # week_n is the previous week
  week_n_rules.each do |sch_rule|
    day_rule = sch_rule.daySchedule
    is_match = true
    # Need a 24 hour array of values for the day rule
    ihr_start = 0
    day_values = []
    day_rule.times.each do |time|
      now_value = day_rule.getValue(time).to_f
      until_ihr = time.totalHours.to_i - 1
      (ihr_start..until_ihr).each do |ihr|
        day_values << now_value
      end
    end
    (0..23).each do |ihr|
      if day_values[ihr] != all_week_values[iweek][ihr + ihr_start]
        # not matching for this day_rule
        is_match = false
        break
      end
    end
    if is_match
      match_was_found = true
      # Extend the schedule period to include this day
      sch_rule.setEndDate(end_date)
      break
    end
  end
  if match_was_found == false
    # Need to add a new rule
    day_of_week = start_date.dayOfWeek.valueName
    day_names = [day_of_week]
    day_sch_name = sch_name + '_Day_365'
    day_sch_values = []
    (0..23).each do |ihr|
      day_sch_values << all_week_values[iweek][ihr]
    end
    # sch_rule is a sub-component of the ScheduleRuleset
    sch_rule = OpenstudioStandards::Schedules.schedule_ruleset_add_rule(sch_ruleset, day_sch_values,
                                                                        start_date: start_date,
                                                                        end_date: end_date,
                                                                        day_names: day_names,
                                                                        rule_name: day_sch_name)
    week_n_rules = sch_rule
  end

  # Handle day 366, if leap year
  # Last day in this week is the holiday schedule
  # If there are three days in this week, then the second is day 366
  if all_week_values[iweek].size == 24 * 3
    ihr_start = 23
    end_date += one_day
    start_date = end_date
    match_was_found = false
    # week_n is the previous week
    # which would be the week based on day 356, if that was its own week
    week_n_rules.each do |sch_rule|
      day_rule = sch_rule.daySchedule
      is_match = true
      day_rule.times.each do |ihr|
        if day_rule.getValue(ihr).to_f != all_week_values[iweek][ihr + ihr_start]
          # not matching for this day_rule
          is_match = false
          break
        end
      end
      if is_match
        match_was_found = true
        # Extend the schedule period to include this day
        sch_rule.setEndDate(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(end_date.month.to_i), end_date.day.to_i))
        break
      end
    end
    if match_was_found == false
      # Need to add a new rule
      # sch_rule is a sub-component of the ScheduleRuleset

      day_of_week = start_date.dayOfWeek.valueName
      day_names = [day_of_week]
      day_sch_name = sch_name + '_Day_366'
      day_sch_values = []
      (0..23).each do |ihr|
        day_sch_values << all_week_values[iweek][ihr]
      end
      sch_rule = OpenstudioStandards::Schedules.schedule_ruleset_add_rule(sch_ruleset, day_sch_values,
                                                                          start_date: start_date,
                                                                          end_date: end_date,
                                                                          day_names: day_names,
                                                                          rule_name: day_sch_name)
      week_n_rules = sch_rule
    end

    # Last day in values array is the holiday schedule
    # @todo add holiday schedule when implemented in OpenStudio SDK
  end

  # Need to handle design days
  # Find schedule with the most operating hours in a day,
  # and apply that to both cooling and heating design days
  hr_of_yr = -1
  max_eflh = 0
  ihr_max = -1
  (0..364).each do |iday|
    eflh = 0
    ihr_start = hr_of_yr + 1
    (0..23).each do |ihr|
      hr_of_yr += 1
      eflh += 1 if values[hr_of_yr] > 0
    end
    if eflh > max_eflh
      max_eflh = eflh
      # store index to first hour of day with max on hours
      ihr_max = ihr_start
    end
  end
  # Create the schedules for the design days
  day_sch = OpenStudio::Model::ScheduleDay.new(model)
  day_sch.setName(sch_name + 'Winter Design Day')
  (0..23).each do |ihr|
    hr_of_yr = ihr_max + ihr
    next if values[hr_of_yr] == values[hr_of_yr + 1]

    day_sch.addValue(OpenStudio::Time.new(0, ihr + 1, 0, 0), values[hr_of_yr])
  end
  sch_ruleset.setWinterDesignDaySchedule(day_sch)

  day_sch = OpenStudio::Model::ScheduleDay.new(model)
  day_sch.setName(sch_name + 'Summer Design Day')
  (0..23).each do |ihr|
    hr_of_yr = ihr_max + ihr
    next if values[hr_of_yr] == values[hr_of_yr + 1]

    day_sch.addValue(OpenStudio::Time.new(0, ihr + 1, 0, 0), values[hr_of_yr])
  end
  sch_ruleset.setSummerDesignDaySchedule(day_sch)

  return sch_ruleset
end
make_week_ruleset_sched_from_168(model, sch_ruleset, values, start_date, end_date, sch_name) click to toggle source

Create a ScheduleRules object from an hourly array of values for a week @author Doug Maddox, PNNL @param model [Object] @param sch_ruleset [Object] ScheduleRuleset object @param values [Array<Double>] array of hourly values for week (168) @param start_date [Date] start date of week period @param end_date [Date] end date of week period @param sch_name [String] name of parent ScheduleRuleset object @return [Array<Object>] array of ScheduleRules objects

# File lib/openstudio-standards/standards/Standards.ScheduleRuleset.rb, line 297
def make_week_ruleset_sched_from_168(model, sch_ruleset, values, start_date, end_date, sch_name)
  one_day = OpenStudio::Time.new(1.0)
  now_date = start_date - one_day
  days_of_week = []
  values_by_day = []
  # Organize data into days
  # create a 2-D array values_by_day[iday][ihr]
  hr_of_wk = -1
  (0..6).each do |iday|
    hr_values = []
    (0..23).each do |hr_of_day|
      hr_of_wk += 1
      hr_values << values[hr_of_wk]
    end
    values_by_day << hr_values
    now_date += one_day
    days_of_week << now_date.dayOfWeek.valueName
  end

  # Make list of unique day schedules
  # First one is automatically unique
  # Store indexes to days with the same sched in array of arrays
  # day_sched_idays[0] << 0
  day_sched = {}
  day_sched['day_idx_list'] = [0]
  day_sched['hr_values'] = values_by_day[0]
  day_scheds = []
  day_scheds << day_sched

  # Check each day with the cumulative list of day_scheds and add new, if unique
  (1..6).each do |iday|
    match_was_found = false
    day_scheds.each do |day_sched|
      # Compare each jday to the current iday and check for a match
      is_a_match = true
      (0..23).each do |ihr|
        if day_sched['hr_values'][ihr] != values_by_day[iday][ihr]
          # this hour is not a match
          is_a_match = false
          break
        end
      end
      if is_a_match
        # Add the day index to the list for this day_sched
        day_sched['day_idx_list'] << iday
        match_was_found = true
        break
      end
    end
    if match_was_found == false
      # Add a new day type
      day_sched = {}
      day_sched['day_idx_list'] = [iday]
      day_sched['hr_values'] = values_by_day[iday]
      day_scheds << day_sched
    end
  end

  # Add the Rule and Day objects
  sch_rules = []
  iday_sch = 0
  day_scheds.each do |day_sched|
    iday_sch += 1

    day_names = []
    day_sched['day_idx_list'].each do |idx|
      day_names << days_of_week[idx]
    end
    day_sch_name = "#{sch_name} Day #{iday_sch}"
    day_sch_values = day_sched['hr_values']
    sch_rule = OpenstudioStandards::Schedules.schedule_ruleset_add_rule(sch_ruleset, day_sch_values,
                                                                        start_date: start_date,
                                                                        end_date: end_date,
                                                                        day_names: day_names,
                                                                        rule_name: day_sch_name)
    sch_rules << sch_rule
  end

  return sch_rules
end
model_add_baseboard(model, thermal_zones, hot_water_loop: nil) click to toggle source

Adds hydronic or electric baseboard heating to each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to add baseboards to. @param hot_water_loop [OpenStudio::Model::PlantLoop] The hot water loop that serves the baseboards. If nil, baseboards are electric. @return [Array<OpenStudio::Model::ZoneHVACBaseboardConvectiveElectric, OpenStudio::Model::ZoneHVACBaseboardConvectiveWater>]

array of baseboard heaters.
# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 4562
def model_add_baseboard(model,
                        thermal_zones,
                        hot_water_loop: nil)

  # Make a baseboard heater for each zone
  baseboards = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding baseboard heat for #{zone.name}.")

    if hot_water_loop.nil?
      baseboard = OpenStudio::Model::ZoneHVACBaseboardConvectiveElectric.new(model)
      baseboard.setName("#{zone.name} Electric Baseboard")
      baseboard.addToThermalZone(zone)
      baseboards << baseboard
    else
      htg_coil = OpenStudio::Model::CoilHeatingWaterBaseboard.new(model)
      htg_coil.setName("#{zone.name} Hydronic Baseboard Coil")
      hot_water_loop.addDemandBranchForComponent(htg_coil)
      baseboard = OpenStudio::Model::ZoneHVACBaseboardConvectiveWater.new(model, model.alwaysOnDiscreteSchedule, htg_coil)
      baseboard.setName("#{zone.name} Hydronic Baseboard")
      baseboard.addToThermalZone(zone)
      baseboards << baseboard
    end
  end

  return baseboards
end
model_add_booster_swh_end_uses(model, swh_booster_loop, peak_flowrate, flowrate_schedule, water_use_temperature) click to toggle source

Creates water fixtures and attaches them to the supplied booster water loop.

@param model [OpenStudio::Model::Model] OpenStudio model object @param swh_booster_loop [OpenStudio::Model::PlantLoop] the booster water loop to add water fixtures to. @param peak_flowrate [Double] in m^3/s @param flowrate_schedule [String] name of the flow rate schedule @param water_use_temperature [Double] mixed water use temperature, in C @return [OpenStudio::Model::WaterUseEquipment] the resulting water fixture

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ServiceWaterHeating.rb, line 1095
def model_add_booster_swh_end_uses(model,
                                   swh_booster_loop,
                                   peak_flowrate,
                                   flowrate_schedule,
                                   water_use_temperature)

  # Water use connection
  swh_connection = OpenStudio::Model::WaterUseConnections.new(model)

  # Water fixture definition
  water_fixture_def = OpenStudio::Model::WaterUseEquipmentDefinition.new(model)
  rated_flow_rate_m3_per_s = peak_flowrate
  rated_flow_rate_gal_per_min = OpenStudio.convert(rated_flow_rate_m3_per_s, 'm^3/s', 'gal/min').get
  water_fixture_def.setName("Booster Water Fixture Def - #{rated_flow_rate_gal_per_min.round(2)} gpm")
  water_fixture_def.setPeakFlowRate(rated_flow_rate_m3_per_s)
  # Target mixed water temperature
  mixed_water_temp_f = OpenStudio.convert(water_use_temperature, 'C', 'F').get
  mixed_water_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                         OpenStudio.convert(mixed_water_temp_f, 'F', 'C').get,
                                                                                         name: "Mixed Water At Faucet Temp - #{mixed_water_temp_f.round}F",
                                                                                         schedule_type_limit: 'Temperature')
  water_fixture_def.setTargetTemperatureSchedule(mixed_water_temp_sch)

  # Water use equipment
  water_fixture = OpenStudio::Model::WaterUseEquipment.new(water_fixture_def)
  water_fixture.setName("Booster Water Fixture - #{rated_flow_rate_gal_per_min.round(2)} gpm at #{mixed_water_temp_f.round}F")
  schedule = model_add_schedule(model, flowrate_schedule)
  water_fixture.setFlowRateFractionSchedule(schedule)
  swh_connection.addWaterUseEquipment(water_fixture)

  # Connect the water use connection to the SWH loop
  unless swh_booster_loop.nil?
    swh_booster_loop.addDemandBranchForComponent(swh_connection)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding water fixture to #{swh_booster_loop.name}.")
  end

  return water_fixture
end
model_add_cav(model, thermal_zones, system_name: nil, hot_water_loop: nil, chilled_water_loop: nil, hvac_op_sch: nil, oa_damper_sch: nil, fan_efficiency: 0.62, fan_motor_efficiency: 0.9, fan_pressure_rise: 4.0) click to toggle source

Creates a CAV system and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param system_name [String] the name of the system, or nil in which case it will be defaulted @param hot_water_loop [OpenStudio::Model::PlantLoop] hot water loop to connect to heating and reheat coils. @param chilled_water_loop [OpenStudio::Model::PlantLoop] chilled water loop to connect to the cooling coil. @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [String] name of the oa damper schedule or nil in which case will be defaulted to always open @param fan_efficiency [Double] fan total efficiency, including motor and impeller @param fan_motor_efficiency [Double] fan motor efficiency @param fan_pressure_rise [Double] fan pressure rise, inH2O @return [OpenStudio::Model::AirLoopHVAC] the resulting packaged VAV air loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 2548
def model_add_cav(model,
                  thermal_zones,
                  system_name: nil,
                  hot_water_loop: nil,
                  chilled_water_loop: nil,
                  hvac_op_sch: nil,
                  oa_damper_sch: nil,
                  fan_efficiency: 0.62,
                  fan_motor_efficiency: 0.9,
                  fan_pressure_rise: 4.0)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding CAV for #{thermal_zones.size} zones.")

  # create air handler
  air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
  if system_name.nil?
    air_loop.setName("#{thermal_zones.size} Zone CAV")
  else
    air_loop.setName(system_name)
  end

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # default design temperatures used across all air loops
  dsgn_temps = standard_design_sizing_temperatures
  unless hot_water_loop.nil?
    hw_temp_c = hot_water_loop.sizingPlant.designLoopExitTemperature
    hw_delta_t_k = hot_water_loop.sizingPlant.loopDesignTemperatureDifference
  end

  # adjusted design heating temperature for cav
  dsgn_temps['htg_dsgn_sup_air_temp_f'] = 62.0
  dsgn_temps['htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
  dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get

  # default design settings used across all air loops
  sizing_system = adjust_sizing_system(air_loop, dsgn_temps, min_sys_airflow_ratio: 1.0)

  # air handler controls
  sa_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                dsgn_temps['clg_dsgn_sup_air_temp_c'],
                                                                                name: "Supply Air Temp - #{dsgn_temps['clg_dsgn_sup_air_temp_f']}F",
                                                                                schedule_type_limit: 'Temperature')
  sa_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, sa_temp_sch)
  sa_stpt_manager.setName("#{air_loop.name} Supply Air Setpoint Manager")
  sa_stpt_manager.addToNode(air_loop.supplyOutletNode)

  # create fan
  fan = create_fan_by_name(model,
                           'Packaged_RTU_SZ_AC_CAV_Fan',
                           fan_name: "#{air_loop.name} Fan",
                           fan_efficiency: fan_efficiency,
                           pressure_rise: fan_pressure_rise,
                           motor_efficiency: fan_motor_efficiency,
                           end_use_subcategory: 'CAV System Fans')
  fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  fan.addToNode(air_loop.supplyInletNode)

  # create heating coil
  create_coil_heating_water(model,
                            hot_water_loop,
                            air_loop_node: air_loop.supplyInletNode,
                            name: "#{air_loop.name} Main Htg Coil",
                            rated_inlet_water_temperature: hw_temp_c,
                            rated_outlet_water_temperature: (hw_temp_c - hw_delta_t_k),
                            rated_inlet_air_temperature: dsgn_temps['prehtg_dsgn_sup_air_temp_c'],
                            rated_outlet_air_temperature: dsgn_temps['htg_dsgn_sup_air_temp_c'])

  # create cooling coil
  if chilled_water_loop.nil?
    create_coil_cooling_dx_two_speed(model,
                                     air_loop_node: air_loop.supplyInletNode,
                                     name: "#{air_loop.name} 2spd DX Clg Coil",
                                     type: 'OS default')
  else
    create_coil_cooling_water(model,
                              chilled_water_loop,
                              air_loop_node: air_loop.supplyInletNode,
                              name: "#{air_loop.name} Clg Coil")
  end

  # create outdoor air intake system
  oa_intake_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
  oa_intake_controller.setName("#{air_loop.name} OA Controller")
  oa_intake_controller.setMinimumLimitType('FixedMinimum')
  oa_intake_controller.autosizeMinimumOutdoorAirFlowRate
  oa_intake_controller.setMinimumFractionofOutdoorAirSchedule(oa_damper_sch)
  oa_intake_controller.resetEconomizerMinimumLimitDryBulbTemperature
  controller_mv = oa_intake_controller.controllerMechanicalVentilation
  controller_mv.setName("#{air_loop.name} Vent Controller")
  controller_mv.setSystemOutdoorAirMethod('ZoneSum')
  oa_intake = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_intake_controller)
  oa_intake.setName("#{air_loop.name} OA System")
  oa_intake.addToNode(air_loop.supplyInletNode)

  # set air loop availability controls and night cycle manager, after oa system added
  air_loop.setAvailabilitySchedule(hvac_op_sch)
  air_loop.setNightCycleControlType('CycleOnAny')

  # Connect the CAV system to each zone
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "Adding CAV for #{zone.name}")

    # Reheat coil
    rht_coil = create_coil_heating_water(model,
                                         hot_water_loop,
                                         name: "#{zone.name} Reheat Coil",
                                         rated_inlet_water_temperature: hw_temp_c,
                                         rated_outlet_water_temperature: (hw_temp_c - hw_delta_t_k),
                                         rated_inlet_air_temperature: dsgn_temps['htg_dsgn_sup_air_temp_c'],
                                         rated_outlet_air_temperature: dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    # VAV terminal
    terminal = OpenStudio::Model::AirTerminalSingleDuctVAVReheat.new(model, model.alwaysOnDiscreteSchedule, rht_coil)
    terminal.setName("#{zone.name} VAV Terminal")
    if model.version < OpenStudio::VersionString.new('3.0.1')
      terminal.setZoneMinimumAirFlowMethod('Constant')
    else
      terminal.setZoneMinimumAirFlowInputMethod('Constant')
    end
    terminal.setMaximumFlowPerZoneFloorAreaDuringReheat(0.0)
    terminal.setMaximumFlowFractionDuringReheat(0.5)
    terminal.setMaximumReheatAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    air_loop.multiAddBranchForZone(zone, terminal.to_HVACComponent.get)
    oa_rate = OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate_per_area(zone)
    air_terminal_single_duct_vav_reheat_apply_initial_prototype_damper_position(terminal, oa_rate)

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setCoolingDesignAirFlowMethod('DesignDayWithLimit')
    sizing_zone.setHeatingDesignAirFlowMethod('DesignDay')
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
  end

  # Set the damper action based on the template.
  air_loop_hvac_apply_vav_damper_action(air_loop)

  return air_loop
end
model_add_central_air_source_heat_pump(model, thermal_zones, heating: true, cooling: true, ventilation: false) click to toggle source

Adds an air source heat pump to each zone. Code adapted from: github.com/NREL/OpenStudio-BEopt/blob/master/measures/ResidentialHVACAirSourceHeatPumpSingleSpeed/measure.rb

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to add fan coil units to. @param heating [Boolean] if true, the unit will include a NaturalGas heating coil @param cooling [Boolean] if true, the unit will include a DX cooling coil @param ventilation [Boolean] if true, the unit will include an OA intake @return [Array<OpenStudio::Model::AirLoopHVAC>] and array of air loops representing the heat pumps

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 5467
def model_add_central_air_source_heat_pump(model,
                                           thermal_zones,
                                           heating: true,
                                           cooling: true,
                                           ventilation: false)
  # defaults
  hspf = 7.7
  # seer = 13.0
  # eer = 11.4
  cop = 3.05
  shr = 0.73
  ac_w_per_cfm = 0.365
  min_hp_oat_f = 0.0
  crank_case_heat_w = 0.0
  crank_case_max_temp_f = 55

  # default design temperatures across all air loops
  dsgn_temps = standard_design_sizing_temperatures

  # adjusted temperatures for furnace_central_ac
  dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
  dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['htg_dsgn_sup_air_temp_f'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_f']
  dsgn_temps['htg_dsgn_sup_air_temp_c'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_c']

  hps = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding Central Air Source HP for #{zone.name}.")

    air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
    air_loop.setName("#{zone.name} Central Air Source HP")

    # default design settings used across all air loops
    sizing_system = adjust_sizing_system(air_loop, dsgn_temps, sizing_option: 'NonCoincident')
    sizing_system.setAllOutdoorAirinCooling(true)
    sizing_system.setAllOutdoorAirinHeating(true)

    # create heating coil
    htg_coil = nil
    supplemental_htg_coil = nil
    if heating
      htg_coil = create_coil_heating_dx_single_speed(model,
                                                     name: "#{air_loop.name} heating coil",
                                                     type: 'Residential Central Air Source HP',
                                                     cop: hspf_to_cop_no_fan(hspf))
      if model.version < OpenStudio::VersionString.new('3.5.0')
        htg_coil.setRatedSupplyFanPowerPerVolumeFlowRate(ac_w_per_cfm / OpenStudio.convert(1.0, 'cfm', 'm^3/s').get)
      else
        htg_coil.setRatedSupplyFanPowerPerVolumeFlowRate2017(ac_w_per_cfm / OpenStudio.convert(1.0, 'cfm', 'm^3/s').get)
      end
      htg_coil.setMinimumOutdoorDryBulbTemperatureforCompressorOperation(OpenStudio.convert(min_hp_oat_f, 'F', 'C').get)
      htg_coil.setMaximumOutdoorDryBulbTemperatureforDefrostOperation(OpenStudio.convert(40.0, 'F', 'C').get)
      htg_coil.setCrankcaseHeaterCapacity(crank_case_heat_w)
      htg_coil.setMaximumOutdoorDryBulbTemperatureforCrankcaseHeaterOperation(OpenStudio.convert(crank_case_max_temp_f, 'F', 'C').get)
      htg_coil.setDefrostStrategy('ReverseCycle')
      htg_coil.setDefrostControl('OnDemand')
      htg_coil.resetDefrostTimePeriodFraction

      # Supplemental Heating Coil

      # create supplemental heating coil
      supplemental_htg_coil = create_coil_heating_electric(model,
                                                           name: "#{air_loop.name} Supplemental Htg Coil")
    end

    # create cooling coil
    clg_coil = nil
    if cooling
      clg_coil = create_coil_cooling_dx_single_speed(model,
                                                     name: "#{air_loop.name} Cooling Coil",
                                                     type: 'Residential Central ASHP',
                                                     cop: cop)
      clg_coil.setRatedSensibleHeatRatio(shr)
      clg_coil.setRatedEvaporatorFanPowerPerVolumeFlowRate(OpenStudio::OptionalDouble.new(ac_w_per_cfm / OpenStudio.convert(1.0, 'cfm', 'm^3/s').get))
      clg_coil.setNominalTimeForCondensateRemovalToBegin(OpenStudio::OptionalDouble.new(1000.0))
      clg_coil.setRatioOfInitialMoistureEvaporationRateAndSteadyStateLatentCapacity(OpenStudio::OptionalDouble.new(1.5))
      clg_coil.setMaximumCyclingRate(OpenStudio::OptionalDouble.new(3.0))
      clg_coil.setLatentCapacityTimeConstant(OpenStudio::OptionalDouble.new(45.0))
      clg_coil.setCondenserType('AirCooled')
      clg_coil.setCrankcaseHeaterCapacity(OpenStudio::OptionalDouble.new(crank_case_heat_w))
      clg_coil.setMaximumOutdoorDryBulbTemperatureForCrankcaseHeaterOperation(OpenStudio::OptionalDouble.new(OpenStudio.convert(crank_case_max_temp_f, 'F', 'C').get))
    end

    # create fan
    fan = create_fan_by_name(model,
                             'Residential_HVAC_Fan',
                             fan_name: "#{air_loop.name} Supply Fan",
                             end_use_subcategory: 'Residential HVAC Fans')
    fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

    # create outdoor air intake
    if ventilation
      oa_intake_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
      oa_intake_controller.setName("#{air_loop.name} OA Controller")
      oa_intake_controller.autosizeMinimumOutdoorAirFlowRate
      oa_intake_controller.resetEconomizerMinimumLimitDryBulbTemperature
      oa_intake = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_intake_controller)
      oa_intake.setName("#{air_loop.name} OA System")
      oa_intake.addToNode(air_loop.supplyInletNode)
    end

    # create unitary system (holds the coils and fan)
    unitary = OpenStudio::Model::AirLoopHVACUnitarySystem.new(model)
    unitary.setName("#{air_loop.name} Unitary System")
    unitary.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
    unitary.setMaximumSupplyAirTemperature(OpenStudio.convert(170.0, 'F', 'C').get) # higher temp for supplemental heat as to not severely limit its use, resulting in unmet hours.
    unitary.setMaximumOutdoorDryBulbTemperatureforSupplementalHeaterOperation(OpenStudio.convert(40.0, 'F', 'C').get)
    unitary.setControllingZoneorThermostatLocation(zone)
    unitary.addToNode(air_loop.supplyInletNode)

    # set flow rates during different conditions
    unitary.setSupplyAirFlowRateWhenNoCoolingorHeatingisRequired(0.0) unless ventilation

    # attach the coils and fan
    unitary.setHeatingCoil(htg_coil) if htg_coil
    unitary.setCoolingCoil(clg_coil) if clg_coil
    unitary.setSupplementalHeatingCoil(supplemental_htg_coil) if supplemental_htg_coil
    unitary.setSupplyFan(fan)
    unitary.setFanPlacement('BlowThrough')
    unitary.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)

    # create a diffuser
    diffuser = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)
    diffuser.setName(" #{zone.name} Direct Air")
    air_loop.multiAddBranchForZone(zone, diffuser.to_HVACComponent.get)

    hps << air_loop
  end

  return hps
end
model_add_chw_loop(model, system_name: 'Chilled Water Loop', cooling_fuel: 'Electricity', dsgn_sup_wtr_temp: 44.0, dsgn_sup_wtr_temp_delt: 10.1, chw_pumping_type: nil, chiller_cooling_type: nil, chiller_condenser_type: nil, chiller_compressor_type: nil, num_chillers: 1, condenser_water_loop: nil, waterside_economizer: 'none') click to toggle source

Creates a chilled water loop and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param system_name [String] the name of the system, or nil in which case it will be defaulted @param cooling_fuel [String] cooling fuel. Valid choices are: Electricity, DistrictCooling @param dsgn_sup_wtr_temp [Double] design supply water temperature in degrees Fahrenheit, default 44F @param dsgn_sup_wtr_temp_delt [Double] design supply-return water temperature difference in degrees Rankine, default 10R @param chw_pumping_type [String] valid choices are const_pri, const_pri_var_sec @param chiller_cooling_type [String] valid choices are AirCooled, WaterCooled @param chiller_condenser_type [String] valid choices are WithCondenser, WithoutCondenser, nil @param chiller_compressor_type [String] valid choices are Centrifugal, Reciprocating, Rotary Screw, Scroll, nil @param num_chillers [Integer] the number of chillers @param condenser_water_loop [OpenStudio::Model::PlantLoop] optional condenser water loop for water-cooled chillers.

If this is not passed in, the chillers will be air cooled.

@param waterside_economizer [String] Options are ‘none’, ‘integrated’, ‘non-integrated’.

If 'integrated' will add a heat exchanger to the supply inlet of the chilled water loop
  to provide waterside economizing whenever wet bulb temperatures allow
If 'non-integrated' will add a heat exchanger in parallel with the chiller that will operate
  only when it can meet cooling demand exclusively with the waterside economizing.

@return [OpenStudio::Model::PlantLoop] the resulting chilled water loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 228
def model_add_chw_loop(model,
                       system_name: 'Chilled Water Loop',
                       cooling_fuel: 'Electricity',
                       dsgn_sup_wtr_temp: 44.0,
                       dsgn_sup_wtr_temp_delt: 10.1,
                       chw_pumping_type: nil,
                       chiller_cooling_type: nil,
                       chiller_condenser_type: nil,
                       chiller_compressor_type: nil,
                       num_chillers: 1,
                       condenser_water_loop: nil,
                       waterside_economizer: 'none')
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', 'Adding chilled water loop.')

  # create chilled water loop
  chilled_water_loop = OpenStudio::Model::PlantLoop.new(model)
  if system_name.nil?
    chilled_water_loop.setName('Chilled Water Loop')
  else
    chilled_water_loop.setName(system_name)
  end

  if dsgn_sup_wtr_temp.nil?
    dsgn_sup_wtr_temp = 44
  end

  # chilled water loop sizing and controls
  chw_sizing_control(model, chilled_water_loop, dsgn_sup_wtr_temp, dsgn_sup_wtr_temp_delt)

  # create chilled water pumps
  if chw_pumping_type == 'const_pri'
    # primary chilled water pump
    pri_chw_pump = OpenStudio::Model::PumpVariableSpeed.new(model)
    pri_chw_pump.setName("#{chilled_water_loop.name} Pump")
    pri_chw_pump.setRatedPumpHead(OpenStudio.convert(60.0, 'ftH_{2}O', 'Pa').get)
    pri_chw_pump.setMotorEfficiency(0.9)
    # flat pump curve makes it behave as a constant speed pump
    pri_chw_pump.setFractionofMotorInefficienciestoFluidStream(0)
    pri_chw_pump.setCoefficient1ofthePartLoadPerformanceCurve(0)
    pri_chw_pump.setCoefficient2ofthePartLoadPerformanceCurve(1)
    pri_chw_pump.setCoefficient3ofthePartLoadPerformanceCurve(0)
    pri_chw_pump.setCoefficient4ofthePartLoadPerformanceCurve(0)
    pri_chw_pump.setPumpControlType('Intermittent')
    pri_chw_pump.addToNode(chilled_water_loop.supplyInletNode)
  elsif chw_pumping_type == 'const_pri_var_sec'
    pri_sec_config = plant_loop_set_chw_pri_sec_configuration(model)

    if pri_sec_config == 'common_pipe'
      # primary chilled water pump
      pri_chw_pump = OpenStudio::Model::PumpConstantSpeed.new(model)
      pri_chw_pump.setName("#{chilled_water_loop.name} Primary Pump")
      pri_chw_pump.setRatedPumpHead(OpenStudio.convert(15.0, 'ftH_{2}O', 'Pa').get)
      pri_chw_pump.setMotorEfficiency(0.9)
      pri_chw_pump.setPumpControlType('Intermittent')
      pri_chw_pump.addToNode(chilled_water_loop.supplyInletNode)
      # secondary chilled water pump
      sec_chw_pump = OpenStudio::Model::PumpVariableSpeed.new(model)
      sec_chw_pump.setName("#{chilled_water_loop.name} Secondary Pump")
      sec_chw_pump.setRatedPumpHead(OpenStudio.convert(45.0, 'ftH_{2}O', 'Pa').get)
      sec_chw_pump.setMotorEfficiency(0.9)
      # curve makes it perform like variable speed pump
      sec_chw_pump.setFractionofMotorInefficienciestoFluidStream(0)
      sec_chw_pump.setCoefficient1ofthePartLoadPerformanceCurve(0)
      sec_chw_pump.setCoefficient2ofthePartLoadPerformanceCurve(0.0205)
      sec_chw_pump.setCoefficient3ofthePartLoadPerformanceCurve(0.4101)
      sec_chw_pump.setCoefficient4ofthePartLoadPerformanceCurve(0.5753)
      sec_chw_pump.setPumpControlType('Intermittent')
      sec_chw_pump.addToNode(chilled_water_loop.demandInletNode)
      # Change the chilled water loop to have a two-way common pipes
      chilled_water_loop.setCommonPipeSimulation('CommonPipe')
    elsif pri_sec_config == 'heat_exchanger'
      # NOTE: PRECONDITIONING for `const_pri_var_sec` pump type is only applicable for PRM routine and only applies to System Type 7 and System Type 8
      # See: model_add_prm_baseline_system under Model object.
      # In this scenario, we will need to create a primary and secondary configuration:
      # chilled_water_loop is the primary loop
      # Primary: demand: heat exchanger, supply: chillers, name: Chilled Water Loop_Primary, additionalProperty: secondary_loop_name
      # Secondary: demand: Coils, supply: heat exchanger, name: Chilled Water Loop, additionalProperty: is_secondary_loop
      secondary_chilled_water_loop = OpenStudio::Model::PlantLoop.new(model)
      secondary_loop_name = system_name.nil? ? 'Chilled Water Loop' : system_name
      # Reset primary loop name
      chilled_water_loop.setName("#{secondary_loop_name}_Primary")
      secondary_chilled_water_loop.setName(secondary_loop_name)
      chw_sizing_control(model, secondary_chilled_water_loop, dsgn_sup_wtr_temp, dsgn_sup_wtr_temp_delt)
      chilled_water_loop.additionalProperties.setFeature('is_primary_loop', true)
      secondary_chilled_water_loop.additionalProperties.setFeature('is_secondary_loop', true)
      # primary chilled water pump
      # Add Constant pump, in plant loop, the number of chiller adjustment will assign pump to each chiller
      pri_chw_pump = OpenStudio::Model::PumpConstantSpeed.new(model)
      pri_chw_pump.setName("#{chilled_water_loop.name} Primary Pump")
      # Will need to adjust the pump power after a sizing run
      pri_chw_pump.setRatedPumpHead(OpenStudio.convert(15.0, 'ftH_{2}O', 'Pa').get / num_chillers)
      pri_chw_pump.setMotorEfficiency(0.9)
      pri_chw_pump.setPumpControlType('Intermittent')
      # chiller_inlet_node = chiller.connectedObject(chiller.supplyInletPort).get.to_Node.get
      pri_chw_pump.addToNode(chilled_water_loop.supplyInletNode)

      # secondary chilled water pump
      sec_chw_pump = OpenStudio::Model::PumpVariableSpeed.new(model)
      sec_chw_pump.setName("#{secondary_chilled_water_loop.name} Pump")
      sec_chw_pump.setRatedPumpHead(OpenStudio.convert(45.0, 'ftH_{2}O', 'Pa').get)
      sec_chw_pump.setMotorEfficiency(0.9)
      # curve makes it perform like variable speed pump
      sec_chw_pump.setFractionofMotorInefficienciestoFluidStream(0)
      sec_chw_pump.setCoefficient1ofthePartLoadPerformanceCurve(0)
      sec_chw_pump.setCoefficient2ofthePartLoadPerformanceCurve(0.0205)
      sec_chw_pump.setCoefficient3ofthePartLoadPerformanceCurve(0.4101)
      sec_chw_pump.setCoefficient4ofthePartLoadPerformanceCurve(0.5753)
      sec_chw_pump.setPumpControlType('Intermittent')
      sec_chw_pump.addToNode(secondary_chilled_water_loop.demandInletNode)

      # Add HX to connect secondary and primary loop
      heat_exchanger = OpenStudio::Model::HeatExchangerFluidToFluid.new(model)
      secondary_chilled_water_loop.addSupplyBranchForComponent(heat_exchanger)
      chilled_water_loop.addDemandBranchForComponent(heat_exchanger)

      # Clean up connections
      hx_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
      hx_bypass_pipe.setName("#{secondary_chilled_water_loop.name} HX Bypass")
      secondary_chilled_water_loop.addSupplyBranchForComponent(hx_bypass_pipe)
      outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
      outlet_pipe.setName("#{secondary_chilled_water_loop.name} Supply Outlet")
      outlet_pipe.addToNode(secondary_chilled_water_loop.supplyOutletNode)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'No primary/secondary configuration specified for the chilled water loop.')
    end
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'No pumping type specified for the chilled water loop.')
  end

  # check for existence of condenser_water_loop if WaterCooled
  if chiller_cooling_type == 'WaterCooled'
    if condenser_water_loop.nil?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'Requested chiller is WaterCooled but no condenser loop specified.')
    end
  end

  # check for non-existence of condenser_water_loop if AirCooled
  if chiller_cooling_type == 'AirCooled'
    unless condenser_water_loop.nil?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'Requested chiller is AirCooled but condenser loop specified.')
    end
  end

  if cooling_fuel == 'DistrictCooling'
    # DistrictCooling
    dist_clg = OpenStudio::Model::DistrictCooling.new(model)
    dist_clg.setName('Purchased Cooling')
    dist_clg.autosizeNominalCapacity
    chilled_water_loop.addSupplyBranchForComponent(dist_clg)
  else
    # make the correct type of chiller based these properties
    chiller_sizing_factor = (1.0 / num_chillers).round(2)
    num_chillers.times do |i|
      chiller = OpenStudio::Model::ChillerElectricEIR.new(model)
      chiller.setName("#{template} #{chiller_cooling_type} #{chiller_condenser_type} #{chiller_compressor_type} Chiller #{i}")
      chilled_water_loop.addSupplyBranchForComponent(chiller)
      dsgn_sup_wtr_temp_c = OpenStudio.convert(dsgn_sup_wtr_temp, 'F', 'C').get
      chiller.setReferenceLeavingChilledWaterTemperature(dsgn_sup_wtr_temp_c)
      chiller.setLeavingChilledWaterLowerTemperatureLimit(OpenStudio.convert(36.0, 'F', 'C').get)
      chiller.setReferenceEnteringCondenserFluidTemperature(OpenStudio.convert(95.0, 'F', 'C').get)
      chiller.setMinimumPartLoadRatio(0.15)
      chiller.setMaximumPartLoadRatio(1.0)
      chiller.setOptimumPartLoadRatio(1.0)
      chiller.setMinimumUnloadingRatio(0.25)
      chiller.setChillerFlowMode('ConstantFlow')
      chiller.setSizingFactor(chiller_sizing_factor)

      # use default efficiency from 90.1-2019
      # 1.188 kw/ton for a 150 ton AirCooled chiller
      # 0.66 kw/ton for a 150 ton Water Cooled positive displacement chiller
      case chiller_cooling_type
      when 'AirCooled'
        default_cop = kw_per_ton_to_cop(1.188)
      when 'WaterCooled'
        default_cop = kw_per_ton_to_cop(0.66)
      else
        default_cop = kw_per_ton_to_cop(0.66)
      end
      chiller.setReferenceCOP(default_cop)

      # connect the chiller to the condenser loop if one was supplied
      if condenser_water_loop.nil?
        chiller.setCondenserType('AirCooled')
      else
        condenser_water_loop.addDemandBranchForComponent(chiller)
        chiller.setCondenserType('WaterCooled')
      end
    end
  end

  # enable waterside economizer if requested
  unless condenser_water_loop.nil?
    case waterside_economizer
    when 'integrated'
      model_add_waterside_economizer(model, chilled_water_loop, condenser_water_loop,
                                     integrated: true)
    when 'non-integrated'
      model_add_waterside_economizer(model, chilled_water_loop, condenser_water_loop,
                                     integrated: false)
    end
  end

  # chilled water loop pipes
  chiller_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  chiller_bypass_pipe.setName("#{chilled_water_loop.name} Chiller Bypass")
  chilled_water_loop.addSupplyBranchForComponent(chiller_bypass_pipe)

  coil_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  coil_bypass_pipe.setName("#{chilled_water_loop.name} Coil Bypass")
  chilled_water_loop.addDemandBranchForComponent(coil_bypass_pipe)

  supply_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_outlet_pipe.setName("#{chilled_water_loop.name} Supply Outlet")
  supply_outlet_pipe.addToNode(chilled_water_loop.supplyOutletNode)

  demand_inlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_inlet_pipe.setName("#{chilled_water_loop.name} Demand Inlet")
  demand_inlet_pipe.addToNode(chilled_water_loop.demandInletNode)

  demand_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_outlet_pipe.setName("#{chilled_water_loop.name} Demand Outlet")
  demand_outlet_pipe.addToNode(chilled_water_loop.demandOutletNode)

  return chilled_water_loop
end
model_add_construction(model, construction_name, construction_props = nil, surface = nil) click to toggle source

Create a construction from the openstudio standards dataset. If construction_props are specified, modifies the insulation layer accordingly.

@param model [OpenStudio::Model::Model] OpenStudio model object @param construction_name [String] name of the construction @param construction_props [Hash] hash of construction properties @return [OpenStudio::Model::Construction] construction object @todo make return an OptionalConstruction

# File lib/openstudio-standards/standards/Standards.Model.rb, line 3036
def model_add_construction(model, construction_name, construction_props = nil, surface = nil)
  # First check model and return construction if it already exists
  model.getConstructions.sort.each do |construction|
    if construction.name.get.to_s == construction_name
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Already added construction: #{construction_name}")
      return construction
    end
  end

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Adding construction: #{construction_name}")

  # Get the object data
  if standards_data.keys.include?('prm_constructions')
    data = model_find_object(standards_data['prm_constructions'], 'name' => construction_name)
  else
    data = model_find_object(standards_data['constructions'], 'name' => construction_name)
  end

  unless data
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Cannot find data for construction: #{construction_name}, will not be created.")
    return OpenStudio::Model::OptionalConstruction.new
  end

  # Make a new construction and set the standards details
  if data['intended_surface_type'] == 'GroundContactFloor' && !surface.nil?
    construction = OpenStudio::Model::FFactorGroundFloorConstruction.new(model)
  elsif data['intended_surface_type'] == 'GroundContactWall' && !surface.nil?
    construction = OpenStudio::Model::CFactorUndergroundWallConstruction.new(model)
  else
    construction = OpenStudio::Model::Construction.new(model)
    # Add the material layers to the construction
    layers = OpenStudio::Model::MaterialVector.new
    data['materials'].each do |material_name|
      material = model_add_material(model, material_name)
      if material
        layers << material
      end
    end
    construction.setLayers(layers)
  end
  construction.setName(construction_name)
  standards_info = construction.standardsInformation

  intended_surface_type = data['intended_surface_type']
  intended_surface_type ||= ''
  standards_info.setIntendedSurfaceType(intended_surface_type)

  standards_construction_type = data['standards_construction_type']
  standards_construction_type ||= ''
  standards_info.setStandardsConstructionType(standards_construction_type)

  # @todo could put construction rendering color in the spreadsheet

  # Modify the R value of the insulation to hit the specified U-value, C-Factor, or F-Factor.
  # Doesn't currently operate on glazing constructions
  if construction_props
    # Determine the target U-value, C-factor, and F-factor
    target_u_value_ip = construction_props['assembly_maximum_u_value']
    target_f_factor_ip = construction_props['assembly_maximum_f_factor']
    target_c_factor_ip = construction_props['assembly_maximum_c_factor']
    target_shgc = construction_props['assembly_maximum_solar_heat_gain_coefficient']
    u_includes_int_film = construction_props['u_value_includes_interior_film_coefficient']
    u_includes_ext_film = construction_props['u_value_includes_exterior_film_coefficient']

    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "#{data['intended_surface_type']} u_val #{target_u_value_ip} f_fac #{target_f_factor_ip} c_fac #{target_c_factor_ip}")

    if target_u_value_ip

      # Handle Opaque and Fenestration Constructions differently
      # if construction.isFenestration && OpenstudioStandards::Constructions.construction_simple_glazing?(construction)
      if construction.isFenestration
        if OpenstudioStandards::Constructions.construction_simple_glazing?(construction)
          # Set the U-Value and SHGC
          OpenstudioStandards::Constructions.construction_set_glazing_u_value(construction, target_u_value_ip.to_f,
                                                                              target_includes_interior_film_coefficients: u_includes_int_film,
                                                                              target_includes_exterior_film_coefficients: u_includes_ext_film)
          simple_glazing = construction.layers.first.to_SimpleGlazing
          unless simple_glazing.is_initialized && !target_shgc.nil?
            simple_glazing.get.setSolarHeatGainCoefficient(target_shgc.to_f)
          end
        else # if !data['intended_surface_type'] == 'ExteriorWindow' && !data['intended_surface_type'] == 'Skylight'
          # Set the U-Value
          OpenstudioStandards::Constructions.construction_set_u_value(construction, target_u_value_ip.to_f,
                                                                      insulation_layer_name: data['insulation_layer'],
                                                                      intended_surface_type: data['intended_surface_type'],
                                                                      target_includes_interior_film_coefficients: u_includes_int_film,
                                                                      target_includes_exterior_film_coefficients: u_includes_ext_film)
          # else
          # OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Not modifying U-value for #{data['intended_surface_type']} u_val #{target_u_value_ip} f_fac #{target_f_factor_ip} c_fac #{target_c_factor_ip}")
        end
      else
        # Set the U-Value
        OpenstudioStandards::Constructions.construction_set_u_value(construction, target_u_value_ip.to_f,
                                                                    insulation_layer_name: data['insulation_layer'],
                                                                    intended_surface_type: data['intended_surface_type'],
                                                                    target_includes_interior_film_coefficients: u_includes_int_film,
                                                                    target_includes_exterior_film_coefficients: u_includes_ext_film)
        # else
        # OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Not modifying U-value for #{data['intended_surface_type']} u_val #{target_u_value_ip} f_fac #{target_f_factor_ip} c_fac #{target_c_factor_ip}")
      end

    elsif target_f_factor_ip && data['intended_surface_type'] == 'GroundContactFloor'
      # F-factor objects are unique to each surface, so a surface needs to be passed
      # If not surface is passed, use the older approach to model ground contact floors
      if surface.nil?
        # Set the F-Factor (only applies to slabs on grade)
        # @todo figure out what the prototype buildings did about ground heat transfer
        # OpenstudioStandards::Constructions.construction_set_slab_f_factor(construction, target_f_factor_ip.to_f, insulation_layer_name: data['insulation_layer'])
        OpenstudioStandards::Constructions.construction_set_u_value(construction, 0.0,
                                                                    insulation_layer_name: data['insulation_layer'],
                                                                    intended_surface_type: data['intended_surface_type'],
                                                                    target_includes_interior_film_coefficients: u_includes_int_film,
                                                                    target_includes_exterior_film_coefficients: u_includes_ext_film)
      else
        OpenstudioStandards::Constructions.construction_set_surface_slab_f_factor(construction, target_f_factor_ip, surface)
      end
    elsif target_c_factor_ip && (data['intended_surface_type'] == 'GroundContactWall' || data['intended_surface_type'] == 'GroundContactRoof')
      # C-factor objects are unique to each surface, so a surface needs to be passed
      # If not surface is passed, use the older approach to model ground contact walls
      if surface.nil?
        # Set the C-Factor (only applies to underground walls)
        # @todo figure out what the prototype buildings did about ground heat transfer
        # OpenstudioStandards::Constructions.construction_set_underground_wall_c_factor(construction, target_c_factor_ip.to_f, insulation_layer_name: data['insulation_layer'])
        OpenstudioStandards::Constructions.construction_set_u_value(construction, 0.0,
                                                                    insulation_layer_name: data['insulation_layer'],
                                                                    intended_surface_type: data['intended_surface_type'],
                                                                    target_includes_interior_film_coefficients: u_includes_int_film,
                                                                    target_includes_exterior_film_coefficients: u_includes_ext_film)
      else
        OpenstudioStandards::Constructions.construction_set_surface_underground_wall_c_factor(construction, target_c_factor_ip, surface)
      end
    end

    # If the construction is fenestration,
    # also set the frame type for use in future lookups
    if construction.isFenestration
      case standards_construction_type
      when 'Metal framing (all other)'
        standards_info.setFenestrationFrameType('Metal Framing')
      when 'Nonmetal framing (all)'
        standards_info.setFenestrationFrameType('Non-Metal Framing')
      end
    end

    # If the construction has a skylight framing material specified,
    # get the skylight frame material properties and add frame to
    # all skylights in the model.
    if data['skylight_framing']
      # Get the skylight framing material
      framing_name = data['skylight_framing']
      frame_data = model_find_object(standards_data['materials'], 'name' => framing_name)
      if frame_data
        frame_width_in = frame_data['frame_width'].to_f
        frame_with_m = OpenStudio.convert(frame_width_in, 'in', 'm').get
        frame_resistance_ip = frame_data['resistance'].to_f
        frame_resistance_si = OpenStudio.convert(frame_resistance_ip, 'hr*ft^2*R/Btu', 'm^2*K/W').get
        frame_conductance_si = 1.0 / frame_resistance_si
        frame = OpenStudio::Model::WindowPropertyFrameAndDivider.new(model)
        frame.setName("Skylight frame R-#{frame_resistance_ip.round(2)} #{frame_width_in.round(1)} in. wide")
        frame.setFrameWidth(frame_with_m)
        frame.setFrameConductance(frame_conductance_si)
        skylights_frame_added = 0
        model.getSubSurfaces.each do |sub_surface|
          next unless sub_surface.outsideBoundaryCondition == 'Outdoors' && sub_surface.subSurfaceType == 'Skylight'

          if model.version < OpenStudio::VersionString.new('3.1.0')
            # window frame setting before https://github.com/NREL/OpenStudio/issues/2895 was fixed
            sub_surface.setString(8, frame.name.get.to_s)
            skylights_frame_added += 1
          else
            if sub_surface.allowWindowPropertyFrameAndDivider
              sub_surface.setWindowPropertyFrameAndDivider(frame)
              skylights_frame_added += 1
            else
              OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "For #{sub_surface.name}: cannot add a frame to this skylight.")
            end
          end
        end
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Adding #{frame.name} to #{skylights_frame_added} skylights.") if skylights_frame_added > 0
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Cannot find skylight framing data for: #{framing_name}, will not be created.")
        return false
        # @todo change to return empty optional material
      end
    end

  end
  #     # Check if the construction with the modified name was already in the model.
  #     # If it was, delete this new construction and return the copy already in the model.
  #     m = construction.name.get.to_s.match(/\s(\d+)/)
  #     if m
  #       revised_cons_name = construction.name.get.to_s.gsub(/\s\d+/,'')
  #       model.getConstructions.sort.each do |exist_construction|
  #         if exist_construction.name.get.to_s == revised_cons_name
  #           OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Already added construction: #{construction_name}")
  #           # Remove the recently added construction
  #           lyrs = construction.layers
  #           # Erase the layers in the construction
  #           construction.setLayers([])
  #           # Delete unused materials
  #           lyrs.uniq.each do |lyr|
  #             if lyr.directUseCount.zero?
  #               OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Removing Material: #{lyr.name}")
  #               lyr.remove
  #             end
  #           end
  #           construction.remove # Remove the construction
  #           return exist_construction
  #         end
  #       end
  #     end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Adding construction #{construction.name}.")

  return construction
end
model_add_construction_set(model, climate_zone, building_type, spc_type, is_residential) click to toggle source

Create a construction set from the openstudio standards dataset.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param building_type [String] the building type @param spc_type [String] the space type @param is_residential [Boolean] true if the building is residential @return [OpenStudio::Model::OptionalDefaultConstructionSet] an optional default construction set

# File lib/openstudio-standards/standards/Standards.Model.rb, line 3331
def model_add_construction_set(model, climate_zone, building_type, spc_type, is_residential)
  construction_set = OpenStudio::Model::OptionalDefaultConstructionSet.new

  # Find the climate zone set that this climate zone falls into
  climate_zone_set = model_find_climate_zone_set(model, climate_zone)
  unless climate_zone_set
    return construction_set
  end

  # Get the object data
  data = model_find_object(standards_data['construction_sets'], 'template' => template, 'climate_zone_set' => climate_zone_set, 'building_type' => building_type, 'space_type' => spc_type, 'is_residential' => is_residential)
  unless data
    # Search again without the is_residential criteria in the case that this field is not specified for a standard
    data = model_find_object(standards_data['construction_sets'], 'template' => template, 'climate_zone_set' => climate_zone_set, 'building_type' => building_type, 'space_type' => spc_type)
    unless data
      # if nothing matches say that we could not find it
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Construction set for template =#{template}, climate zone set =#{climate_zone_set}, building type = #{building_type}, space type = #{spc_type}, is residential = #{is_residential} was not found in standards_data['construction_sets']")
      return construction_set
    end
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Adding construction set: #{template}-#{climate_zone}-#{building_type}-#{spc_type}-is_residential#{is_residential}")

  name = model_make_name(model, climate_zone, building_type, spc_type)

  # Create a new construction set and name it
  construction_set = OpenStudio::Model::DefaultConstructionSet.new(model)
  construction_set.setName(name)

  # Exterior surfaces constructions
  exterior_surfaces = OpenStudio::Model::DefaultSurfaceConstructions.new(model)
  construction_set.setDefaultExteriorSurfaceConstructions(exterior_surfaces)
  # Special condition for attics, where the insulation is actually on the floor but the soffit is uninsulated
  if spc_type == 'Attic'
    exterior_surfaces.setFloorConstruction(model_add_construction(model, 'Typical Attic Soffit'))
  else
    if data['exterior_floor_standards_construction_type'] && data['exterior_floor_building_category']
      exterior_surfaces.setFloorConstruction(model_find_and_add_construction(model,
                                                                             climate_zone_set,
                                                                             'ExteriorFloor',
                                                                             data['exterior_floor_standards_construction_type'],
                                                                             data['exterior_floor_building_category']))
    end
  end
  if data['exterior_wall_standards_construction_type'] && data['exterior_wall_building_category']
    exterior_surfaces.setWallConstruction(model_find_and_add_construction(model,
                                                                          climate_zone_set,
                                                                          'ExteriorWall',
                                                                          data['exterior_wall_standards_construction_type'],
                                                                          data['exterior_wall_building_category']))
  end
  # Special condition for attics, where the insulation is actually on the floor and the roof itself is uninsulated
  if spc_type == 'Attic'
    if data['exterior_roof_standards_construction_type'] && data['exterior_roof_building_category']
      exterior_surfaces.setRoofCeilingConstruction(model_add_construction(model, 'Typical Uninsulated Wood Joist Attic Roof'))
    end
  else
    if data['exterior_roof_standards_construction_type'] && data['exterior_roof_building_category']
      exterior_surfaces.setRoofCeilingConstruction(model_find_and_add_construction(model,
                                                                                   climate_zone_set,
                                                                                   'ExteriorRoof',
                                                                                   data['exterior_roof_standards_construction_type'],
                                                                                   data['exterior_roof_building_category']))
    end
  end
  # Interior surfaces constructions
  interior_surfaces = OpenStudio::Model::DefaultSurfaceConstructions.new(model)
  construction_set.setDefaultInteriorSurfaceConstructions(interior_surfaces)
  construction_name = data['interior_floors']
  # Special condition for attics, where the insulation is actually on the floor and the roof itself is uninsulated
  if spc_type == 'Attic'
    if data['exterior_roof_standards_construction_type'] && data['exterior_roof_building_category']
      interior_surfaces.setFloorConstruction(model_find_and_add_construction(model,
                                                                             climate_zone_set,
                                                                             'ExteriorRoof',
                                                                             data['exterior_roof_standards_construction_type'],
                                                                             data['exterior_roof_building_category']))

    end
  else
    unless construction_name.nil?
      interior_surfaces.setFloorConstruction(model_add_construction(model, construction_name))
    end
  end
  construction_name = data['interior_walls']
  unless construction_name.nil?
    interior_surfaces.setWallConstruction(model_add_construction(model, construction_name))
  end
  construction_name = data['interior_ceilings']
  unless construction_name.nil?
    interior_surfaces.setRoofCeilingConstruction(model_add_construction(model, construction_name))
  end

  # Ground contact surfaces constructions
  ground_surfaces = OpenStudio::Model::DefaultSurfaceConstructions.new(model)
  construction_set.setDefaultGroundContactSurfaceConstructions(ground_surfaces)
  if data['ground_contact_floor_standards_construction_type'] && data['ground_contact_floor_building_category']
    ground_surfaces.setFloorConstruction(model_find_and_add_construction(model,
                                                                         climate_zone_set,
                                                                         'GroundContactFloor',
                                                                         data['ground_contact_floor_standards_construction_type'],
                                                                         data['ground_contact_floor_building_category']))
  end
  if data['ground_contact_wall_standards_construction_type'] && data['ground_contact_wall_building_category']
    ground_surfaces.setWallConstruction(model_find_and_add_construction(model,
                                                                        climate_zone_set,
                                                                        'GroundContactWall',
                                                                        data['ground_contact_wall_standards_construction_type'],
                                                                        data['ground_contact_wall_building_category']))
  end
  if data['ground_contact_ceiling_standards_construction_type'] && data['ground_contact_ceiling_building_category']
    ground_surfaces.setRoofCeilingConstruction(model_find_and_add_construction(model,
                                                                               climate_zone_set,
                                                                               'GroundContactRoof',
                                                                               data['ground_contact_ceiling_standards_construction_type'],
                                                                               data['ground_contact_ceiling_building_category']))

  end

  # Exterior sub surfaces constructions
  exterior_subsurfaces = OpenStudio::Model::DefaultSubSurfaceConstructions.new(model)
  construction_set.setDefaultExteriorSubSurfaceConstructions(exterior_subsurfaces)
  if data['exterior_fixed_window_standards_construction_type'] && data['exterior_fixed_window_building_category']
    exterior_subsurfaces.setFixedWindowConstruction(model_find_and_add_construction(model,
                                                                                    climate_zone_set,
                                                                                    'ExteriorWindow',
                                                                                    data['exterior_fixed_window_standards_construction_type'],
                                                                                    data['exterior_fixed_window_building_category']))
  end
  if data['exterior_operable_window_standards_construction_type'] && data['exterior_operable_window_building_category']
    exterior_subsurfaces.setOperableWindowConstruction(model_find_and_add_construction(model,
                                                                                       climate_zone_set,
                                                                                       'ExteriorWindow',
                                                                                       data['exterior_operable_window_standards_construction_type'],
                                                                                       data['exterior_operable_window_building_category']))
  end
  if data['exterior_door_standards_construction_type'] && data['exterior_door_building_category']
    exterior_subsurfaces.setDoorConstruction(model_find_and_add_construction(model,
                                                                             climate_zone_set,
                                                                             'ExteriorDoor',
                                                                             data['exterior_door_standards_construction_type'],
                                                                             data['exterior_door_building_category']))
  end
  if data['exterior_glass_door_standards_construction_type'] && data['exterior_glass_door_building_category']
    exterior_subsurfaces.setGlassDoorConstruction(model_find_and_add_construction(model,
                                                                                  climate_zone_set,
                                                                                  'GlassDoor',
                                                                                  data['exterior_glass_door_standards_construction_type'],
                                                                                  data['exterior_glass_door_building_category']))
  end
  if data['exterior_overhead_door_standards_construction_type'] && data['exterior_overhead_door_building_category']
    exterior_subsurfaces.setOverheadDoorConstruction(model_find_and_add_construction(model,
                                                                                     climate_zone_set,
                                                                                     'ExteriorDoor',
                                                                                     data['exterior_overhead_door_standards_construction_type'],
                                                                                     data['exterior_overhead_door_building_category']))
  end
  if data['exterior_skylight_standards_construction_type'] && data['exterior_skylight_building_category']
    exterior_subsurfaces.setSkylightConstruction(model_find_and_add_construction(model,
                                                                                 climate_zone_set,
                                                                                 'Skylight',
                                                                                 data['exterior_skylight_standards_construction_type'],
                                                                                 data['exterior_skylight_building_category']))
  end
  if (construction_name = data['tubular_daylight_domes'])
    exterior_subsurfaces.setTubularDaylightDomeConstruction(model_add_construction(model, construction_name))
  end
  if (construction_name = data['tubular_daylight_diffusers'])
    exterior_subsurfaces.setTubularDaylightDiffuserConstruction(model_add_construction(model, construction_name))
  end

  # Interior sub surfaces constructions
  interior_subsurfaces = OpenStudio::Model::DefaultSubSurfaceConstructions.new(model)
  construction_set.setDefaultInteriorSubSurfaceConstructions(interior_subsurfaces)
  if (construction_name = data['interior_fixed_windows'])
    interior_subsurfaces.setFixedWindowConstruction(model_add_construction(model, construction_name))
  end
  if (construction_name = data['interior_operable_windows'])
    interior_subsurfaces.setOperableWindowConstruction(model_add_construction(model, construction_name))
  end
  if (construction_name = data['interior_doors'])
    interior_subsurfaces.setDoorConstruction(model_add_construction(model, construction_name))
  end

  # Other constructions
  if (construction_name = data['interior_partitions'])
    construction_set.setInteriorPartitionConstruction(model_add_construction(model, construction_name))
  end
  if (construction_name = data['space_shading'])
    construction_set.setSpaceShadingConstruction(model_add_construction(model, construction_name))
  end
  if (construction_name = data['building_shading'])
    construction_set.setBuildingShadingConstruction(model_add_construction(model, construction_name))
  end
  if (construction_name = data['site_shading'])
    construction_set.setSiteShadingConstruction(model_add_construction(model, construction_name))
  end

  # componentize the construction set
  # construction_set_component = construction_set.createComponent

  # Return the construction set
  return OpenStudio::Model::OptionalDefaultConstructionSet.new(construction_set)
end
model_add_crac(model, thermal_zones, climate_zone, system_name: nil, hvac_op_sch: nil, oa_damper_sch: nil, fan_location: 'DrawThrough', fan_type: 'ConstantVolume', cooling_type: 'Single Speed DX AC', supply_temp_sch: nil) click to toggle source

Creates a CRAC system for data center and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param system_name [String] the name of the system, or nil in which case it will be defaulted @param thermal_zones [String] zones to connect to this system @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [Double] name of the oa damper schedule, or nil in which case will be defaulted to always open @param fan_location [Double] valid choices are BlowThrough, DrawThrough @param fan_type [Double] valid choices are ConstantVolume, Cycling, VariableVolume no heating @param cooling_type [String] valid choices are Two Speed DX AC, Single Speed DX AC @return [Array<OpenStudio::Model::AirLoopHVAC>] an array of the resulting CRAC air loops

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 3375
def model_add_crac(model,
                   thermal_zones,
                   climate_zone,
                   system_name: nil,
                   hvac_op_sch: nil,
                   oa_damper_sch: nil,
                   fan_location: 'DrawThrough',
                   fan_type: 'ConstantVolume',
                   cooling_type: 'Single Speed DX AC',
                   supply_temp_sch: nil)

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # Make a CRAC for each data center zone
  air_loops = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding CRAC for #{zone.name}.")

    air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
    if system_name.nil?
      air_loop.setName("#{zone.name} CRAC")
    else
      air_loop.setName("#{zone.name} #{system_name}")
    end

    # default design temperatures across all air loops
    dsgn_temps = standard_design_sizing_temperatures

    # adjusted zone design heating temperature for data center psz_ac
    dsgn_temps['prehtg_dsgn_sup_air_temp_f'] = 64.4
    dsgn_temps['preclg_dsgn_sup_air_temp_f'] = 80.6
    dsgn_temps['htg_dsgn_sup_air_temp_f'] = 55
    dsgn_temps['clg_dsgn_sup_air_temp_f'] = 55
    dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = dsgn_temps['htg_dsgn_sup_air_temp_f']
    dsgn_temps['zn_clg_dsgn_sup_air_temp_f'] = dsgn_temps['clg_dsgn_sup_air_temp_f']
    dsgn_temps['prehtg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['prehtg_dsgn_sup_air_temp_f'], 'F', 'C').get
    dsgn_temps['preclg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['preclg_dsgn_sup_air_temp_f'], 'F', 'C').get
    dsgn_temps['htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['htg_dsgn_sup_air_temp_f'], 'F', 'C').get
    dsgn_temps['clg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['clg_dsgn_sup_air_temp_f'], 'F', 'C').get
    dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
    dsgn_temps['zn_clg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_clg_dsgn_sup_air_temp_f'], 'F', 'C').get

    # default design settings used across all air loops
    sizing_system = adjust_sizing_system(air_loop, dsgn_temps, min_sys_airflow_ratio: 0.05)

    # Zone sizing
    sizing_zone = zone.sizingZone
    # per ASHRAE 90.4, recommended range of data center supply air temperature is 18-27C, pick the mean value 22.5C as prototype
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])

    # create fan
    # ConstantVolume: Packaged Rooftop Single Zone Air conditioner
    # Cycling: Unitary System
    # CyclingHeatPump: Unitary Heat Pump system
    if fan_type == 'VariableVolume'
      fan = create_fan_by_name(model,
                               'CRAC_VAV_fan',
                               fan_name: "#{air_loop.name} Fan")
      fan.setAvailabilitySchedule(hvac_op_sch)
    elsif fan_type == 'ConstantVolume'
      fan = create_fan_by_name(model,
                               'CRAC_CAV_fan',
                               fan_name: "#{air_loop.name} Fan")
      fan.setAvailabilitySchedule(hvac_op_sch)
    elsif fan_type == 'Cycling'
      fan = create_fan_by_name(model,
                               'CRAC_Cycling_fan',
                               fan_name: "#{air_loop.name} Fan")
      fan.setAvailabilitySchedule(hvac_op_sch)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Fan type '#{fan_type}' not recognized, cannot add CRAC.")
      return false
    end

    # create cooling coil
    case cooling_type
    when 'Two Speed DX AC'
      clg_coil = create_coil_cooling_dx_two_speed(model,
                                                  name: "#{air_loop.name} 2spd DX AC Clg Coil")
    when 'Single Speed DX AC'
      clg_coil = create_coil_cooling_dx_single_speed(model,
                                                     name: "#{air_loop.name} 1spd DX AC Clg Coil",
                                                     type: 'PSZ-AC')
    else
      clg_coil = nil
    end

    oa_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
    oa_controller.setName("#{air_loop.name} OA System Controller")
    oa_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
    oa_system = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_controller)
    oa_system.setName("#{air_loop.name} OA System")

    # CRAC can't operate properly at very low ambient temperature (E+ limit: -25C)
    # As a result, the room temperature will rise to HUGE
    # Adding economizer can solve the issue, but economizer is not added until first sizing done, which causes severe error during sizing
    # To solve the issue, add economizer here for cold climates
    # select the climate zones with winter design temperature lower than -20C (for safer)
    cold_climates = ['ASHRAE 169-2006-6A', 'ASHRAE 169-2006-6B', 'ASHRAE 169-2006-7A',
                     'ASHRAE 169-2006-7B', 'ASHRAE 169-2006-8A', 'ASHRAE 169-2006-8B',
                     'ASHRAE 169-2013-6A', 'ASHRAE 169-2013-6B', 'ASHRAE 169-2013-7A',
                     'ASHRAE 169-2013-7B', 'ASHRAE 169-2013-8A', 'ASHRAE 169-2013-8B']
    if cold_climates.include? climate_zone
      # Determine the economizer type in the prototype buildings, which depends on climate zone.
      economizer_type = model_economizer_type(model, climate_zone)
      oa_controller.setEconomizerControlType(economizer_type)

      # Check that the economizer type set by the prototypes
      # is not prohibited by code.  If it is, change to no economizer.
      unless air_loop_hvac_economizer_type_allowable?(air_loop, climate_zone)
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.Model', "#{air_loop.name} is required to have an economizer, but the type chosen, #{economizer_type} is prohibited by code for , climate zone #{climate_zone}.  Economizer type will be switched to No Economizer.")
        oa_controller.setEconomizerControlType('NoEconomizer')
      end
    end

    # add humidifier to control minimum RH
    humidifier = OpenStudio::Model::HumidifierSteamElectric.new(model)
    humidifier.autosizeRatedCapacity
    humidifier.autosizeRatedPower
    humidifier.setName("#{air_loop.name} Electric Steam Humidifier")

    # Add the components to the air loop
    # in order from closest to zone to furthest from zone
    supply_inlet_node = air_loop.supplyInletNode

    if fan_location == 'DrawThrough'
      # Add the fan
      fan.addToNode(supply_inlet_node) unless fan.nil?
      # Add the humidifier
      humidifier.addToNode(supply_inlet_node) unless humidifier.nil?
      # Add the cooling coil
      clg_coil.addToNode(supply_inlet_node) unless clg_coil.nil?

    elsif fan_location == 'BlowThrough'
      # Add the humidifier
      humidifier.addToNode(supply_inlet_node) unless humidifier.nil?
      # Add the cooling coil
      clg_coil.addToNode(supply_inlet_node) unless clg_coil.nil?
      # Add the fan
      fan.addToNode(supply_inlet_node) unless fan.nil?

    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Invalid fan location')
      return false
    end

    # add humidifying setpoint
    humidity_spm = OpenStudio::Model::SetpointManagerSingleZoneHumidityMinimum.new(model)
    humidity_spm.setControlZone(zone)
    humidity_spm.addToNode(humidifier.outletModelObject.get.to_Node.get)

    humidistat = OpenStudio::Model::ZoneControlHumidistat.new(model)
    humidistat.setHumidifyingRelativeHumiditySetpointSchedule(model_add_schedule(model, 'DataCenter Humidity Setpoint Schedule'))
    zone.setZoneControlHumidistat(humidistat)

    # Add a setpoint manager for cooling to control the supply air temperature based on the needs of this zone
    if supply_temp_sch.nil?
      supply_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                        dsgn_temps['clg_dsgn_sup_air_temp_c'],
                                                                                        name: 'AHU Supply Temp Sch',
                                                                                        schedule_type_limit: 'Temperature')
    end
    setpoint_mgr_cooling = OpenStudio::Model::SetpointManagerScheduled.new(model, supply_temp_sch)
    setpoint_mgr_cooling.setName('CRAC supply air setpoint manager')
    setpoint_mgr_cooling.addToNode(air_loop.supplyOutletNode)

    # Add the OA system
    oa_system.addToNode(supply_inlet_node)

    # set air loop availability controls
    air_loop.setAvailabilitySchedule(hvac_op_sch)

    # Create a diffuser and attach the zone/diffuser pair to the air loop
    diffuser = OpenStudio::Model::AirTerminalSingleDuctVAVNoReheat.new(model, model.alwaysOnDiscreteSchedule)
    diffuser.setName("#{air_loop.name} Diffuser")
    if model.version < OpenStudio::VersionString.new('3.0.1')
      diffuser.setZoneMinimumAirFlowMethod('Constant')
    else
      diffuser.setZoneMinimumAirFlowInputMethod('Constant')
    end
    diffuser.setConstantMinimumAirFlowFraction(0.1)
    air_loop.multiAddBranchForZone(zone, diffuser.to_HVACComponent.get)

    air_loops << air_loop
  end

  return air_loops
end
model_add_crah(model, thermal_zones, system_name: nil, chilled_water_loop: nil, hvac_op_sch: nil, oa_damper_sch: nil, return_plenum: nil, supply_temp_sch: nil) click to toggle source

Creates a CRAH system for larger size data center and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param chilled_water_loop [String @param system_name [String] the name of the system, or nil in which case it will be defaulted @param thermal_zones [String] zones to connect to this system @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [Double] name of the oa damper schedule, or nil in which case will be defaulted to always open no heating @return [Array<OpenStudio::Model::AirLoopHVAC>] an array of the resulting CRAH air loops

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 3589
def model_add_crah(model,
                   thermal_zones,
                   system_name: nil,
                   chilled_water_loop: nil,
                   hvac_op_sch: nil,
                   oa_damper_sch: nil,
                   return_plenum: nil,
                   supply_temp_sch: nil)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding CRAH system for #{thermal_zones.size} zones data center.")
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "---#{zone.name}")
  end

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # air handler
  air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
  if system_name.nil?
    air_loop.setName('Data Center CRAH')
  else
    air_loop.setName(system_name)
  end

  # default design temperatures across all air loops
  dsgn_temps = standard_design_sizing_temperatures

  # adjusted zone design heating temperature for data center psz_ac
  dsgn_temps['prehtg_dsgn_sup_air_temp_f'] = 64.4
  dsgn_temps['preclg_dsgn_sup_air_temp_f'] = 80.6
  dsgn_temps['htg_dsgn_sup_air_temp_f'] = 55
  dsgn_temps['clg_dsgn_sup_air_temp_f'] = 55
  dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = dsgn_temps['htg_dsgn_sup_air_temp_f']
  dsgn_temps['zn_clg_dsgn_sup_air_temp_f'] = dsgn_temps['clg_dsgn_sup_air_temp_f']
  dsgn_temps['prehtg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['prehtg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['preclg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['preclg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['clg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['clg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = dsgn_temps['htg_dsgn_sup_air_temp_c']
  dsgn_temps['zn_clg_dsgn_sup_air_temp_c'] = dsgn_temps['clg_dsgn_sup_air_temp_c']

  # default design settings used across all air loops
  sizing_system = adjust_sizing_system(air_loop, dsgn_temps, min_sys_airflow_ratio: 0.3)

  # Add a setpoint manager for cooling to control the supply air temperature based on the needs of this zone
  if supply_temp_sch.nil?
    supply_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                      dsgn_temps['clg_dsgn_sup_air_temp_c'],
                                                                                      name: 'AHU Supply Temp Sch',
                                                                                      schedule_type_limit: 'Temperature')
  end
  setpoint_mgr_cooling = OpenStudio::Model::SetpointManagerScheduled.new(model, supply_temp_sch)
  setpoint_mgr_cooling.setName('CRAH supply air setpoint manager')
  setpoint_mgr_cooling.addToNode(air_loop.supplyOutletNode)

  # create fan
  fan = create_fan_by_name(model,
                           'VAV_System_Fan',
                           fan_name: "#{air_loop.name} Fan")
  fan.setAvailabilitySchedule(hvac_op_sch)
  fan.addToNode(air_loop.supplyInletNode)

  # add humidifier to control minimum RH
  humidifier = OpenStudio::Model::HumidifierSteamElectric.new(model)
  humidifier.autosizeRatedCapacity
  humidifier.autosizeRatedPower
  humidifier.setName("#{air_loop.name} Electric Steam Humidifier")
  humidifier.addToNode(air_loop.supplyInletNode)

  # cooling coil
  if chilled_water_loop.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'No chilled water plant loop supplied for CRAH system')
    return false
  else
    create_coil_cooling_water(model,
                              chilled_water_loop,
                              air_loop_node: air_loop.supplyInletNode,
                              name: "#{air_loop.name} Water Clg Coil",
                              schedule: hvac_op_sch)
  end

  # outdoor air intake system
  oa_intake_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
  oa_intake_controller.setName("#{air_loop.name} OA Controller")
  oa_intake_controller.setMinimumLimitType('FixedMinimum')
  oa_intake_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
  oa_intake_controller.autosizeMinimumOutdoorAirFlowRate

  controller_mv = oa_intake_controller.controllerMechanicalVentilation
  controller_mv.setName("#{air_loop.name} Vent Controller")
  controller_mv.setSystemOutdoorAirMethod('ZoneSum')

  oa_intake = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_intake_controller)
  oa_intake.setName("#{air_loop.name} OA System")
  oa_intake.addToNode(air_loop.supplyInletNode)

  # set air loop availability controls
  air_loop.setAvailabilitySchedule(hvac_op_sch)

  # hook the CRAH system to each zone
  thermal_zones.each do |zone|
    # Create a diffuser and attach the zone/diffuser pair to the air loop
    diffuser = OpenStudio::Model::AirTerminalSingleDuctVAVNoReheat.new(model, model.alwaysOnDiscreteSchedule)
    diffuser.setName("#{zone.name} VAV terminal")
    if model.version < OpenStudio::VersionString.new('3.0.1')
      diffuser.setZoneMinimumAirFlowMethod('Constant')
    else
      diffuser.setZoneMinimumAirFlowInputMethod('Constant')
    end
    diffuser.setConstantMinimumAirFlowFraction(0.1)
    air_loop.multiAddBranchForZone(zone, diffuser.to_HVACComponent.get)

    # Zone sizing
    sizing_zone = zone.sizingZone
    # per ASHRAE 90.4, recommended range of data center supply air temperature is 18-27C, pick the mean value 22.5C as prototype
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])

    humidity_spm = OpenStudio::Model::SetpointManagerSingleZoneHumidityMinimum.new(model)
    humidity_spm.setControlZone(zone)
    humidity_spm.addToNode(humidifier.outletModelObject.get.to_Node.get)

    humidistat = OpenStudio::Model::ZoneControlHumidistat.new(model)
    humidistat.setHumidifyingRelativeHumiditySetpointSchedule(model_add_schedule(model, 'DataCenter Humidity Setpoint Schedule'))
    zone.setZoneControlHumidistat(humidistat)

    unless return_plenum.nil?
      zone.setReturnPlenum(return_plenum)
    end
  end

  return air_loop
end
model_add_curve(model, curve_name) click to toggle source

Adds a curve from the OpenStudio-Standards dataset to the model based on the curve name.

@param model [OpenStudio::Model::Model] OpenStudio model object @param curve_name [String] name of the curve @return [OpenStudio::Model::Curve] curve object, nil if not found

# File lib/openstudio-standards/standards/Standards.Model.rb, line 3541
def model_add_curve(model, curve_name)
  # First check model and return curve if it already exists
  existing_curves = []
  existing_curves += model.getCurveLinears
  existing_curves += model.getCurveCubics
  existing_curves += model.getCurveQuadratics
  existing_curves += model.getCurveBicubics
  existing_curves += model.getCurveBiquadratics
  existing_curves += model.getCurveQuadLinears
  existing_curves += model.getTableMultiVariableLookups
  existing_curves += model.getTableLookups
  existing_curves.sort.each do |curve|
    if curve.name.get.to_s == curve_name
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Already added curve: #{curve_name}")
      return curve
    end
  end

  # Find curve data
  data = model_find_object(standards_data['curves'], 'name' => curve_name)
  if data.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "Could not find a curve called '#{curve_name}' in the standards.")
    return nil
  end

  # Make the correct type of curve
  case data['form']
    when 'Linear'
      curve = OpenStudio::Model::CurveLinear.new(model)
      curve.setName(data['name'])
      curve.setCoefficient1Constant(data['coeff_1'])
      curve.setCoefficient2x(data['coeff_2'])
      curve.setMinimumValueofx(data['minimum_independent_variable_1']) if data['minimum_independent_variable_1']
      curve.setMaximumValueofx(data['maximum_independent_variable_1']) if data['maximum_independent_variable_1']
      curve.setMinimumCurveOutput(data['minimum_dependent_variable_output']) if data['minimum_dependent_variable_output']
      curve.setMaximumCurveOutput(data['maximum_dependent_variable_output']) if data['maximum_dependent_variable_output']
      return curve
    when 'Cubic'
      curve = OpenStudio::Model::CurveCubic.new(model)
      curve.setName(data['name'])
      curve.setCoefficient1Constant(data['coeff_1'])
      curve.setCoefficient2x(data['coeff_2'])
      curve.setCoefficient3xPOW2(data['coeff_3'])
      curve.setCoefficient4xPOW3(data['coeff_4'])
      curve.setMinimumValueofx(data['minimum_independent_variable_1']) if data['minimum_independent_variable_1']
      curve.setMaximumValueofx(data['maximum_independent_variable_1']) if data['maximum_independent_variable_1']
      curve.setMinimumCurveOutput(data['minimum_dependent_variable_output']) if data['minimum_dependent_variable_output']
      curve.setMaximumCurveOutput(data['maximum_dependent_variable_output']) if data['maximum_dependent_variable_output']
      return curve
    when 'Quadratic'
      curve = OpenStudio::Model::CurveQuadratic.new(model)
      curve.setName(data['name'])
      curve.setCoefficient1Constant(data['coeff_1'])
      curve.setCoefficient2x(data['coeff_2'])
      curve.setCoefficient3xPOW2(data['coeff_3'])
      curve.setMinimumValueofx(data['minimum_independent_variable_1']) if data['minimum_independent_variable_1']
      curve.setMaximumValueofx(data['maximum_independent_variable_1']) if data['maximum_independent_variable_1']
      curve.setMinimumCurveOutput(data['minimum_dependent_variable_output']) if data['minimum_dependent_variable_output']
      curve.setMaximumCurveOutput(data['maximum_dependent_variable_output']) if data['maximum_dependent_variable_output']
      return curve
    when 'BiCubic'
      curve = OpenStudio::Model::CurveBicubic.new(model)
      curve.setName(data['name'])
      curve.setCoefficient1Constant(data['coeff_1'])
      curve.setCoefficient2x(data['coeff_2'])
      curve.setCoefficient3xPOW2(data['coeff_3'])
      curve.setCoefficient4y(data['coeff_4'])
      curve.setCoefficient5yPOW2(data['coeff_5'])
      curve.setCoefficient6xTIMESY(data['coeff_6'])
      curve.setCoefficient7xPOW3(data['coeff_7'])
      curve.setCoefficient8yPOW3(data['coeff_8'])
      curve.setCoefficient9xPOW2TIMESY(data['coeff_9'])
      curve.setCoefficient10xTIMESYPOW2(data['coeff_10'])
      curve.setMinimumValueofx(data['minimum_independent_variable_1']) if data['minimum_independent_variable_1']
      curve.setMaximumValueofx(data['maximum_independent_variable_1']) if data['maximum_independent_variable_1']
      curve.setMinimumValueofy(data['minimum_independent_variable_2']) if data['minimum_independent_variable_2']
      curve.setMaximumValueofy(data['maximum_independent_variable_2']) if data['maximum_independent_variable_2']
      curve.setMinimumCurveOutput(data['minimum_dependent_variable_output']) if data['minimum_dependent_variable_output']
      curve.setMaximumCurveOutput(data['maximum_dependent_variable_output']) if data['maximum_dependent_variable_output']
      return curve
    when 'BiQuadratic'
      curve = OpenStudio::Model::CurveBiquadratic.new(model)
      curve.setName(data['name'])
      curve.setCoefficient1Constant(data['coeff_1'])
      curve.setCoefficient2x(data['coeff_2'])
      curve.setCoefficient3xPOW2(data['coeff_3'])
      curve.setCoefficient4y(data['coeff_4'])
      curve.setCoefficient5yPOW2(data['coeff_5'])
      curve.setCoefficient6xTIMESY(data['coeff_6'])
      curve.setMinimumValueofx(data['minimum_independent_variable_1']) if data['minimum_independent_variable_1']
      curve.setMaximumValueofx(data['maximum_independent_variable_1']) if data['maximum_independent_variable_1']
      curve.setMinimumValueofy(data['minimum_independent_variable_2']) if data['minimum_independent_variable_2']
      curve.setMaximumValueofy(data['maximum_independent_variable_2']) if data['maximum_independent_variable_2']
      curve.setMinimumCurveOutput(data['minimum_dependent_variable_output']) if data['minimum_dependent_variable_output']
      curve.setMaximumCurveOutput(data['maximum_dependent_variable_output']) if data['maximum_dependent_variable_output']
      return curve
    when 'BiLinear'
      curve = OpenStudio::Model::CurveBiquadratic.new(model)
      curve.setName(data['name'])
      curve.setCoefficient1Constant(data['coeff_1'])
      curve.setCoefficient2x(data['coeff_2'])
      curve.setCoefficient4y(data['coeff_3'])
      curve.setMinimumValueofx(data['minimum_independent_variable_1']) if data['minimum_independent_variable_1']
      curve.setMaximumValueofx(data['maximum_independent_variable_1']) if data['maximum_independent_variable_1']
      curve.setMinimumValueofy(data['minimum_independent_variable_2']) if data['minimum_independent_variable_2']
      curve.setMaximumValueofy(data['maximum_independent_variable_2']) if data['maximum_independent_variable_2']
      curve.setMinimumCurveOutput(data['minimum_dependent_variable_output']) if data['minimum_dependent_variable_output']
      curve.setMaximumCurveOutput(data['maximum_dependent_variable_output']) if data['maximum_dependent_variable_output']
      return curve
    when 'QuadLinear'
      curve = OpenStudio::Model::CurveQuadLinear.new(model)
      curve.setName(data['name'])
      curve.setCoefficient1Constant(data['coeff_1'])
      curve.setCoefficient2w(data['coeff_2'])
      curve.setCoefficient3x(data['coeff_3'])
      curve.setCoefficient4y(data['coeff_4'])
      curve.setCoefficient5z(data['coeff_5'])
      curve.setMinimumValueofw(data['minimum_independent_variable_w'])
      curve.setMaximumValueofw(data['maximum_independent_variable_w'])
      curve.setMinimumValueofx(data['minimum_independent_variable_x'])
      curve.setMaximumValueofx(data['maximum_independent_variable_x'])
      curve.setMinimumValueofy(data['minimum_independent_variable_y'])
      curve.setMaximumValueofy(data['maximum_independent_variable_y'])
      curve.setMinimumValueofz(data['minimum_independent_variable_z'])
      curve.setMaximumValueofz(data['maximum_independent_variable_z'])
      curve.setMinimumCurveOutput(data['minimum_dependent_variable_output'])
      curve.setMaximumCurveOutput(data['maximum_dependent_variable_output'])
      return curve
    when 'TableLookup', 'LookupTable', 'TableMultiVariableLookup', 'MultiVariableLookupTable'
      num_ind_var = data['number_independent_variables'].to_i
      if model.version < OpenStudio::VersionString.new('3.7.0')
        # Use TableMultiVariableLookup object
        table = OpenStudio::Model::TableMultiVariableLookup.new(model, num_ind_var)
        table.setInterpolationMethod(data['interpolation_method'])
        table.setNumberofInterpolationPoints(data['number_of_interpolation_points'])
        table.setCurveType(data['curve_type'])
        table.setTableDataFormat('SingleLineIndependentVariableWithMatrix')
        table.setNormalizationReference(data['normalization_reference'].to_f)

        # set table limits
        table.setMinimumValueofX1(data['minimum_independent_variable_1'].to_f)
        table.setMaximumValueofX1(data['maximum_independent_variable_1'].to_f)
        table.setInputUnitTypeforX1(data['input_unit_type_x1'])
        if num_ind_var == 2
          table.setMinimumValueofX2(data['minimum_independent_variable_2'].to_f)
          table.setMaximumValueofX2(data['maximum_independent_variable_2'].to_f)
          table.setInputUnitTypeforX2(data['input_unit_type_x2'])
        end

        # add data points
        data_points = data.each.select { |key, value| key.include? 'data_point' }
        data_points.each do |key, value|
          if num_ind_var == 1
            table.addPoint(value.split(',')[0].to_f, value.split(',')[1].to_f)
          elsif num_ind_var == 2
            table.addPoint(value.split(',')[0].to_f, value.split(',')[1].to_f, value.split(',')[2].to_f)
          end
        end
      else
        # Use TableLookup Object
        table = OpenStudio::Model::TableLookup.new(model)
        table.setNormalizationDivisor(data['normalization_reference'].to_f)

        # sorting data in ascending order
        data_points = data.each.select { |key, value| key.include? 'data_point' }
        data_points = data_points.sort_by { |item| item[1].split(',').map(&:to_f) }
        data_points.each do |key, value|
          var_dep = value.split(',')[2].to_f
          table.addOutputValue(var_dep)
        end
        num_ind_var.times do |i|
          table_indvar = OpenStudio::Model::TableIndependentVariable.new(model)
          table_indvar.setName(data['name'] + "_ind_#{i + 1}")
          table_indvar.setInterpolationMethod(data['interpolation_method'])

          # set table limits
          table_indvar.setMinimumValue(data["minimum_independent_variable_#{i + 1}"].to_f)
          table_indvar.setMaximumValue(data["maximum_independent_variable_#{i + 1}"].to_f)
          table_indvar.setUnitType(data["input_unit_type_x#{i + 1}"].to_s)

          # add data points
          var_ind_unique = data_points.map { |key, value| value.split(',')[i].to_f }.uniq
          var_ind_unique.each { |var_ind| table_indvar.addValue(var_ind) }
          table.addIndependentVariable(table_indvar)
        end
      end
      table.setName(data['name'])
      table.setOutputUnitType(data['output_unit_type'])
      return table
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "#{curve_name}' has an invalid form: #{data['form']}', cannot create this curve.")
      return nil
  end
end
model_add_cw_loop(model, system_name: 'Condenser Water Loop', cooling_tower_type: 'Open Cooling Tower', cooling_tower_fan_type: 'Propeller or Axial', cooling_tower_capacity_control: 'TwoSpeed Fan', number_of_cells_per_tower: 1, number_cooling_towers: 1, use_90_1_design_sizing: true, sup_wtr_temp: 70.0, dsgn_sup_wtr_temp: 85.0, dsgn_sup_wtr_temp_delt: 10.0, wet_bulb_approach: 7.0, pump_spd_ctrl: 'Constant', pump_tot_hd: 49.7) click to toggle source

Creates a condenser water loop and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param system_name [String] the name of the system, or nil in which case it will be defaulted @param cooling_tower_type [String] valid choices are Open Cooling Tower, Closed Cooling Tower @param cooling_tower_fan_type [String] valid choices are Centrifugal, “Propeller or Axial” @param cooling_tower_capacity_control [String] valid choices are Fluid Bypass, Fan Cycling, TwoSpeed Fan, Variable Speed Fan @param number_of_cells_per_tower [Integer] the number of discrete cells per tower @param number_cooling_towers [Integer] the number of cooling towers to be added (in parallel) @param use_90_1_design_sizing [Boolean] will determine the design sizing temperatures based on the 90.1 Appendix G approach.

Overrides sup_wtr_temp, dsgn_sup_wtr_temp, dsgn_sup_wtr_temp_delt, and wet_bulb_approach if true.

@param sup_wtr_temp [Double] supply water temperature in degrees Fahrenheit, default 70F @param dsgn_sup_wtr_temp [Double] design supply water temperature in degrees Fahrenheit, default 85F @param dsgn_sup_wtr_temp_delt [Double] design water range temperature in degrees Rankine, default 10R @param wet_bulb_approach [Double] design wet bulb approach temperature, default 7R @param pump_spd_ctrl [String] pump speed control type, Constant or Variable (default) @param pump_tot_hd [Double] pump head in ft H2O @return [OpenStudio::Model::PlantLoop] the resulting condenser water plant loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 472
def model_add_cw_loop(model,
                      system_name: 'Condenser Water Loop',
                      cooling_tower_type: 'Open Cooling Tower',
                      cooling_tower_fan_type: 'Propeller or Axial',
                      cooling_tower_capacity_control: 'TwoSpeed Fan',
                      number_of_cells_per_tower: 1,
                      number_cooling_towers: 1,
                      use_90_1_design_sizing: true,
                      sup_wtr_temp: 70.0,
                      dsgn_sup_wtr_temp: 85.0,
                      dsgn_sup_wtr_temp_delt: 10.0,
                      wet_bulb_approach: 7.0,
                      pump_spd_ctrl: 'Constant',
                      pump_tot_hd: 49.7)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', 'Adding condenser water loop.')

  # create condenser water loop
  condenser_water_loop = OpenStudio::Model::PlantLoop.new(model)
  if system_name.nil?
    condenser_water_loop.setName('Condenser Water Loop')
  else
    condenser_water_loop.setName(system_name)
  end

  # condenser water loop sizing and controls
  if sup_wtr_temp.nil?
    sup_wtr_temp = 70.0
    sup_wtr_temp_c = OpenStudio.convert(sup_wtr_temp, 'F', 'C').get
  else
    sup_wtr_temp_c = OpenStudio.convert(sup_wtr_temp, 'F', 'C').get
  end
  if dsgn_sup_wtr_temp.nil?
    dsgn_sup_wtr_temp = 85.0
    dsgn_sup_wtr_temp_c = OpenStudio.convert(dsgn_sup_wtr_temp, 'F', 'C').get
  else
    dsgn_sup_wtr_temp_c = OpenStudio.convert(dsgn_sup_wtr_temp, 'F', 'C').get
  end
  if dsgn_sup_wtr_temp_delt.nil?
    dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(10.0, 'R', 'K').get
  else
    dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(dsgn_sup_wtr_temp_delt, 'R', 'K').get
  end
  if wet_bulb_approach.nil?
    wet_bulb_approach_k = OpenStudio.convert(7.0, 'R', 'K').get
  else
    wet_bulb_approach_k = OpenStudio.convert(wet_bulb_approach, 'R', 'K').get
  end
  condenser_water_loop.setMinimumLoopTemperature(5.0)
  condenser_water_loop.setMaximumLoopTemperature(80.0)
  sizing_plant = condenser_water_loop.sizingPlant
  sizing_plant.setLoopType('Condenser')
  sizing_plant.setDesignLoopExitTemperature(dsgn_sup_wtr_temp_c)
  sizing_plant.setLoopDesignTemperatureDifference(dsgn_sup_wtr_temp_delt_k)
  sizing_plant.setSizingOption('Coincident')
  sizing_plant.setZoneTimestepsinAveragingWindow(6)
  sizing_plant.setCoincidentSizingFactorMode('GlobalCoolingSizingFactor')

  # follow outdoor air wetbulb with given approach temperature
  cw_stpt_manager = OpenStudio::Model::SetpointManagerFollowOutdoorAirTemperature.new(model)
  cw_stpt_manager.setName("#{condenser_water_loop.name} Setpoint Manager Follow OATwb with #{wet_bulb_approach}F Approach")
  cw_stpt_manager.setReferenceTemperatureType('OutdoorAirWetBulb')
  cw_stpt_manager.setMaximumSetpointTemperature(dsgn_sup_wtr_temp_c)
  cw_stpt_manager.setMinimumSetpointTemperature(sup_wtr_temp_c)
  cw_stpt_manager.setOffsetTemperatureDifference(wet_bulb_approach_k)
  cw_stpt_manager.addToNode(condenser_water_loop.supplyOutletNode)

  # create condenser water pump
  case pump_spd_ctrl
  when 'Constant'
    cw_pump = OpenStudio::Model::PumpConstantSpeed.new(model)
  when 'Variable'
    cw_pump = OpenStudio::Model::PumpVariableSpeed.new(model)
  when 'HeaderedVariable'
    cw_pump = OpenStudio::Model::HeaderedPumpsVariableSpeed.new(model)
    cw_pump.setNumberofPumpsinBank(2)
  when 'HeaderedConstant'
    cw_pump = OpenStudio::Model::HeaderedPumpsConstantSpeed.new(model)
    cw_pump.setNumberofPumpsinBank(2)
  else
    cw_pump = OpenStudio::Model::PumpConstantSpeed.new(model)
  end
  cw_pump.setName("#{condenser_water_loop.name} #{pump_spd_ctrl} Pump")
  cw_pump.setPumpControlType('Intermittent')

  if pump_tot_hd.nil?
    pump_tot_hd_pa =  OpenStudio.convert(49.7, 'ftH_{2}O', 'Pa').get
  else
    pump_tot_hd_pa =  OpenStudio.convert(pump_tot_hd, 'ftH_{2}O', 'Pa').get
  end
  cw_pump.setRatedPumpHead(pump_tot_hd_pa)
  cw_pump.addToNode(condenser_water_loop.supplyInletNode)

  # Cooling towers
  # Per PNNL PRM Reference Manual
  number_cooling_towers.times do |_i|
    # Tower object depends on the control type
    cooling_tower = nil
    case cooling_tower_capacity_control
    when 'Fluid Bypass', 'Fan Cycling'
      cooling_tower = OpenStudio::Model::CoolingTowerSingleSpeed.new(model)
      if cooling_tower_capacity_control == 'Fluid Bypass'
        cooling_tower.setCellControl('FluidBypass')
      else
        cooling_tower.setCellControl('FanCycling')
      end
    when 'TwoSpeed Fan'
      cooling_tower = OpenStudio::Model::CoolingTowerTwoSpeed.new(model)
      # @todo expose newer cooling tower sizing fields in API
      # cooling_tower.setLowFanSpeedAirFlowRateSizingFactor(0.5)
      # cooling_tower.setLowFanSpeedFanPowerSizingFactor(0.3)
      # cooling_tower.setLowFanSpeedUFactorTimesAreaSizingFactor
      # cooling_tower.setLowSpeedNominalCapacitySizingFactor
    when 'Variable Speed Fan'
      cooling_tower = OpenStudio::Model::CoolingTowerVariableSpeed.new(model)
      cooling_tower.setDesignRangeTemperature(dsgn_sup_wtr_temp_delt_k)
      cooling_tower.setDesignApproachTemperature(wet_bulb_approach_k)
      cooling_tower.setFractionofTowerCapacityinFreeConvectionRegime(0.125)
      twr_fan_curve = model_add_curve(model, 'VSD-TWR-FAN-FPLR')
      cooling_tower.setFanPowerRatioFunctionofAirFlowRateRatioCurve(twr_fan_curve)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Prototype.hvac_systems', "#{cooling_tower_capacity_control} is not a valid choice of cooling tower capacity control.  Valid choices are Fluid Bypass, Fan Cycling, TwoSpeed Fan, Variable Speed Fan.")
    end

    # Set the properties that apply to all tower types and attach to the condenser loop.
    unless cooling_tower.nil?
      cooling_tower.setName("#{cooling_tower_fan_type} #{cooling_tower_capacity_control} #{cooling_tower_type}")
      cooling_tower.setSizingFactor(1 / number_cooling_towers)
      cooling_tower.setNumberofCells(number_of_cells_per_tower)
      condenser_water_loop.addSupplyBranchForComponent(cooling_tower)
    end
  end

  # apply 90.1 sizing temperatures
  if use_90_1_design_sizing
    # use the formulation in 90.1-2010 G3.1.3.11 to set the approach temperature
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Prototype.hvac_systems', "Using the 90.1-2010 G3.1.3.11 approach temperature sizing methodology for condenser loop #{condenser_water_loop.name}.")

    # first, look in the model design day objects for sizing information
    summer_oat_wbs_f = []
    condenser_water_loop.model.getDesignDays.sort.each do |dd|
      next unless dd.dayType == 'SummerDesignDay'
      next unless dd.name.get.to_s.include?('WB=>MDB')

      if condenser_water_loop.model.version < OpenStudio::VersionString.new('3.3.0')
        if dd.humidityIndicatingType == 'Wetbulb'
          summer_oat_wb_c = dd.humidityIndicatingConditionsAtMaximumDryBulb
          summer_oat_wbs_f << OpenStudio.convert(summer_oat_wb_c, 'C', 'F').get
        else
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.hvac_systems', "For #{dd.name}, humidity is specified as #{dd.humidityIndicatingType}; cannot determine Twb.")
        end
      else
        if dd.humidityConditionType == 'Wetbulb' && dd.wetBulbOrDewPointAtMaximumDryBulb.is_initialized
          summer_oat_wbs_f << OpenStudio.convert(dd.wetBulbOrDewPointAtMaximumDryBulb.get, 'C', 'F').get
        else
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.hvac_systems', "For #{dd.name}, humidity is specified as #{dd.humidityConditionType}; cannot determine Twb.")
        end
      end
    end

    # if no design day objects are present in the model, attempt to load the .ddy file directly
    if summer_oat_wbs_f.size.zero?
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.hvac_systems', 'No valid WB=>MDB Summer Design Days were found in the model.  Attempting to load wet bulb sizing from the .ddy file directly.')
      if model.weatherFile.is_initialized && model.weatherFile.get.path.is_initialized
        weather_file_path = model.weatherFile.get.path.get.to_s
        # Run differently depending on whether running from embedded filesystem in OpenStudio CLI or not
        if weather_file_path[0] == ':' # Running from OpenStudio CLI
          # Attempt to load in the ddy file based on convention that it is in the same directory and has the same basename as the epw file.
          ddy_file = weather_file_path.gsub('.epw', '.ddy')
          if EmbeddedScripting.hasFile(ddy_file)
            ddy_string = EmbeddedScripting.getFileAsString(ddy_file)
            temp_ddy_path = "#{Dir.pwd}/in.ddy"
            File.open(temp_ddy_path, 'wb') do |f|
              f << ddy_string
              f.flush
            end
            ddy_model = OpenStudio::EnergyPlus.loadAndTranslateIdf(temp_ddy_path).get
            File.delete(temp_ddy_path) if File.exist?(temp_ddy_path)
          else
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.hvac_systems', "Could not locate a .ddy file for weather file path #{weather_file_path}")
          end
        else
          # Attempt to load in the ddy file based on convention that it is in the same directory and has the same basename as the epw file.
          ddy_file = "#{File.join(File.dirname(weather_file_path), File.basename(weather_file_path, '.*'))}.ddy"
          if File.exist? ddy_file
            ddy_model = OpenStudio::EnergyPlus.loadAndTranslateIdf(ddy_file).get
          else
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.hvac_systems', "Could not locate a .ddy file for weather file path #{weather_file_path}")
          end
        end

        unless ddy_model.nil?
          ddy_model.getDesignDays.sort.each do |dd|
            # Save the model wetbulb design conditions Condns WB=>MDB
            if dd.name.get.include? '4% Condns WB=>MDB'
              if model.version < OpenStudio::VersionString.new('3.3.0')
                summer_oat_wb_c = dd.humidityIndicatingConditionsAtMaximumDryBulb
                summer_oat_wbs_f << OpenStudio.convert(summer_oat_wb_c, 'C', 'F').get
              else
                if dd.wetBulbOrDewPointAtMaximumDryBulb.is_initialized
                  summer_oat_wb_c = dd.wetBulbOrDewPointAtMaximumDryBulb
                  summer_oat_wbs_f << OpenStudio.convert(summer_oat_wb_c, 'C', 'F').get
                end
              end

            end
          end
        end
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.hvac_systems', 'The model does not have a weather file object or path specified in the object. Cannot get .ddy file directory.')
      end
    end

    # if values are still absent, use the CTI rating condition 78F
    design_oat_wb_f = nil
    if summer_oat_wbs_f.size.zero?
      design_oat_wb_f = 78.0
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.hvac_systems', "For condenser loop #{condenser_water_loop.name}, no design day OATwb conditions found.  CTI rating condition of 78F OATwb will be used for sizing cooling towers.")
    else
      # Take worst case condition
      design_oat_wb_f = summer_oat_wbs_f.max
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Prototype.hvac_systems', "The maximum design wet bulb temperature from the Summer Design Day WB=>MDB is #{design_oat_wb_f} F")
    end
    design_oat_wb_c = OpenStudio.convert(design_oat_wb_f, 'F', 'C').get

    # call method to apply design sizing to the condenser water loop
    prototype_apply_condenser_water_temperatures(condenser_water_loop, design_wet_bulb_c: design_oat_wb_c)
  end

  # Condenser water loop pipes
  cooling_tower_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  cooling_tower_bypass_pipe.setName("#{condenser_water_loop.name} Cooling Tower Bypass")
  condenser_water_loop.addSupplyBranchForComponent(cooling_tower_bypass_pipe)

  chiller_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  chiller_bypass_pipe.setName("#{condenser_water_loop.name} Chiller Bypass")
  condenser_water_loop.addDemandBranchForComponent(chiller_bypass_pipe)

  supply_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_outlet_pipe.setName("#{condenser_water_loop.name} Supply Outlet")
  supply_outlet_pipe.addToNode(condenser_water_loop.supplyOutletNode)

  demand_inlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_inlet_pipe.setName("#{condenser_water_loop.name} Demand Inlet")
  demand_inlet_pipe.addToNode(condenser_water_loop.demandInletNode)

  demand_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_outlet_pipe.setName("#{condenser_water_loop.name} Demand Outlet")
  demand_outlet_pipe.addToNode(condenser_water_loop.demandOutletNode)

  return condenser_water_loop
end
model_add_data_center_hvac(model, thermal_zones, hot_water_loop, heat_pump_loop, system_name: nil, hvac_op_sch: nil, oa_damper_sch: nil, main_data_center: false) click to toggle source

Creates a data center PSZ-AC system for each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param system_name [String] the name of the system, or nil in which case it will be defaulted @param hot_water_loop [OpenStudio::Model::PlantLoop] hot water loop to connect to the heating coil @param heat_pump_loop [OpenStudio::Model::PlantLoop] heat pump water loop to connect to heat pump @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [String] name of the oa damper schedule or nil in which case will be defaulted to always open @param main_data_center [Boolean] whether or not this is the main data center in the building. @return [Array<OpenStudio::Model::AirLoopHVAC>] an array of the resulting air loops

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 3211
def model_add_data_center_hvac(model,
                               thermal_zones,
                               hot_water_loop,
                               heat_pump_loop,
                               system_name: nil,
                               hvac_op_sch: nil,
                               oa_damper_sch: nil,
                               main_data_center: false)

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # create a PSZ-AC for each zone
  air_loops = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding data center HVAC for #{zone.name}.")

    air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
    if system_name.nil?
      air_loop.setName("#{zone.name} PSZ-AC Data Center")
    else
      air_loop.setName("#{zone.name} #{system_name}")
    end

    # default design temperatures across all air loops
    dsgn_temps = standard_design_sizing_temperatures
    unless hot_water_loop.nil?
      hw_temp_c = hot_water_loop.sizingPlant.designLoopExitTemperature
      hw_delta_t_k = hot_water_loop.sizingPlant.loopDesignTemperatureDifference
    end

    # adjusted zone design heating temperature for data center psz_ac
    dsgn_temps['htg_dsgn_sup_air_temp_f'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_f']
    dsgn_temps['htg_dsgn_sup_air_temp_c'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_c']

    # default design settings used across all air loops
    sizing_system = adjust_sizing_system(air_loop, dsgn_temps, min_sys_airflow_ratio: 1.0)

    # air handler controls
    # add a setpoint manager single zone reheat to control the supply air temperature
    setpoint_mgr_single_zone_reheat = OpenStudio::Model::SetpointManagerSingleZoneReheat.new(model)
    setpoint_mgr_single_zone_reheat.setName("#{zone.name} Setpoint Manager SZ Reheat")
    setpoint_mgr_single_zone_reheat.setControlZone(zone)
    setpoint_mgr_single_zone_reheat.setMinimumSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    setpoint_mgr_single_zone_reheat.setMaximumSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    setpoint_mgr_single_zone_reheat.addToNode(air_loop.supplyOutletNode)

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])

    # add the components to the air loop in order from closest to zone to furthest from zone
    if main_data_center
      # extra water heating coil
      create_coil_heating_water(model,
                                hot_water_loop,
                                air_loop_node: air_loop.supplyInletNode,
                                name: "#{air_loop.name} Water Htg Coil",
                                rated_inlet_water_temperature: hw_temp_c,
                                rated_outlet_water_temperature: (hw_temp_c - hw_delta_t_k),
                                rated_inlet_air_temperature: dsgn_temps['prehtg_dsgn_sup_air_temp_c'],
                                rated_outlet_air_temperature: dsgn_temps['htg_dsgn_sup_air_temp_c'])

      # extra electric heating coil
      create_coil_heating_electric(model,
                                   air_loop_node: air_loop.supplyInletNode,
                                   name: "#{air_loop.name} Electric Htg Coil")

      # humidity controllers
      humidifier = OpenStudio::Model::HumidifierSteamElectric.new(model)
      humidifier.setRatedCapacity(3.72E-5)
      humidifier.setRatedPower(100_000)
      humidifier.setName("#{air_loop.name} Electric Steam Humidifier")
      humidifier.addToNode(air_loop.supplyInletNode)
      humidity_spm = OpenStudio::Model::SetpointManagerSingleZoneHumidityMinimum.new(model)
      humidity_spm.setControlZone(zone)
      humidity_spm.addToNode(humidifier.outletModelObject.get.to_Node.get)
      humidistat = OpenStudio::Model::ZoneControlHumidistat.new(model)
      humidistat.setHumidifyingRelativeHumiditySetpointSchedule(model_add_schedule(model, 'OfficeLarge DC_MinRelHumSetSch'))
      zone.setZoneControlHumidistat(humidistat)
    end

    # create fan
    # @type [OpenStudio::Model::FanConstantVolume]
    fan = create_fan_by_name(model,
                             'Packaged_RTU_SZ_AC_Cycling_Fan',
                             fan_name: "#{air_loop.name} Fan")
    fan.setAvailabilitySchedule(hvac_op_sch)

    # create heating and cooling coils
    htg_coil = create_coil_heating_water_to_air_heat_pump_equation_fit(model,
                                                                       heat_pump_loop,
                                                                       name: "#{air_loop.name} Water-to-Air HP Htg Coil")
    clg_coil = create_coil_cooling_water_to_air_heat_pump_equation_fit(model,
                                                                       heat_pump_loop,
                                                                       name: "#{air_loop.name} Water-to-Air HP Clg Coil")
    supplemental_htg_coil = create_coil_heating_electric(model,
                                                         name: "#{air_loop.name} Electric Backup Htg Coil")

    # wrap fan and coils in a unitary system object
    unitary_system = OpenStudio::Model::AirLoopHVACUnitarySystem.new(model)
    unitary_system.setName("#{zone.name} Unitary HP")
    unitary_system.setSupplyFan(fan)
    unitary_system.setHeatingCoil(htg_coil)
    unitary_system.setCoolingCoil(clg_coil)
    unitary_system.setSupplementalHeatingCoil(supplemental_htg_coil)
    unitary_system.setControllingZoneorThermostatLocation(zone)
    unitary_system.setMaximumOutdoorDryBulbTemperatureforSupplementalHeaterOperation(OpenStudio.convert(40.0, 'F', 'C').get)
    unitary_system.setFanPlacement('BlowThrough')
    unitary_system.setSupplyAirFanOperatingModeSchedule(hvac_op_sch)
    unitary_system.setSupplyAirFanOperatingModeSchedule(model.alwaysOnDiscreteSchedule)
    unitary_system.addToNode(air_loop.supplyInletNode)

    # create outdoor air system
    oa_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
    oa_controller.setName("#{air_loop.name} OA System Controller")
    oa_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
    oa_controller.autosizeMinimumOutdoorAirFlowRate
    oa_controller.resetEconomizerMinimumLimitDryBulbTemperature
    oa_system = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_controller)
    oa_system.setName("#{air_loop.name} OA System")
    oa_system.addToNode(air_loop.supplyInletNode)

    # set air loop availability controls and night cycle manager, after oa system added
    air_loop.setAvailabilitySchedule(hvac_op_sch)
    air_loop.setNightCycleControlType('CycleOnAny')

    # create a diffuser and attach the zone/diffuser pair to the air loop
    diffuser = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)
    diffuser.setName("#{air_loop.name} Diffuser")
    air_loop.multiAddBranchForZone(zone, diffuser.to_HVACComponent.get)

    air_loops << air_loop
  end

  return air_loops
end
model_add_data_center_load(model, space, dc_watts_per_area) click to toggle source

Adds a data center load to a given space.

@param model [OpenStudio::Model::Model] OpenStudio model object @param space [OpenStudio::Model::Space] which space to assign the data center loads to @param dc_watts_per_area [Double] data center load, in W/m^2 @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 3186
def model_add_data_center_load(model, space, dc_watts_per_area)
  # create data center load
  data_center_definition = OpenStudio::Model::ElectricEquipmentDefinition.new(model)
  data_center_definition.setName('Data Center Load')
  data_center_definition.setWattsperSpaceFloorArea(dc_watts_per_area)
  data_center_equipment = OpenStudio::Model::ElectricEquipment.new(data_center_definition)
  data_center_equipment.setName('Data Center Load')
  data_center_sch = model.alwaysOnDiscreteSchedule
  data_center_equipment.setSchedule(data_center_sch)
  data_center_equipment.setSpace(space)

  return true
end
model_add_daylighting_controls(model) click to toggle source

Applies daylighting controls to each space in the model per the standard.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2306
def model_add_daylighting_controls(model)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Started adding daylighting controls.')

  # Add daylighting controls to each space
  model.getSpaces.sort.each do |space|
    added = space_add_daylighting_controls(space, true, false)
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Finished adding daylighting controls.')
  return true
end
model_add_district_ambient_loop(model, system_name: 'Ambient Loop') click to toggle source

Adds an ambient condenser water loop that will be used in a district to connect buildings as a shared sink/source for heat pumps.

@param model [OpenStudio::Model::Model] OpenStudio model object @param system_name [String] the name of the system, or nil in which case it will be defaulted @return [OpenStudio::Model::PlantLoop] the ambient loop @todo add inputs for design temperatures like heat pump loop object @todo handle ground and heat pump with this; make heating/cooling source options (boiler, fluid cooler, district)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 1062
def model_add_district_ambient_loop(model,
                                    system_name: 'Ambient Loop')
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', 'Adding district ambient loop.')

  # create ambient loop
  ambient_loop = OpenStudio::Model::PlantLoop.new(model)
  if system_name.nil?
    ambient_loop.setName('Ambient Loop')
  else
    ambient_loop.setName(system_name)
  end

  # ambient loop sizing and controls
  ambient_loop.setMinimumLoopTemperature(5.0)
  ambient_loop.setMaximumLoopTemperature(80.0)

  amb_high_temp_f = 90 # Supplemental cooling below 65F
  amb_low_temp_f = 41 # Supplemental heat below 41F
  amb_temp_sizing_f = 102.2 # CW sized to deliver 102.2F
  amb_delta_t_r = 19.8 # 19.8F delta-T
  amb_high_temp_c = OpenStudio.convert(amb_high_temp_f, 'F', 'C').get
  amb_low_temp_c = OpenStudio.convert(amb_low_temp_f, 'F', 'C').get
  amb_temp_sizing_c = OpenStudio.convert(amb_temp_sizing_f, 'F', 'C').get
  amb_delta_t_k = OpenStudio.convert(amb_delta_t_r, 'R', 'K').get

  amb_high_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                      amb_high_temp_c,
                                                                                      name: "Ambient Loop High Temp - #{amb_high_temp_f}F",
                                                                                      schedule_type_limit: 'Temperature')

  amb_low_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                     amb_low_temp_c,
                                                                                     name: "Ambient Loop Low Temp - #{amb_low_temp_f}F",
                                                                                     schedule_type_limit: 'Temperature')

  amb_stpt_manager = OpenStudio::Model::SetpointManagerScheduledDualSetpoint.new(model)
  amb_stpt_manager.setName("#{ambient_loop.name} Supply Water Setpoint Manager")
  amb_stpt_manager.setHighSetpointSchedule(amb_high_temp_sch)
  amb_stpt_manager.setLowSetpointSchedule(amb_low_temp_sch)
  amb_stpt_manager.addToNode(ambient_loop.supplyOutletNode)

  sizing_plant = ambient_loop.sizingPlant
  sizing_plant.setLoopType('Heating')
  sizing_plant.setDesignLoopExitTemperature(amb_temp_sizing_c)
  sizing_plant.setLoopDesignTemperatureDifference(amb_delta_t_k)

  # create pump
  pump = OpenStudio::Model::PumpVariableSpeed.new(model)
  pump.setName("#{ambient_loop.name} Pump")
  pump.setRatedPumpHead(OpenStudio.convert(60.0, 'ftH_{2}O', 'Pa').get)
  pump.setPumpControlType('Intermittent')
  pump.addToNode(ambient_loop.supplyInletNode)

  # cooling
  district_cooling = OpenStudio::Model::DistrictCooling.new(model)
  district_cooling.setNominalCapacity(1_000_000_000_000) # large number; no autosizing
  ambient_loop.addSupplyBranchForComponent(district_cooling)

  # heating
  if model.version < OpenStudio::VersionString.new('3.7.0')
    district_heating = OpenStudio::Model::DistrictHeating.new(model)
  else
    district_heating = OpenStudio::Model::DistrictHeatingWater.new(model)
  end
  district_heating.setNominalCapacity(1_000_000_000_000) # large number; no autosizing
  ambient_loop.addSupplyBranchForComponent(district_heating)

  # add ambient water loop pipes
  supply_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_bypass_pipe.setName("#{ambient_loop.name} Supply Bypass")
  ambient_loop.addSupplyBranchForComponent(supply_bypass_pipe)

  demand_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_bypass_pipe.setName("#{ambient_loop.name} Demand Bypass")
  ambient_loop.addDemandBranchForComponent(demand_bypass_pipe)

  supply_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_outlet_pipe.setName("#{ambient_loop.name} Supply Outlet")
  supply_outlet_pipe.addToNode(ambient_loop.supplyOutletNode)

  demand_inlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_inlet_pipe.setName("#{ambient_loop.name} Demand Inlet")
  demand_inlet_pipe.addToNode(ambient_loop.demandInletNode)

  demand_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_outlet_pipe.setName("#{ambient_loop.name} Demand Outlet")
  demand_outlet_pipe.addToNode(ambient_loop.demandOutletNode)

  return ambient_loop
end
model_add_doas(model, thermal_zones, system_name: nil, doas_type: 'DOASCV', hot_water_loop: nil, chilled_water_loop: nil, hvac_op_sch: nil, min_oa_sch: nil, min_frac_oa_sch: nil, fan_maximum_flow_rate: nil, econo_ctrl_mthd: 'NoEconomizer', include_exhaust_fan: true, demand_control_ventilation: false, doas_control_strategy: 'NeutralSupplyAir', clg_dsgn_sup_air_temp: 60.0, htg_dsgn_sup_air_temp: 70.0) click to toggle source

Creates a DOAS system with terminal units for each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param system_name [String] the name of the system, or nil in which case it will be defaulted @param doas_type [String] DOASCV or DOASVAV, determines whether the DOAS is operated at scheduled,

constant flow rate, or airflow is variable to allow for economizing or demand controlled ventilation

@param doas_control_strategy [String] DOAS control strategy @param hot_water_loop [OpenStudio::Model::PlantLoop] hot water loop to connect to heating and zone fan coils @param chilled_water_loop [OpenStudio::Model::PlantLoop] chilled water loop to connect to cooling coil @param hvac_op_sch [String] name of the HVAC operation schedule, default is always on @param min_oa_sch [String] name of the minimum outdoor air schedule, default is always on @param min_frac_oa_sch [String] name of the minimum fraction of outdoor air schedule, default is always on @param fan_maximum_flow_rate [Double] fan maximum flow rate in cfm, default is autosize @param econo_ctrl_mthd [String] economizer control type, default is Fixed Dry Bulb

If enabled, the DOAS will be sized for twice the ventilation minimum to allow economizing

@param include_exhaust_fan [Boolean] if true, include an exhaust fan @param clg_dsgn_sup_air_temp [Double] design cooling supply air temperature in degrees Fahrenheit, default 65F @param htg_dsgn_sup_air_temp [Double] design heating supply air temperature in degrees Fahrenheit, default 75F @return [OpenStudio::Model::AirLoopHVAC] the resulting DOAS air loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 1519
def model_add_doas(model,
                   thermal_zones,
                   system_name: nil,
                   doas_type: 'DOASCV',
                   hot_water_loop: nil,
                   chilled_water_loop: nil,
                   hvac_op_sch: nil,
                   min_oa_sch: nil,
                   min_frac_oa_sch: nil,
                   fan_maximum_flow_rate: nil,
                   econo_ctrl_mthd: 'NoEconomizer',
                   include_exhaust_fan: true,
                   demand_control_ventilation: false,
                   doas_control_strategy: 'NeutralSupplyAir',
                   clg_dsgn_sup_air_temp: 60.0,
                   htg_dsgn_sup_air_temp: 70.0)

  # Check the total OA requirement for all zones on the system
  tot_oa_req = 0
  thermal_zones.each do |zone|
    tot_oa_req += OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate(zone)
  end

  # If the total OA requirement is zero do not add the DOAS system because the simulations will fail
  if tot_oa_req.zero?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Not adding DOAS system for #{thermal_zones.size} zones because combined OA requirement for all zones is zero.")
    return false
  end
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding DOAS system for #{thermal_zones.size} zones.")

  # create a DOAS air loop
  air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
  if system_name.nil?
    air_loop.setName("#{thermal_zones.size} Zone DOAS")
  else
    air_loop.setName(system_name)
  end

  # set availability schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # DOAS design temperatures
  if clg_dsgn_sup_air_temp.nil?
    clg_dsgn_sup_air_temp_c = OpenStudio.convert(60.0, 'F', 'C').get
  else
    clg_dsgn_sup_air_temp_c = OpenStudio.convert(clg_dsgn_sup_air_temp, 'F', 'C').get
  end

  if htg_dsgn_sup_air_temp.nil?
    htg_dsgn_sup_air_temp_c = OpenStudio.convert(70.0, 'F', 'C').get
  else
    htg_dsgn_sup_air_temp_c = OpenStudio.convert(htg_dsgn_sup_air_temp, 'F', 'C').get
  end

  # modify system sizing properties
  sizing_system = air_loop.sizingSystem
  sizing_system.setTypeofLoadtoSizeOn('VentilationRequirement')
  sizing_system.setAllOutdoorAirinCooling(true)
  sizing_system.setAllOutdoorAirinHeating(true)
  # set minimum airflow ratio to 1.0 to avoid under-sizing heating coil
  if model.version < OpenStudio::VersionString.new('2.7.0')
    sizing_system.setMinimumSystemAirFlowRatio(1.0)
  else
    sizing_system.setCentralHeatingMaximumSystemAirFlowRatio(1.0)
  end
  sizing_system.setSizingOption('Coincident')
  sizing_system.setCentralCoolingDesignSupplyAirTemperature(clg_dsgn_sup_air_temp_c)
  sizing_system.setCentralHeatingDesignSupplyAirTemperature(htg_dsgn_sup_air_temp_c)

  if doas_type == 'DOASCV'
    supply_fan = create_fan_by_name(model,
                                    'Constant_DOAS_Fan',
                                    fan_name: 'DOAS Supply Fan',
                                    end_use_subcategory: 'DOAS Fans')
  else # 'DOASVAV'
    supply_fan = create_fan_by_name(model,
                                    'Variable_DOAS_Fan',
                                    fan_name: 'DOAS Supply Fan',
                                    end_use_subcategory: 'DOAS Fans')
  end
  supply_fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  supply_fan.setMaximumFlowRate(OpenStudio.convert(fan_maximum_flow_rate, 'cfm', 'm^3/s').get) unless fan_maximum_flow_rate.nil?
  supply_fan.addToNode(air_loop.supplyInletNode)

  # create heating coil
  if hot_water_loop.nil?
    # electric backup heating coil
    create_coil_heating_electric(model,
                                 air_loop_node: air_loop.supplyInletNode,
                                 name: "#{air_loop.name} Backup Htg Coil")
    # heat pump coil
    create_coil_heating_dx_single_speed(model,
                                        air_loop_node: air_loop.supplyInletNode,
                                        name: "#{air_loop.name} Htg Coil")
  else
    create_coil_heating_water(model,
                              hot_water_loop,
                              air_loop_node: air_loop.supplyInletNode,
                              name: "#{air_loop.name} Htg Coil",
                              controller_convergence_tolerance: 0.0001)
  end

  # could add a humidity controller here set to limit supply air to a 16.6C/62F dewpoint
  # the default outdoor air reset to 60F prevents exceeding this dewpoint in all ASHRAE climate zones
  # the humidity controller needs a DX coil that can control humidity, e.g. CoilCoolingDXTwoStageWithHumidityControlMode
  # max_humidity_ratio_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
  #                                                                                          0.012,
  #                                                                                          name: "0.012 Humidity Ratio Schedule",
  #                                                                                          schedule_type_limit: "Humidity Ratio")
  # sat_oa_reset = OpenStudio::Model::SetpointManagerScheduled.new(model, max_humidity_ratio_sch)
  # sat_oa_reset.setName("#{air_loop.name.to_s} Humidity Controller")
  # sat_oa_reset.setControlVariable('MaximumHumidityRatio')
  # sat_oa_reset.addToNode(air_loop.supplyInletNode)

  # create cooling coil
  if chilled_water_loop.nil?
    create_coil_cooling_dx_two_speed(model,
                                     air_loop_node: air_loop.supplyInletNode,
                                     name: "#{air_loop.name} 2spd DX Clg Coil",
                                     type: 'OS default')
  else
    create_coil_cooling_water(model,
                              chilled_water_loop,
                              air_loop_node: air_loop.supplyInletNode,
                              name: "#{air_loop.name} Clg Coil")
  end

  # minimum outdoor air schedule
  unless min_oa_sch.nil?
    min_oa_sch = model_add_schedule(model, min_oa_sch)
  end

  # minimum outdoor air fraction schedule
  if min_frac_oa_sch.nil?
    min_frac_oa_sch = model.alwaysOnDiscreteSchedule
  else
    min_frac_oa_sch = model_add_schedule(model, min_frac_oa_sch)
  end

  # create controller outdoor air
  controller_oa = OpenStudio::Model::ControllerOutdoorAir.new(model)
  controller_oa.setName("#{air_loop.name} Outdoor Air Controller")
  controller_oa.setEconomizerControlType(econo_ctrl_mthd)
  controller_oa.setMinimumLimitType('FixedMinimum')
  controller_oa.autosizeMinimumOutdoorAirFlowRate
  controller_oa.setMinimumOutdoorAirSchedule(min_oa_sch) unless min_oa_sch.nil?
  controller_oa.setMinimumFractionofOutdoorAirSchedule(min_frac_oa_sch)
  controller_oa.resetEconomizerMinimumLimitDryBulbTemperature
  controller_oa.resetEconomizerMaximumLimitDryBulbTemperature
  controller_oa.resetEconomizerMaximumLimitEnthalpy
  controller_oa.resetMaximumFractionofOutdoorAirSchedule
  controller_oa.setHeatRecoveryBypassControlType('BypassWhenWithinEconomizerLimits')
  controller_mech_vent = controller_oa.controllerMechanicalVentilation
  controller_mech_vent.setName("#{air_loop.name} Mechanical Ventilation Controller")
  controller_mech_vent.setDemandControlledVentilation(true) if demand_control_ventilation
  controller_mech_vent.setSystemOutdoorAirMethod('ZoneSum')

  # create outdoor air system
  oa_system = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, controller_oa)
  oa_system.setName("#{air_loop.name} OA System")
  oa_system.addToNode(air_loop.supplyInletNode)

  # create an exhaust fan
  if include_exhaust_fan
    if doas_type == 'DOASCV'
      exhaust_fan = create_fan_by_name(model,
                                       'Constant_DOAS_Fan',
                                       fan_name: 'DOAS Exhaust Fan',
                                       end_use_subcategory: 'DOAS Fans')
    else # 'DOASVAV'
      exhaust_fan = create_fan_by_name(model,
                                       'Variable_DOAS_Fan',
                                       fan_name: 'DOAS Exhaust Fan',
                                       end_use_subcategory: 'DOAS Fans')
    end
    # set pressure rise 1.0 inH2O lower than supply fan, 1.0 inH2O minimum
    exhaust_fan_pressure_rise = supply_fan.pressureRise - OpenStudio.convert(1.0, 'inH_{2}O', 'Pa').get
    exhaust_fan_pressure_rise = OpenStudio.convert(1.0, 'inH_{2}O', 'Pa').get if exhaust_fan_pressure_rise < OpenStudio.convert(1.0, 'inH_{2}O', 'Pa').get
    exhaust_fan.setPressureRise(exhaust_fan_pressure_rise)
    exhaust_fan.addToNode(air_loop.supplyInletNode)
  end

  # create a setpoint manager
  sat_oa_reset = OpenStudio::Model::SetpointManagerOutdoorAirReset.new(model)
  sat_oa_reset.setName("#{air_loop.name} SAT Reset")
  sat_oa_reset.setControlVariable('Temperature')
  sat_oa_reset.setSetpointatOutdoorLowTemperature(htg_dsgn_sup_air_temp_c)
  sat_oa_reset.setOutdoorLowTemperature(OpenStudio.convert(55.0, 'F', 'C').get)
  sat_oa_reset.setSetpointatOutdoorHighTemperature(clg_dsgn_sup_air_temp_c)
  sat_oa_reset.setOutdoorHighTemperature(OpenStudio.convert(70.0, 'F', 'C').get)
  sat_oa_reset.addToNode(air_loop.supplyOutletNode)

  # set air loop availability controls and night cycle manager, after oa system added
  air_loop.setAvailabilitySchedule(hvac_op_sch)
  air_loop.setNightCycleControlType('CycleOnAnyZoneFansOnly')

  # add thermal zones to airloop
  thermal_zones.each do |zone|
    # skip zones with no outdoor air flow rate
    unless OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate(zone) > 0
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "---#{zone.name} has no outdoor air flow rate and will not be added to #{air_loop.name}")
      next
    end

    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "---adding #{zone.name} to #{air_loop.name}")

    # make an air terminal for the zone
    if doas_type == 'DOASCV'
      air_terminal = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)
    elsif doas_type == 'DOASVAVReheat'
      # Reheat coil
      if hot_water_loop.nil?
        rht_coil = create_coil_heating_electric(model, name: "#{zone.name} Electric Reheat Coil")
      else
        rht_coil = create_coil_heating_water(model, hot_water_loop, name: "#{zone.name} Reheat Coil")
      end
      # VAV reheat terminal
      air_terminal = OpenStudio::Model::AirTerminalSingleDuctVAVReheat.new(model, model.alwaysOnDiscreteSchedule, rht_coil)
      if model.version < OpenStudio::VersionString.new('3.0.1')
        air_terminal.setZoneMinimumAirFlowMethod('Constant')
      else
        air_terminal.setZoneMinimumAirFlowInputMethod('Constant')
      end
      air_terminal.setControlForOutdoorAir(true) if demand_control_ventilation
    else # 'DOASVAV'
      air_terminal = OpenStudio::Model::AirTerminalSingleDuctVAVNoReheat.new(model, model.alwaysOnDiscreteSchedule)
      if model.version < OpenStudio::VersionString.new('3.0.1')
        air_terminal.setZoneMinimumAirFlowMethod('Constant')
      else
        air_terminal.setZoneMinimumAirFlowInputMethod('Constant')
      end
      air_terminal.setConstantMinimumAirFlowFraction(0.1)
      air_terminal.setControlForOutdoorAir(true) if demand_control_ventilation
    end
    air_terminal.setName("#{zone.name} Air Terminal")

    # attach new terminal to the zone and to the airloop
    air_loop.multiAddBranchForZone(zone, air_terminal.to_HVACComponent.get)

    # ensure the DOAS takes priority, so ventilation load is included when treated by other zonal systems
    # From EnergyPlus I/O reference:
    # "For situations where one or more equipment types has limited capacity or limited control capability, order the
    #  sequence so that the most controllable piece of equipment runs last. For example, with a dedicated outdoor air
    #  system (DOAS), the air terminal for the DOAS should be assigned Heating Sequence = 1 and Cooling Sequence = 1.
    #  Any other equipment should be assigned sequence 2 or higher so that it will see the net load after the DOAS air
    #  is added to the zone."
    zone.setCoolingPriority(air_terminal.to_ModelObject.get, 1)
    zone.setHeatingPriority(air_terminal.to_ModelObject.get, 1)

    # set the cooling and heating fraction to zero so that if DCV is enabled,
    # the system will lower the ventilation rate rather than trying to meet the heating or cooling load.
    if model.version < OpenStudio::VersionString.new('2.8.0')
      if demand_control_ventilation
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'Unable to add DOAS with DCV to model because the setSequentialCoolingFraction method is not available in OpenStudio versions less than 2.8.0.')
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', 'OpenStudio version is less than 2.8.0.  The DOAS system will not be able to have DCV if changed at a later date.')
      end
    else
      zone.setSequentialCoolingFraction(air_terminal.to_ModelObject.get, 0.0)
      zone.setSequentialHeatingFraction(air_terminal.to_ModelObject.get, 0.0)

      # if economizing, override to meet cooling load first with doas supply
      unless econo_ctrl_mthd == 'NoEconomizer'
        zone.setSequentialCoolingFraction(air_terminal.to_ModelObject.get, 1.0)
      end
    end

    # DOAS sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setAccountforDedicatedOutdoorAirSystem(true)
    sizing_zone.setDedicatedOutdoorAirSystemControlStrategy(doas_control_strategy)
    sizing_zone.setDedicatedOutdoorAirLowSetpointTemperatureforDesign(clg_dsgn_sup_air_temp_c)
    sizing_zone.setDedicatedOutdoorAirHighSetpointTemperatureforDesign(htg_dsgn_sup_air_temp_c)
  end

  return air_loop
end
model_add_doas_cold_supply(model, thermal_zones, system_name: nil, hot_water_loop: nil, chilled_water_loop: nil, hvac_op_sch: nil, min_oa_sch: nil, min_frac_oa_sch: nil, fan_maximum_flow_rate: nil, econo_ctrl_mthd: 'FixedDryBulb', energy_recovery: false, doas_control_strategy: 'NeutralSupplyAir', clg_dsgn_sup_air_temp: 55.0, htg_dsgn_sup_air_temp: 60.0) click to toggle source

Creates a DOAS system with cold supply and terminal units for each zone. This is the default DOAS system for DOE prototype buildings. Use model_add_doas for other DOAS systems.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param system_name [String] the name of the system, or nil in which case it will be defaulted @param hot_water_loop [OpenStudio::Model::PlantLoop] hot water loop to connect to heating and zone fan coils @param chilled_water_loop [OpenStudio::Model::PlantLoop] chilled water loop to connect to cooling coil @param hvac_op_sch [String] name of the HVAC operation schedule, default is always on @param min_oa_sch [String] name of the minimum outdoor air schedule, default is always on @param min_frac_oa_sch [String] name of the minimum fraction of outdoor air schedule, default is always on @param fan_maximum_flow_rate [Double] fan maximum flow rate in cfm, default is autosize @param econo_ctrl_mthd [String] economizer control type, default is Fixed Dry Bulb @param energy_recovery [Boolean] if true, an ERV will be added to the system @param doas_control_strategy [String] DOAS control strategy @param clg_dsgn_sup_air_temp [Double] design cooling supply air temperature in degrees Fahrenheit, default 65F @param htg_dsgn_sup_air_temp [Double] design heating supply air temperature in degrees Fahrenheit, default 75F @return [OpenStudio::Model::AirLoopHVAC] the resulting DOAS air loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 1288
def model_add_doas_cold_supply(model,
                               thermal_zones,
                               system_name: nil,
                               hot_water_loop: nil,
                               chilled_water_loop: nil,
                               hvac_op_sch: nil,
                               min_oa_sch: nil,
                               min_frac_oa_sch: nil,
                               fan_maximum_flow_rate: nil,
                               econo_ctrl_mthd: 'FixedDryBulb',
                               energy_recovery: false,
                               doas_control_strategy: 'NeutralSupplyAir',
                               clg_dsgn_sup_air_temp: 55.0,
                               htg_dsgn_sup_air_temp: 60.0)

  # Check the total OA requirement for all zones on the system
  tot_oa_req = 0
  thermal_zones.each do |zone|
    tot_oa_req += OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate(zone)
    break if tot_oa_req > 0
  end

  # If the total OA requirement is zero do not add the DOAS system because the simulations will fail
  if tot_oa_req.zero?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Not adding DOAS system for #{thermal_zones.size} zones because combined OA requirement for all zones is zero.")
    return false
  end
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding DOAS system for #{thermal_zones.size} zones.")

  # create a DOAS air loop
  air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
  if system_name.nil?
    air_loop.setName("#{thermal_zones.size} Zone DOAS")
  else
    air_loop.setName(system_name)
  end

  # set availability schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # DOAS design temperatures
  if clg_dsgn_sup_air_temp.nil?
    clg_dsgn_sup_air_temp_c = OpenStudio.convert(55.0, 'F', 'C').get
  else
    clg_dsgn_sup_air_temp_c = OpenStudio.convert(clg_dsgn_sup_air_temp, 'F', 'C').get
  end

  if htg_dsgn_sup_air_temp.nil?
    htg_dsgn_sup_air_temp_c = OpenStudio.convert(60.0, 'F', 'C').get
  else
    htg_dsgn_sup_air_temp_c = OpenStudio.convert(htg_dsgn_sup_air_temp, 'F', 'C').get
  end

  # modify system sizing properties
  sizing_system = air_loop.sizingSystem
  sizing_system.setTypeofLoadtoSizeOn('VentilationRequirement')
  sizing_system.setAllOutdoorAirinCooling(true)
  sizing_system.setAllOutdoorAirinHeating(true)
  # set minimum airflow ratio to 1.0 to avoid under-sizing heating coil
  if model.version < OpenStudio::VersionString.new('2.7.0')
    sizing_system.setMinimumSystemAirFlowRatio(1.0)
  else
    sizing_system.setCentralHeatingMaximumSystemAirFlowRatio(1.0)
  end
  sizing_system.setSizingOption('Coincident')
  sizing_system.setCentralCoolingDesignSupplyAirTemperature(clg_dsgn_sup_air_temp_c)
  sizing_system.setCentralHeatingDesignSupplyAirTemperature(htg_dsgn_sup_air_temp_c)

  # create supply fan
  supply_fan = create_fan_by_name(model,
                                  'Constant_DOAS_Fan',
                                  fan_name: 'DOAS Supply Fan',
                                  end_use_subcategory: 'DOAS Fans')
  supply_fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  supply_fan.setMaximumFlowRate(OpenStudio.convert(fan_maximum_flow_rate, 'cfm', 'm^3/s').get) unless fan_maximum_flow_rate.nil?
  supply_fan.addToNode(air_loop.supplyInletNode)

  # create heating coil
  if hot_water_loop.nil?
    # electric backup heating coil
    create_coil_heating_electric(model,
                                 air_loop_node: air_loop.supplyInletNode,
                                 name: "#{air_loop.name} Backup Htg Coil")
    # heat pump coil
    create_coil_heating_dx_single_speed(model,
                                        air_loop_node: air_loop.supplyInletNode,
                                        name: "#{air_loop.name} Htg Coil")
  else
    create_coil_heating_water(model,
                              hot_water_loop,
                              air_loop_node: air_loop.supplyInletNode,
                              name: "#{air_loop.name} Htg Coil",
                              controller_convergence_tolerance: 0.0001)
  end

  # create cooling coil
  if chilled_water_loop.nil?
    create_coil_cooling_dx_two_speed(model,
                                     air_loop_node: air_loop.supplyInletNode,
                                     name: "#{air_loop.name} 2spd DX Clg Coil",
                                     type: 'OS default')
  else
    create_coil_cooling_water(model,
                              chilled_water_loop,
                              air_loop_node: air_loop.supplyInletNode,
                              name: "#{air_loop.name} Clg Coil")
  end

  # minimum outdoor air schedule
  if min_oa_sch.nil?
    min_oa_sch = model.alwaysOnDiscreteSchedule
  else
    min_oa_sch = model_add_schedule(model, min_oa_sch)
  end

  # minimum outdoor air fraction schedule
  if min_frac_oa_sch.nil?
    min_frac_oa_sch = model.alwaysOnDiscreteSchedule
  else
    min_frac_oa_sch = model_add_schedule(model, min_frac_oa_sch)
  end

  # create controller outdoor air
  controller_oa = OpenStudio::Model::ControllerOutdoorAir.new(model)
  controller_oa.setName("#{air_loop.name} OA Controller")
  controller_oa.setEconomizerControlType(econo_ctrl_mthd)
  controller_oa.setMinimumLimitType('FixedMinimum')
  controller_oa.autosizeMinimumOutdoorAirFlowRate
  controller_oa.setMinimumOutdoorAirSchedule(min_oa_sch)
  controller_oa.setMinimumFractionofOutdoorAirSchedule(min_frac_oa_sch)
  controller_oa.resetEconomizerMaximumLimitDryBulbTemperature
  controller_oa.resetEconomizerMaximumLimitEnthalpy
  controller_oa.resetMaximumFractionofOutdoorAirSchedule
  controller_oa.resetEconomizerMinimumLimitDryBulbTemperature
  controller_oa.setHeatRecoveryBypassControlType('BypassWhenWithinEconomizerLimits')

  # create outdoor air system
  oa_system = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, controller_oa)
  oa_system.setName("#{air_loop.name} OA System")
  oa_system.addToNode(air_loop.supplyInletNode)

  # create a setpoint manager
  sat_oa_reset = OpenStudio::Model::SetpointManagerOutdoorAirReset.new(model)
  sat_oa_reset.setName("#{air_loop.name} SAT Reset")
  sat_oa_reset.setControlVariable('Temperature')
  sat_oa_reset.setSetpointatOutdoorLowTemperature(htg_dsgn_sup_air_temp_c)
  sat_oa_reset.setOutdoorLowTemperature(OpenStudio.convert(60.0, 'F', 'C').get)
  sat_oa_reset.setSetpointatOutdoorHighTemperature(clg_dsgn_sup_air_temp_c)
  sat_oa_reset.setOutdoorHighTemperature(OpenStudio.convert(70.0, 'F', 'C').get)
  sat_oa_reset.addToNode(air_loop.supplyOutletNode)

  # set air loop availability controls and night cycle manager, after oa system added
  air_loop.setAvailabilitySchedule(hvac_op_sch)
  air_loop.setNightCycleControlType('CycleOnAny')

  # add energy recovery if requested
  if energy_recovery
    # Get the OA system and its outboard OA node
    oa_system = air_loop.airLoopHVACOutdoorAirSystem.get

    # create the ERV and set its properties
    erv = OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent.new(model)
    erv.addToNode(oa_system.outboardOANode.get)
    erv.setHeatExchangerType('Rotary')
    # @todo come up with scheme for estimating power of ERV motor wheel which might require knowing airflow.
    # erv.setNominalElectricPower(value_new)
    erv.setEconomizerLockout(true)
    erv.setSupplyAirOutletTemperatureControl(false)

    erv.setSensibleEffectivenessat100HeatingAirFlow(0.76)
    erv.setSensibleEffectivenessat75HeatingAirFlow(0.81)
    erv.setLatentEffectivenessat100HeatingAirFlow(0.68)
    erv.setLatentEffectivenessat75HeatingAirFlow(0.73)

    erv.setSensibleEffectivenessat100CoolingAirFlow(0.76)
    erv.setSensibleEffectivenessat75CoolingAirFlow(0.81)
    erv.setLatentEffectivenessat100CoolingAirFlow(0.68)
    erv.setLatentEffectivenessat75CoolingAirFlow(0.73)

    # increase fan static pressure to account for ERV
    erv_pressure_rise = OpenStudio.convert(1.0, 'inH_{2}O', 'Pa').get
    new_pressure_rise = supply_fan.pressureRise + erv_pressure_rise
    supply_fan.setPressureRise(new_pressure_rise)
  end

  # add thermal zones to airloop
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "---adding #{zone.name} to #{air_loop.name}")

    # make an air terminal for the zone
    air_terminal = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)
    air_terminal.setName("#{zone.name} Air Terminal")

    # attach new terminal to the zone and to the airloop
    air_loop.multiAddBranchForZone(zone, air_terminal.to_HVACComponent.get)

    # DOAS sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setAccountforDedicatedOutdoorAirSystem(true)
    sizing_zone.setDedicatedOutdoorAirSystemControlStrategy('ColdSupplyAir')
    sizing_zone.setDedicatedOutdoorAirLowSetpointTemperatureforDesign(clg_dsgn_sup_air_temp_c)
    sizing_zone.setDedicatedOutdoorAirHighSetpointTemperatureforDesign(htg_dsgn_sup_air_temp_c)
  end

  return air_loop
end
model_add_elevator(model, space, number_of_elevators, elevator_type, elevator_schedule, elevator_fan_schedule, elevator_lights_schedule, building_type = nil) click to toggle source

Add an elevator the the specified space

@param model [OpenStudio::Model::Model] OpenStudio model object @param space [OpenStudio::Model::Space] the space that contains the elevators @param number_of_elevators [Integer] the number of elevators @param elevator_type [String] valid choices are Traction, Hydraulic @param elevator_schedule [String] the name of the elevator schedule @param elevator_fan_schedule [String] the name of the elevator fan schedule @param elevator_lights_schedule [String] the name of the elevator lights schedule @param building_type [String] the building type @return [OpenStudio::Model::ElectricEquipment] the resulting elevator

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.elevators.rb, line 13
def model_add_elevator(model,
                       space,
                       number_of_elevators,
                       elevator_type,
                       elevator_schedule,
                       elevator_fan_schedule,
                       elevator_lights_schedule,
                       building_type = nil)

  # Lift motor assumptions
  lift_pwr_w = model_elevator_lift_power(model, elevator_type, building_type)

  # Size assumptions
  length_ft = 6.66
  width_ft = 4.25
  height_ft = 8.0
  area_ft2 = length_ft * width_ft
  volume_ft3 = area_ft2 * height_ft

  # Ventilation assumptions
  vent_rate_acm = 1 # air changes per minute
  vent_rate_cfm = volume_ft3 / vent_rate_acm
  vent_pwr_w = model_elevator_fan_pwr(model, vent_rate_cfm)

  # Heating fraction radiant assumptions
  elec_equip_frac_radiant = 0.5

  # Lighting assumptions
  design_ltg_lm_per_ft2 = 30
  light_loss_factor = 0.75
  pct_incandescent = model_elevator_lighting_pct_incandescent(model)
  pct_led = 1.0 - pct_incandescent

  incandescent_efficacy_lm_per_w = 10.0
  led_efficacy_lm_per_w = 35.0
  target_ltg_lm_per_ft2 = design_ltg_lm_per_ft2 / light_loss_factor # 40
  target_ltg_lm = target_ltg_lm_per_ft2 * area_ft2 # 1132.2
  lm_incandescent = target_ltg_lm * pct_incandescent # 792.54
  lm_led = target_ltg_lm * pct_led # 339.66
  w_incandescent = lm_incandescent / incandescent_efficacy_lm_per_w # 79.254
  w_led = lm_led / led_efficacy_lm_per_w # 9.7
  lighting_pwr_w = w_incandescent + w_led

  # Elevator lift motor
  elevator_definition = OpenStudio::Model::ElectricEquipmentDefinition.new(model)
  elevator_definition.setName('Elevator Lift Motor')
  elevator_definition.setDesignLevel(lift_pwr_w)
  elevator_definition.setFractionRadiant(elec_equip_frac_radiant)

  elevator_equipment = OpenStudio::Model::ElectricEquipment.new(elevator_definition)
  elevator_equipment.setName("#{number_of_elevators.round} Elevator Lift Motors")
  elevator_equipment.setEndUseSubcategory('Elevators')
  elevator_sch = model_add_schedule(model, elevator_schedule)
  elevator_equipment.setSchedule(elevator_sch)
  elevator_equipment.setSpace(space)
  elevator_equipment.setMultiplier(number_of_elevators)

  # Elevator fan
  elevator_fan_definition = OpenStudio::Model::ElectricEquipmentDefinition.new(model)
  elevator_fan_definition.setName('Elevator Fan')
  elevator_fan_definition.setDesignLevel(vent_pwr_w)
  elevator_fan_definition.setFractionRadiant(elec_equip_frac_radiant)

  elevator_fan_equipment = OpenStudio::Model::ElectricEquipment.new(elevator_fan_definition)
  elevator_fan_equipment.setName("#{number_of_elevators.round} Elevator Fans")
  elevator_fan_equipment.setEndUseSubcategory('Elevators')
  elevator_fan_sch = model_add_schedule(model, elevator_fan_schedule)
  elevator_fan_equipment.setSchedule(elevator_fan_sch)
  elevator_fan_equipment.setSpace(space)
  elevator_fan_equipment.setMultiplier(number_of_elevators)

  # Elevator lights
  elevator_lights_definition = OpenStudio::Model::ElectricEquipmentDefinition.new(model)
  elevator_lights_definition.setName('Elevator Lights')
  elevator_lights_definition.setDesignLevel(lighting_pwr_w)
  elevator_lights_definition.setFractionRadiant(elec_equip_frac_radiant)

  elevator_lights_equipment = OpenStudio::Model::ElectricEquipment.new(elevator_lights_definition)
  elevator_lights_equipment.setName("#{number_of_elevators.round} Elevator Lights")
  elevator_lights_equipment.setEndUseSubcategory('Elevators')
  elevator_lights_sch = model_add_schedule(model, elevator_lights_schedule)
  elevator_lights_equipment.setSchedule(elevator_lights_sch)
  elevator_lights_equipment.setSpace(space)
  elevator_lights_equipment.setMultiplier(number_of_elevators)

  return elevator_equipment
end
model_add_elevators(model) click to toggle source

Add elevators to the model based on the building size, number of stories, and building type. Logic was derived from the DOE prototype buildings.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::ElectricEquipment] the resulting elevator

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.elevators.rb, line 151
def model_add_elevators(model)
  # determine effective number of stories
  effective_num_stories = model_effective_num_stories(model)

  # determine elevator type
  # todo add logic here or upstream to have some multi-story buildings without elevators (e.g. small multi-family and small hotels)
  if effective_num_stories[:below_grade] + effective_num_stories[:above_grade] < 2
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', 'The building only has 1 story, no elevators will be added.')
    return nil # don't add elevators
  elsif effective_num_stories[:below_grade] + effective_num_stories[:above_grade] < 6
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', 'The building has fewer than 6 effective stories; assuming Hydraulic elevators.')
    elevator_type = 'Hydraulic'
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', 'The building has 6 or more effective stories; assuming Traction elevators.')
    elevator_type = 'Traction'
  end

  # determine space to put elevator load in
  # largest bottom story (including basement) space that has multiplier of 1
  bottom_spaces = {}
  bottom_story = effective_num_stories[:story_hash].keys.first
  bottom_story.spaces.each do |space|
    next if space.multiplier > 1

    bottom_spaces[space] = space.floorArea
  end
  target_space = bottom_spaces.key(bottom_spaces.values.max)

  building_types = []

  # determine number of elevators
  number_of_pass_elevators = 0.0
  number_of_freight_elevators = 0.0
  building_type_hash = {}

  # apply building type specific log to add to number of elevators based on Beyer (2009) rules of thumb
  space_type_hash = model_create_space_type_hash(model)
  space_type_hash.each do |space_type, hash|
    # update building_type_hash
    if building_type_hash.key?(hash[:stds_bldg_type])
      building_type_hash[hash[:stds_bldg_type]] += hash[:floor_area]
    else
      building_type_hash[hash[:stds_bldg_type]] = hash[:floor_area]
    end

    building_type = hash[:stds_bldg_type]
    building_types << building_type

    # store floor area ip
    floor_area_ip = OpenStudio.convert(hash[:floor_area], 'm^2', 'ft^2').get

    # load elevator_data
    search_criteria = {
      'building_type' => building_type,
      'template' => template
    }
    elevator_data_lookup = model_find_object(standards_data['elevators'], search_criteria)
    if elevator_data_lookup.nil?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.prototype.elevators', "Could not find elevator data for #{building_type}, elevator counts will not account for serving this portion of the building area.")
      next
    end

    # determine number of passenger elevators
    if !elevator_data_lookup['area_per_passenger_elevator'].nil?
      pass_elevs = floor_area_ip / elevator_data_lookup['area_per_passenger_elevator'].to_f
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "For #{space_type.name}, adding #{pass_elevs.round(1)} passenger elevators at 1 per #{elevator_data_lookup['area_per_passenger_elevator']} ft^2.")
    elsif !elevator_data_lookup['units_per_passenger_elevator'].nil?
      pass_elevs = hash[:num_units] / elevator_data_lookup['units_per_passenger_elevator'].to_f
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "For #{space_type.name}, adding #{pass_elevs.round(1)} passenger elevators at 1 per #{elevator_data_lookup['units_per_passenger_elevator']} units.")
    elsif !elevator_data_lookup['beds_per_passenger_elevator'].nil?
      pass_elevs = hash[:num_beds] / elevator_data_lookup['beds_per_passenger_elevator'].to_f
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "For #{space_type.name}, adding #{pass_elevs.round(1)} passenger elevators at 1 per #{elevator_data_lookup['beds_per_passenger_elevator']} beds.")
    else
      pass_elevs = 0.0
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "Unexpected key, can't calculate number of passenger elevators from #{elevator_data_lookup.keys.first}.")
    end

    # determine number of freight elevators
    if !elevator_data_lookup['area_per_freight_elevator'].nil?
      freight_elevs = floor_area_ip / elevator_data_lookup['area_per_freight_elevator'].to_f
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "For #{space_type.name}, adding #{freight_elevs.round(1)} freight/service elevators at 1 per #{elevator_data_lookup['area_per_freight_elevator']} ft^2.")
    elsif !elevator_data_lookup['units_per_freight_elevator'].nil?
      freight_elevs = hash[:num_units] / elevator_data_lookup['units_per_freight_elevator'].to_f
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "For #{space_type.name}, adding #{freight_elevs.round(1)} freight/service elevators at 1 per #{elevator_data_lookup['units_per_freight_elevator']} units.")
    elsif !elevator_data_lookup['beds_per_freight_elevator'].nil?
      freight_elevs = hash[:num_beds] / elevator_data_lookup['beds_per_freight_elevator'].to_f
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "For #{space_type.name}, adding #{freight_elevs.round(1)} freight/service elevators at 1 per #{elevator_data_lookup['beds_per_freight_elevator']} beds.")
    else
      freight_elevs = 0.0
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "Unexpected key, can't calculate number of freight elevators from #{elevator_data_lookup.keys.first}.")
    end
    number_of_pass_elevators += pass_elevs
    number_of_freight_elevators += freight_elevs
  end

  # additional passenger elevators (applicable for DOE LargeHotel and DOE Hospital only)
  add_pass_elevs = 0.0
  building_types.uniq.each do |building_type|
    # load elevator_data
    search_criteria = { 'building_type' => building_type }
    elevator_data_lookup = model_find_object(standards_data['elevators'], search_criteria)
    if elevator_data_lookup.nil?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.prototype.elevators', "Could not find elevator data for #{building_type}.")
      next
    end

    # determine number of additional passenger elevators
    if !elevator_data_lookup['additional_passenger_elevators'].nil?
      add_pass_elevs += elevator_data_lookup['additional_passenger_elevators']
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "Adding #{elevator_data_lookup['additional_passenger_elevators']} additional passenger elevators.")
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', 'No additional passenger elevators added to model.')
    end
  end

  # adjust number of elevators (can be double but if not 0 must be at least 1.0)
  if (number_of_pass_elevators > 0.0) && (number_of_pass_elevators < 1.0)
    number_of_pass_elevators = 1.0
  end
  if (number_of_freight_elevators > 0.0) && (number_of_freight_elevators < 1.0)
    number_of_freight_elevators = 1.0
  end

  # determine total number of elevators (rounding up to nearest whole number)
  number_of_pass_elevators = number_of_pass_elevators.ceil + add_pass_elevs
  number_of_freight_elevators = number_of_freight_elevators.ceil
  number_of_elevators = number_of_pass_elevators + number_of_freight_elevators

  building_type = building_type_hash.key(building_type_hash.values.max)

  # determine blended occupancy schedule
  occ_schedule = OpenstudioStandards::Space.spaces_get_occupancy_schedule(model.getSpaces)

  # get total number of people in building
  max_occ_in_spaces = 0
  model.getSpaces.each do |space|
    # From the space type
    if space.spaceType.is_initialized
      space.spaceType.get.people.each do |people|
        num_ppl = people.getNumberOfPeople(space.floorArea)
        max_occ_in_spaces += num_ppl
      end
    end
    # From the space
    space.people.each do |people|
      num_ppl = people.getNumberOfPeople(space.floorArea)
      max_occ_in_spaces += num_ppl
    end
  end

  # make elevator schedule based on change in occupancy for each timestep
  day_schedules = []
  default_day_schedule = occ_schedule.defaultDaySchedule
  day_schedules << default_day_schedule
  occ_schedule.scheduleRules.each do |rule|
    day_schedules << rule.daySchedule
  end
  day_schedules.each do |day_schedule|
    elevator_hourly_fractions = []
    (0..23).each do |hr|
      t = OpenStudio::Time.new(0, hr, 0, 0)
      value = day_schedule.getValue(t)
      t_plus = OpenStudio::Time.new(0, hr + 1, 0, 0)
      value_plus = day_schedule.getValue(t_plus)
      change_occupancy_fraction = (value_plus - value).abs
      change_num_people = change_occupancy_fraction * max_occ_in_spaces * 1.2
      # multiplication factor or 1.2 to account for interfloor traffic

      # determine time per ride based on number of floors and elevator type
      if elevator_type == 'Hydraulic'
        time_per_ride = 8.7 + (effective_num_stories[:above_grade] * 5.6)
      elsif elevator_type == 'Traction'
        time_per_ride = 5.6 + (effective_num_stories[:above_grade] * 2.1)
      else
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.prototype.elevators', "Elevator type #{elevator_type} not recognized.")
        return nil
      end

      # determine elevator operation fraction for each timestep
      people_per_ride = 5
      rides_per_elevator = (change_num_people / people_per_ride) / number_of_elevators
      operation_time = rides_per_elevator * time_per_ride
      elevator_operation_fraction = operation_time / 3600
      if elevator_operation_fraction > 1.00
        elevator_operation_fraction = 1.00
      end
      elevator_hourly_fractions << elevator_operation_fraction
    end

    # replace hourly occupancy values with operating fractions
    day_schedule.clearValues
    (0..23).each do |hr|
      t = OpenStudio::Time.new(0, hr, 0, 0)
      value = elevator_hourly_fractions[hr]
      value_plus = if hr <= 22
                     elevator_hourly_fractions[hr + 1]
                   else
                     elevator_hourly_fractions[0]
                   end
      next if value == value_plus

      day_schedule.addValue(t, elevator_hourly_fractions[hr])
    end
  end

  occ_schedule.setName('Elevator Schedule')

  # clone new elevator schedule and assign to elevator
  elev_sch = occ_schedule.clone(model)
  elevator_schedule = elev_sch.name.to_s

  # For elevator lights and fan, assume 100% operation during hours that elevator fraction > 0 (when elevator is in operation).
  # elevator lights
  lights_sch = occ_schedule.clone(model)
  lights_sch = lights_sch.to_ScheduleRuleset.get
  profiles = []
  profiles << lights_sch.defaultDaySchedule
  rules = lights_sch.scheduleRules
  rules.each do |rule|
    profiles << rule.daySchedule
  end
  profiles.each do |profile|
    times = profile.times
    values = profile.values
    values.each_with_index do |val, i|
      if val > 0
        profile.addValue(times[i], 1.0)
      end
    end
  end
  elevator_lights_schedule = lights_sch.name.to_s

  # elevator fan
  fan_sch = occ_schedule.clone(model)
  fan_sch = fan_sch.to_ScheduleRuleset.get
  profiles = []
  profiles << fan_sch.defaultDaySchedule
  rules = fan_sch.scheduleRules
  rules.each do |rule|
    profiles << rule.daySchedule
  end
  profiles.each do |profile|
    times = profile.times
    values = profile.values
    values.each_with_index do |val, i|
      if val > 0
        profile.addValue(times[i], 1.0)
      end
    end
  end
  elevator_fan_schedule = fan_sch.name.to_s

  # @todo currently add elevator doesn't allow me to choose the size of the elevator?
  # ref bldg pdf has formula for motor hp based on weight, speed, counterweight fraction and mech eff (in 5.1.4)

  # @todo should schedules change based on traction vs. hydraulic vs. just taking what is in prototype.

  # call add_elevator in Prototype.hvac_systems.rb to create elevator objects
  elevator = model_add_elevator(model,
                                target_space,
                                number_of_elevators,
                                elevator_type,
                                elevator_schedule,
                                elevator_fan_schedule,
                                elevator_lights_schedule,
                                building_type)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.elevators', "Adding #{elevator.multiplier.round(1)} #{elevator_type} elevators to the model in #{target_space.name}.")

  # check fraction lost on heat from elevator if traction, change to 100% lost if not setup that way.
  if elevator_type == 'Traction'
    elevator.definition.to_ElectricEquipmentDefinition.get.setFractionLatent(0.0)
    elevator.definition.to_ElectricEquipmentDefinition.get.setFractionRadiant(0.0)
    elevator.definition.to_ElectricEquipmentDefinition.get.setFractionLost(1.0)
  end

  return elevator
end
model_add_evap_cooler(model, thermal_zones) click to toggle source

Creates an evaporative cooler for each zone and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @return [Array<OpenStudio::Model::AirLoopHVAC>] the resulting evaporative coolers

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 4398
  def model_add_evap_cooler(model,
                            thermal_zones)

    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding evaporative coolers for #{thermal_zones.size} zones.")
    thermal_zones.each do |zone|
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "---#{zone.name}")
    end

    # default design temperatures used across all air loops
    dsgn_temps = standard_design_sizing_temperatures

    # adjusted design temperatures for evap cooler
    dsgn_temps['clg_dsgn_sup_air_temp_f'] = 70.0
    dsgn_temps['clg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['clg_dsgn_sup_air_temp_f'], 'F', 'C').get
    dsgn_temps['max_clg_dsgn_sup_air_temp_f'] = 78.0
    dsgn_temps['max_clg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['max_clg_dsgn_sup_air_temp_f'], 'F', 'C').get
    dsgn_temps['approach_r'] = 3.0 # wetbulb approach temperature
    dsgn_temps['approach_k'] = OpenStudio.convert(dsgn_temps['approach_r'], 'R', 'K').get

    # EMS programs
    programs = []

    # Make an evap cooler for each zone
    evap_coolers = []
    thermal_zones.each do |zone|
      zone_name_clean = zone.name.get.delete(':')

      # Air loop
      air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
      air_loop.setName("#{zone_name_clean} Evaporative Cooler")

      # default design settings used across all air loops
      sizing_system = adjust_sizing_system(air_loop, dsgn_temps)

      # air handler controls
      # setpoint follows OAT WetBulb
      evap_stpt_manager = OpenStudio::Model::SetpointManagerFollowOutdoorAirTemperature.new(model)
      evap_stpt_manager.setName("#{dsgn_temps['approach_r']} F above OATwb")
      evap_stpt_manager.setReferenceTemperatureType('OutdoorAirWetBulb')
      evap_stpt_manager.setMaximumSetpointTemperature(dsgn_temps['max_clg_dsgn_sup_air_temp_c'])
      evap_stpt_manager.setMinimumSetpointTemperature(dsgn_temps['clg_dsgn_sup_air_temp_c'])
      evap_stpt_manager.setOffsetTemperatureDifference(dsgn_temps['approach_k'])
      evap_stpt_manager.addToNode(air_loop.supplyOutletNode)

      # Schedule to control the airloop availability
      air_loop_avail_sch = OpenStudio::Model::ScheduleConstant.new(model)
      air_loop_avail_sch.setName("#{air_loop.name} Availability Sch")
      air_loop_avail_sch.setValue(1)
      air_loop.setAvailabilitySchedule(air_loop_avail_sch)

      # EMS to turn on Evap Cooler if there is a cooling load in the target zone.
      # Without this EMS, the airloop runs 24/7-365 even when there is no load in the zone.

      # Create a sensor to read the zone load
      zn_load_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model,
                                                                           'Zone Predicted Sensible Load to Cooling Setpoint Heat Transfer Rate')
      zn_load_sensor.setName("#{zone_name_clean.to_s.gsub(/[ +-.]/, '_')} Clg Load Sensor")
      zn_load_sensor.setKeyName(zone.handle.to_s)

      # Create an actuator to set the airloop availability
      air_loop_avail_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(air_loop_avail_sch,
                                                                                      'Schedule:Constant',
                                                                                      'Schedule Value')
      air_loop_avail_actuator.setName("#{air_loop.name.to_s.gsub(/[ +-.]/, '_')} Availability Actuator")

      # Create a program to turn on Evap Cooler if
      # there is a cooling load in the target zone.
      # Load < 0.0 is a cooling load.
      avail_program = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
      avail_program.setName("#{air_loop.name.to_s.gsub(/[ +-.]/, '_')} Availability Control")
      avail_program_body = <<-EMS
        IF #{zn_load_sensor.handle} < 0.0
          SET #{air_loop_avail_actuator.handle} = 1
        ELSE
          SET #{air_loop_avail_actuator.handle} = 0
        ENDIF
      EMS
      avail_program.setBody(avail_program_body)

      programs << avail_program

      # Direct Evap Cooler
      # @todo better assumptions for evap cooler performance and fan pressure rise
      evap = OpenStudio::Model::EvaporativeCoolerDirectResearchSpecial.new(model, model.alwaysOnDiscreteSchedule)
      evap.setName("#{zone.name} Evap Media")
      evap.autosizePrimaryAirDesignFlowRate
      evap.addToNode(air_loop.supplyInletNode)

      # Fan (cycling), must be inside unitary system to cycle on airloop
      fan = create_fan_by_name(model,
                               'Evap_Cooler_Supply_Fan',
                               fan_name: "#{zone.name} Evap Cooler Supply Fan")
      fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

      # Dummy zero-capacity cooling coil
      clg_coil = create_coil_cooling_dx_single_speed(model,
                                                     name: 'Dummy Always Off DX Coil',
                                                     schedule: model.alwaysOffDiscreteSchedule)
      unitary_system = OpenStudio::Model::AirLoopHVACUnitarySystem.new(model)
      unitary_system.setName("#{zone.name} Evap Cooler Cycling Fan")
      unitary_system.setSupplyFan(fan)
      unitary_system.setCoolingCoil(clg_coil)
      unitary_system.setControllingZoneorThermostatLocation(zone)
      unitary_system.setMaximumSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
      unitary_system.setFanPlacement('BlowThrough')
      if model.version < OpenStudio::VersionString.new('3.7.0')
        unitary_system.setSupplyAirFlowRateMethodDuringCoolingOperation('SupplyAirFlowRate')
        unitary_system.setSupplyAirFlowRateMethodDuringHeatingOperation('SupplyAirFlowRate')
        unitary_system.setSupplyAirFlowRateMethodWhenNoCoolingorHeatingisRequired('SupplyAirFlowRate')
      else
        unitary_system.autosizeSupplyAirFlowRateDuringCoolingOperation
        unitary_system.autosizeSupplyAirFlowRateDuringHeatingOperation
        unitary_system.autosizeSupplyAirFlowRateWhenNoCoolingorHeatingisRequired
      end
      unitary_system.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)
      unitary_system.addToNode(air_loop.supplyInletNode)

      # Outdoor air intake system
      oa_intake_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
      oa_intake_controller.setName("#{air_loop.name} OA Controller")
      oa_intake_controller.setMinimumLimitType('FixedMinimum')
      oa_intake_controller.autosizeMinimumOutdoorAirFlowRate
      oa_intake_controller.resetEconomizerMinimumLimitDryBulbTemperature
      oa_intake_controller.setMinimumFractionofOutdoorAirSchedule(model.alwaysOnDiscreteSchedule)
      controller_mv = oa_intake_controller.controllerMechanicalVentilation
      controller_mv.setName("#{air_loop.name} Vent Controller")
      controller_mv.setSystemOutdoorAirMethod('ZoneSum')

      oa_intake = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_intake_controller)
      oa_intake.setName("#{air_loop.name} OA System")
      oa_intake.addToNode(air_loop.supplyInletNode)

      # make an air terminal for the zone
      air_terminal = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)
      air_terminal.setName("#{zone.name} Air Terminal")

      # attach new terminal to the zone and to the airloop
      air_loop.multiAddBranchForZone(zone, air_terminal.to_HVACComponent.get)

      sizing_zone = zone.sizingZone
      sizing_zone.setCoolingDesignAirFlowMethod('DesignDay')
      sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])

      evap_coolers << air_loop
    end

    # Create a programcallingmanager
    avail_pcm = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
    avail_pcm.setName('EvapCoolerAvailabilityProgramCallingManager')
    avail_pcm.setCallingPoint('AfterPredictorAfterHVACManagers')
    programs.each do |program|
      avail_pcm.addProgram(program)
    end

    return evap_coolers
  end
model_add_exhaust_fan(model, thermal_zones, flow_rate: nil, availability_sch_name: nil, flow_fraction_schedule_name: nil, balanced_exhaust_fraction_schedule_name: nil) click to toggle source

Adds an exhaust fan to each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] an array of thermal zones @param flow_rate [Double] the exhaust fan flow rate in m^3/s @param availability_sch_name [String] the name of the fan availability schedule @param flow_fraction_schedule_name [String] the name of the flow fraction schedule @param balanced_exhaust_fraction_schedule_name [String] the name of the balanced exhaust fraction schedule @return [Array<OpenStudio::Model::FanZoneExhaust>] an array of exhaust fans created @todo use the create_fan_zone_exhaust method, default to 1.25 inH2O pressure rise and fan efficiency of 0.6

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6092
def model_add_exhaust_fan(model,
                          thermal_zones,
                          flow_rate: nil,
                          availability_sch_name: nil,
                          flow_fraction_schedule_name: nil,
                          balanced_exhaust_fraction_schedule_name: nil)

  if availability_sch_name.nil?
    availability_schedule = model.alwaysOnDiscreteSchedule
  else
    availability_schedule = model_add_schedule(model, availability_sch_name)
  end

  # make an exhaust fan for each zone
  fans = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding zone exhaust fan for #{zone.name}.")
    fan = OpenStudio::Model::FanZoneExhaust.new(model)
    fan.setName("#{zone.name} Exhaust Fan")
    fan.setAvailabilitySchedule(availability_schedule)

    # input the flow rate as a number (assign directly) or from an array (assign each flow rate to each zone)
    if flow_rate.is_a? Numeric
      fan.setMaximumFlowRate(flow_rate)
    elsif flow_rate.class.to_s == 'Array'
      index = thermal_zones.index(zone)
      flow_rate_zone = flow_rate[index]
      fan.setMaximumFlowRate(flow_rate_zone)
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', 'Wrong format of flow rate')
    end

    unless flow_fraction_schedule_name.nil?
      fan.setFlowFractionSchedule(model_add_schedule(model, flow_fraction_schedule_name))
    end

    fan.setSystemAvailabilityManagerCouplingMode('Decoupled')
    unless balanced_exhaust_fraction_schedule_name.nil?
      fan.setBalancedExhaustFractionSchedule(model_add_schedule(model, balanced_exhaust_fraction_schedule_name))
    end

    fan.addToThermalZone(zone)
    fans << fan
  end

  return fans
end
model_add_four_pipe_fan_coil(model, thermal_zones, chilled_water_loop, hot_water_loop: nil, ventilation: false, capacity_control_method: 'CyclingFan') click to toggle source

Adds four pipe fan coil units to each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to add fan coil units @param chilled_water_loop [OpenStudio::Model::PlantLoop] the chilled water loop that serves the fan coils. @param hot_water_loop [OpenStudio::Model::PlantLoop] the hot water loop that serves the fan coils.

If nil, a zero-capacity, electric heating coil set to Always-Off will be included in the unit.

@param ventilation [Boolean] If true, ventilation will be supplied through the unit. If false,

no ventilation will be supplied through the unit, with the expectation that it will be provided by a DOAS or separate system.

@param capacity_control_method [String] Capacity control method for the fan coil. Options are ConstantFanVariableFlow,

CyclingFan, VariableFanVariableFlow, and VariableFanConstantFlow.  If VariableFan, the fan will be VariableVolume.

@return [Array<OpenStudio::Model::ZoneHVACFourPipeFanCoil>] array of fan coil units.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 4659
def model_add_four_pipe_fan_coil(model,
                                 thermal_zones,
                                 chilled_water_loop,
                                 hot_water_loop: nil,
                                 ventilation: false,
                                 capacity_control_method: 'CyclingFan')

  # default design temperatures used across all air loops
  dsgn_temps = standard_design_sizing_temperatures

  # make a fan coil unit for each zone
  fcus = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding fan coil for #{zone.name}.")
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])

    if chilled_water_loop
      fcu_clg_coil = create_coil_cooling_water(model,
                                               chilled_water_loop,
                                               name: "#{zone.name} FCU Cooling Coil")
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'Fan coil units require a chilled water loop, but none was provided.')
      return false
    end

    if hot_water_loop
      fcu_htg_coil = create_coil_heating_water(model,
                                               hot_water_loop,
                                               name: "#{zone.name} FCU Heating Coil",
                                               rated_outlet_air_temperature: dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    else
      # Zero-capacity, always-off electric heating coil
      fcu_htg_coil = create_coil_heating_electric(model,
                                                  name: "#{zone.name} No Heat",
                                                  schedule: model.alwaysOffDiscreteSchedule,
                                                  nominal_capacity: 0.0)
    end

    case capacity_control_method
    when 'VariableFanVariableFlow', 'VariableFanConstantFlow'
      fcu_fan = create_fan_by_name(model,
                                   'Fan_Coil_VarSpeed_Fan',
                                   fan_name: "#{zone.name} Fan Coil Variable Fan",
                                   end_use_subcategory: 'FCU Fans')
    else
      fcu_fan = create_fan_by_name(model,
                                   'Fan_Coil_Fan',
                                   fan_name: "#{zone.name} Fan Coil fan",
                                   end_use_subcategory: 'FCU Fans')
    end
    fcu_fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
    fcu_fan.autosizeMaximumFlowRate

    fcu = OpenStudio::Model::ZoneHVACFourPipeFanCoil.new(model,
                                                         model.alwaysOnDiscreteSchedule,
                                                         fcu_fan,
                                                         fcu_clg_coil,
                                                         fcu_htg_coil)
    fcu.setName("#{zone.name} FCU")
    fcu.setCapacityControlMethod(capacity_control_method)
    fcu.autosizeMaximumSupplyAirFlowRate
    unless ventilation
      fcu.setMaximumOutdoorAirFlowRate(0.0)
    end
    fcu.addToThermalZone(zone)
    fcus << fcu
  end

  return fcus
end
model_add_furnace_central_ac(model, thermal_zones, heating: true, cooling: false, ventilation: false) click to toggle source

Adds a forced air furnace or central AC to each zone. Default is a forced air furnace without outdoor air Code adapted from: github.com/NREL/OpenStudio-BEopt/blob/master/measures/ResidentialHVACFurnaceFuel/measure.rb

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to add fan coil units to. @param heating [Boolean] if true, the unit will include a NaturalGas heating coil @param cooling [Boolean] if true, the unit will include a DX cooling coil @param ventilation [Boolean] if true, the unit will include an OA intake @return [Array<OpenStudio::Model::AirLoopHVAC>] and array of air loops representing the furnaces

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 5336
def model_add_furnace_central_ac(model,
                                 thermal_zones,
                                 heating: true,
                                 cooling: false,
                                 ventilation: false)

  if heating && cooling
    equip_name = 'Central Heating and AC'
  elsif heating && !cooling
    equip_name = 'Furnace'
  elsif cooling && !heating
    equip_name = 'Central AC'
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', 'Heating and cooling both disabled, not a valid Furnace or Central AC selection, no equipment was added.')
    return false
  end

  # defaults
  afue = 0.78
  # seer = 13.0
  eer = 11.1
  shr = 0.73
  ac_w_per_cfm = 0.365
  crank_case_heat_w = 0.0
  crank_case_max_temp_f = 55.0

  furnaces = []
  thermal_zones.each do |zone|
    air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
    air_loop.setName("#{zone.name} #{equip_name}")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding furnace AC for #{zone.name}.")

    # default design temperatures across all air loops
    dsgn_temps = standard_design_sizing_temperatures

    # adjusted temperatures for furnace_central_ac
    dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
    dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
    dsgn_temps['htg_dsgn_sup_air_temp_f'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_f']
    dsgn_temps['htg_dsgn_sup_air_temp_c'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_c']

    # default design settings used across all air loops
    sizing_system = adjust_sizing_system(air_loop, dsgn_temps, sizing_option: 'NonCoincident')
    sizing_system.setAllOutdoorAirinCooling(true)
    sizing_system.setAllOutdoorAirinHeating(true)

    # create heating coil
    htg_coil = nil
    if heating
      htg_coil = create_coil_heating_gas(model,
                                         name: "#{air_loop.name} Heating Coil",
                                         efficiency: afue_to_thermal_eff(afue))
    end

    # create cooling coil
    clg_coil = nil
    if cooling
      clg_coil = create_coil_cooling_dx_single_speed(model,
                                                     name: "#{air_loop.name} Cooling Coil",
                                                     type: 'Residential Central AC')
      clg_coil.setRatedSensibleHeatRatio(shr)
      clg_coil.setRatedCOP(OpenStudio::OptionalDouble.new(eer_to_cop_no_fan(eer)))
      clg_coil.setRatedEvaporatorFanPowerPerVolumeFlowRate(OpenStudio::OptionalDouble.new(ac_w_per_cfm / OpenStudio.convert(1.0, 'cfm', 'm^3/s').get))
      clg_coil.setNominalTimeForCondensateRemovalToBegin(OpenStudio::OptionalDouble.new(1000.0))
      clg_coil.setRatioOfInitialMoistureEvaporationRateAndSteadyStateLatentCapacity(OpenStudio::OptionalDouble.new(1.5))
      clg_coil.setMaximumCyclingRate(OpenStudio::OptionalDouble.new(3.0))
      clg_coil.setLatentCapacityTimeConstant(OpenStudio::OptionalDouble.new(45.0))
      clg_coil.setCondenserType('AirCooled')
      clg_coil.setCrankcaseHeaterCapacity(OpenStudio::OptionalDouble.new(crank_case_heat_w))
      clg_coil.setMaximumOutdoorDryBulbTemperatureForCrankcaseHeaterOperation(OpenStudio::OptionalDouble.new(OpenStudio.convert(crank_case_max_temp_f, 'F', 'C').get))
    end

    # create fan
    fan = create_fan_by_name(model,
                             'Residential_HVAC_Fan',
                             fan_name: "#{air_loop.name} Supply Fan",
                             end_use_subcategory: 'Residential HVAC Fans')
    fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

    if ventilation
      # create outdoor air intake
      oa_intake_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
      oa_intake_controller.setName("#{air_loop.name} OA Controller")
      oa_intake_controller.autosizeMinimumOutdoorAirFlowRate
      oa_intake_controller.resetEconomizerMinimumLimitDryBulbTemperature
      oa_intake = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_intake_controller)
      oa_intake.setName("#{air_loop.name} OA System")
      oa_intake.addToNode(air_loop.supplyInletNode)
    end

    # create unitary system (holds the coils and fan)
    unitary = OpenStudio::Model::AirLoopHVACUnitarySystem.new(model)
    unitary.setName("#{air_loop.name} Unitary System")
    unitary.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
    unitary.setMaximumSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    unitary.setControllingZoneorThermostatLocation(zone)
    unitary.addToNode(air_loop.supplyInletNode)

    # set flow rates during different conditions
    unitary.setSupplyAirFlowRateDuringHeatingOperation(0.0) unless heating
    unitary.setSupplyAirFlowRateDuringCoolingOperation(0.0) unless cooling
    unitary.setSupplyAirFlowRateWhenNoCoolingorHeatingisRequired(0.0) unless ventilation

    # attach the coils and fan
    unitary.setHeatingCoil(htg_coil) if htg_coil
    unitary.setCoolingCoil(clg_coil) if clg_coil
    unitary.setSupplyFan(fan)
    unitary.setFanPlacement('BlowThrough')
    unitary.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)

    # create a diffuser
    diffuser = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)
    diffuser.setName("#{zone.name} Direct Air")
    air_loop.multiAddBranchForZone(zone, diffuser.to_HVACComponent.get)

    furnaces << air_loop
  end

  return furnaces
end
model_add_ground_hx_loop(model, system_name: 'Ground HX Loop') click to toggle source

Creates loop that roughly mimics a properly sized ground heat exchanger for supplemental heating/cooling and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param system_name [String] the name of the system, or nil in which case it will be defaulted @return [OpenStudio::Model::PlantLoop] the resulting plant loop @todo replace condenser loop w/ ground HX model that does not involve district objects

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 965
  def model_add_ground_hx_loop(model,
                               system_name: 'Ground HX Loop')
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', 'Adding ground source loop.')

    # create ground hx loop
    ground_hx_loop = OpenStudio::Model::PlantLoop.new(model)
    if system_name.nil?
      ground_hx_loop.setName('Ground HX Loop')
    else
      ground_hx_loop.setName(system_name)
    end

    # ground hx loop sizing and controls
    ground_hx_loop.setMinimumLoopTemperature(5.0)
    ground_hx_loop.setMaximumLoopTemperature(80.0)
    delta_t_k = OpenStudio.convert(12.0, 'R', 'K').get # temp change at high and low entering condition
    min_inlet_c = OpenStudio.convert(30.0, 'F', 'C').get # low entering condition.
    max_inlet_c = OpenStudio.convert(90.0, 'F', 'C').get # high entering condition

    # calculate the linear formula that defines outlet temperature based on inlet temperature of the ground hx
    min_outlet_c = min_inlet_c + delta_t_k
    max_outlet_c = max_inlet_c - delta_t_k
    slope_c_per_c = (max_outlet_c - min_outlet_c) / (max_inlet_c - min_inlet_c)
    intercept_c = min_outlet_c - (slope_c_per_c * min_inlet_c)

    sizing_plant = ground_hx_loop.sizingPlant
    sizing_plant.setLoopType('Heating')
    sizing_plant.setDesignLoopExitTemperature(max_outlet_c)
    sizing_plant.setLoopDesignTemperatureDifference(delta_t_k)

    # create pump
    pump = OpenStudio::Model::PumpConstantSpeed.new(model)
    pump.setName("#{ground_hx_loop.name} Pump")
    pump.setRatedPumpHead(OpenStudio.convert(60.0, 'ftH_{2}O', 'Pa').get)
    pump.setPumpControlType('Intermittent')
    pump.addToNode(ground_hx_loop.supplyInletNode)

    # use EMS and a PlantComponentTemperatureSource to mimic the operation of the ground heat exchanger.

    # schedule to actuate ground HX outlet temperature
    hx_temp_sch = OpenStudio::Model::ScheduleConstant.new(model)
    hx_temp_sch.setName('Ground HX Temp Sch')
    hx_temp_sch.setValue(24.0)

    ground_hx = OpenStudio::Model::PlantComponentTemperatureSource.new(model)
    ground_hx.setName('Ground HX')
    ground_hx.setTemperatureSpecificationType('Scheduled')
    ground_hx.setSourceTemperatureSchedule(hx_temp_sch)
    ground_hx_loop.addSupplyBranchForComponent(ground_hx)

    hx_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, hx_temp_sch)
    hx_stpt_manager.setName("#{ground_hx.name} Supply Outlet Setpoint")
    hx_stpt_manager.addToNode(ground_hx.outletModelObject.get.to_Node.get)

    loop_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, hx_temp_sch)
    loop_stpt_manager.setName("#{ground_hx_loop.name} Supply Outlet Setpoint")
    loop_stpt_manager.addToNode(ground_hx_loop.supplyOutletNode)

    # sensor to read supply inlet temperature
    inlet_temp_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model,
                                                                            'System Node Temperature')
    inlet_temp_sensor.setName("#{ground_hx.name.to_s.gsub(/[ +-.]/, '_')} Inlet Temp Sensor")
    inlet_temp_sensor.setKeyName(ground_hx_loop.supplyInletNode.handle.to_s)

    # actuator to set supply outlet temperature
    outlet_temp_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(hx_temp_sch,
                                                                                 'Schedule:Constant',
                                                                                 'Schedule Value')
    outlet_temp_actuator.setName("#{ground_hx.name} Outlet Temp Actuator")

    # program to control outlet temperature
    # adjusts delta-t based on calculation of slope and intercept from control temperatures
    program = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
    program.setName("#{ground_hx.name.to_s.gsub(/[ +-.]/, '_')} Temperature Control")
    program_body = <<-EMS
      SET Tin = #{inlet_temp_sensor.handle}
      SET Tout = #{slope_c_per_c.round(2)} * Tin + #{intercept_c.round(1)}
      SET #{outlet_temp_actuator.handle} = Tout
    EMS
    program.setBody(program_body)

    # program calling manager
    pcm = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
    pcm.setName("#{program.name.to_s.gsub(/[ +-.]/, '_')} Calling Manager")
    pcm.setCallingPoint('InsideHVACSystemIterationLoop')
    pcm.addProgram(program)

    return ground_hx_loop
  end
model_add_heatpump_water_heater(model, type: 'PumpedCondenser', water_heater_capacity: 500, electric_backup_capacity: 4500, water_heater_volume: OpenStudio.convert(80.0, 'gal', 'm^3').get, service_water_temperature: OpenStudio.convert(125.0, 'F', 'C').get, parasitic_fuel_consumption_rate: 3.0, swh_temp_sch: nil, cop: 2.8, shr: 0.88, tank_ua: 3.9, set_peak_use_flowrate: false, peak_flowrate: 0.0, flowrate_schedule: nil, water_heater_thermal_zone: nil, use_ems_control: false) click to toggle source

Creates a heatpump water heater and attaches it to the supplied service water heating loop.

@param model [OpenStudio::Model::Model] OpenStudio model object @param type [String] valid option are ‘WrappedCondenser’ or ‘PumpedCondenser’ (default).

The 'WrappedCondenser' uses a WaterHeaterStratified tank, 'PumpedCondenser' uses a WaterHeaterMixed tank.

@param water_heater_capacity [Double] water heater capacity, in W @param water_heater_volume [Double] water heater volume, in m^3 @param service_water_temperature [Double] water heater temperature, in C @param parasitic_fuel_consumption_rate [Double] water heater parasitic fuel consumption rate, in W @param swh_temp_sch [OpenStudio::Model::Schedule] the service water heating schedule. If nil, will be defaulted. @param set_peak_use_flowrate [Boolean] if true, the peak flow rate and flow rate schedule will be set. @param peak_flowrate [Double] in m^3/s @param flowrate_schedule [String] name of the flow rate schedule @param water_heater_thermal_zone [OpenStudio::Model::ThermalZone] zone to place water heater in.

If nil, will be assumed in 70F air for heat loss.

@param use_ems_control [Boolean] if true, use ems control logic if using a ‘WrappedCondenser’ style HPWH. @return [OpenStudio::Model::WaterHeaterMixed] the resulting water heater

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ServiceWaterHeating.rb, line 327
def model_add_heatpump_water_heater(model,
                                    type: 'PumpedCondenser',
                                    water_heater_capacity: 500,
                                    electric_backup_capacity: 4500,
                                    water_heater_volume: OpenStudio.convert(80.0, 'gal', 'm^3').get,
                                    service_water_temperature: OpenStudio.convert(125.0, 'F', 'C').get,
                                    parasitic_fuel_consumption_rate: 3.0,
                                    swh_temp_sch: nil,
                                    cop: 2.8,
                                    shr: 0.88,
                                    tank_ua: 3.9,
                                    set_peak_use_flowrate: false,
                                    peak_flowrate: 0.0,
                                    flowrate_schedule: nil,
                                    water_heater_thermal_zone: nil,
                                    use_ems_control: false)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', 'Adding heat pump water heater')

  # create heat pump water heater
  if type == 'WrappedCondenser'
    hpwh = OpenStudio::Model::WaterHeaterHeatPumpWrappedCondenser.new(model)
  elsif type == 'PumpedCondenser'
    hpwh = OpenStudio::Model::WaterHeaterHeatPump.new(model)
  end

  # calculate tank height and radius
  water_heater_capacity_kbtu_per_hr = OpenStudio.convert(water_heater_capacity, 'W', 'kBtu/hr').get
  hpwh_vol_gal = OpenStudio.convert(water_heater_volume, 'm^3', 'gal').get
  tank_height = 0.0188 * hpwh_vol_gal + 0.0935 # linear relationship that gets GE height at 50 gal and AO Smith height at 80 gal
  tank_radius = (0.9 * water_heater_volume / (Math::PI * tank_height))**0.5
  tank_surface_area = 2.0 * Math::PI * tank_radius * (tank_radius + tank_height)
  u_tank = (5.678 * tank_ua) / OpenStudio.convert(tank_surface_area, 'm^2', 'ft^2').get
  hpwh.setName("#{hpwh_vol_gal.round}gal Heat Pump Water Heater - #{water_heater_capacity_kbtu_per_hr.round(0)}kBtu/hr")

  # set min/max HPWH operating temperature limit
  hpwh_op_min_temp_c = OpenStudio.convert(45.0, 'F', 'C').get
  hpwh_op_max_temp_c = OpenStudio.convert(120.0, 'F', 'C').get

  if type == 'WrappedCondenser'
    hpwh.setMinimumInletAirTemperatureforCompressorOperation(hpwh_op_min_temp_c)
    hpwh.setMaximumInletAirTemperatureforCompressorOperation(hpwh_op_max_temp_c)
    # set sensor heights
    if hpwh_vol_gal <= 50.0
      hpwh.setDeadBandTemperatureDifference(0.5)
      h_ue = (1 - (3.5 / 12.0)) * tank_height # in the 4th node of the tank (counting from top)
      h_le = (1 - (10.5 / 12.0)) * tank_height # in the 11th node of the tank (counting from top)
      h_condtop = (1 - (5.5 / 12.0)) * tank_height # in the 6th node of the tank (counting from top)
      h_condbot = (1 - (10.99 / 12.0)) * tank_height # in the 11th node of the tank
      h_hpctrl = (1 - (2.5 / 12.0)) * tank_height # in the 3rd node of the tank
      hpwh.setControlSensor1HeightInStratifiedTank(h_hpctrl)
      hpwh.setControlSensor1Weight(1.0)
      hpwh.setControlSensor2HeightInStratifiedTank(h_hpctrl)
    else
      hpwh.setDeadBandTemperatureDifference(3.89)
      h_ue = (1 - (3.5 / 12.0)) * tank_height # in the 3rd node of the tank (counting from top)
      h_le = (1 - (9.5 / 12.0)) * tank_height # in the 10th node of the tank (counting from top)
      h_condtop = (1 - (5.5 / 12.0)) * tank_height # in the 6th node of the tank (counting from top)
      h_condbot = 0.01 # bottom node
      h_hpctrl_up = (1 - (2.5 / 12.0)) * tank_height # in the 3rd node of the tank
      h_hpctrl_low = (1 - (8.5 / 12.0)) * tank_height # in the 9th node of the tank
      hpwh.setControlSensor1HeightInStratifiedTank(h_hpctrl_up)
      hpwh.setControlSensor1Weight(0.75)
      hpwh.setControlSensor2HeightInStratifiedTank(h_hpctrl_low)
    end
    hpwh.setCondenserBottomLocation(h_condbot)
    hpwh.setCondenserTopLocation(h_condtop)
    hpwh.setTankElementControlLogic('MutuallyExclusive')
    hpwh.autocalculateEvaporatorAirFlowRate
  elsif type == 'PumpedCondenser'
    hpwh.setDeadBandTemperatureDifference(3.89)
    hpwh.autosizeEvaporatorAirFlowRate
  end

  # set heat pump water heater properties
  hpwh.setFanPlacement('DrawThrough')
  hpwh.setOnCycleParasiticElectricLoad(0.0)
  hpwh.setOffCycleParasiticElectricLoad(0.0)
  hpwh.setParasiticHeatRejectionLocation('Outdoors')

  # set temperature setpoint schedule
  if swh_temp_sch.nil?
    # temperature schedule type limits
    temp_sch_type_limits = OpenstudioStandards::Schedules.create_schedule_type_limits(model,
                                                                                      name: 'Temperature Schedule Type Limits',
                                                                                      lower_limit_value: 0.0,
                                                                                      upper_limit_value: 100.0,
                                                                                      numeric_type: 'Continuous',
                                                                                      unit_type: 'Temperature')
    # service water heating loop controls
    swh_temp_c = service_water_temperature
    swh_temp_f = OpenStudio.convert(swh_temp_c, 'C', 'F').get
    swh_delta_t_r = 9.0 # 9F delta-T
    swh_temp_c = OpenStudio.convert(swh_temp_f, 'F', 'C').get
    swh_delta_t_k = OpenStudio.convert(swh_delta_t_r, 'R', 'K').get
    swh_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                   swh_temp_c,
                                                                                   name: "Heat Pump Water Heater Temp - #{swh_temp_f.round}F",
                                                                                   schedule_type_limit: 'Temperature')
    swh_temp_sch.setScheduleTypeLimits(temp_sch_type_limits)
  end
  hpwh.setCompressorSetpointTemperatureSchedule(swh_temp_sch)

  # coil curves
  hpwh_cap = OpenStudio::Model::CurveBiquadratic.new(model)
  hpwh_cap.setName('HPWH-Cap-fT')
  hpwh_cap.setCoefficient1Constant(0.563)
  hpwh_cap.setCoefficient2x(0.0437)
  hpwh_cap.setCoefficient3xPOW2(0.000039)
  hpwh_cap.setCoefficient4y(0.0055)
  hpwh_cap.setCoefficient5yPOW2(-0.000148)
  hpwh_cap.setCoefficient6xTIMESY(-0.000145)
  hpwh_cap.setMinimumValueofx(0.0)
  hpwh_cap.setMaximumValueofx(100.0)
  hpwh_cap.setMinimumValueofy(0.0)
  hpwh_cap.setMaximumValueofy(100.0)

  hpwh_cop = OpenStudio::Model::CurveBiquadratic.new(model)
  hpwh_cop.setName('HPWH-COP-fT')
  hpwh_cop.setCoefficient1Constant(1.1332)
  hpwh_cop.setCoefficient2x(0.063)
  hpwh_cop.setCoefficient3xPOW2(-0.0000979)
  hpwh_cop.setCoefficient4y(-0.00972)
  hpwh_cop.setCoefficient5yPOW2(-0.0000214)
  hpwh_cop.setCoefficient6xTIMESY(-0.000686)
  hpwh_cop.setMinimumValueofx(0.0)
  hpwh_cop.setMaximumValueofx(100.0)
  hpwh_cop.setMinimumValueofy(0.0)
  hpwh_cop.setMaximumValueofy(100.0)

  # create DX coil object
  if type == 'WrappedCondenser'
    coil = hpwh.dXCoil.to_CoilWaterHeatingAirToWaterHeatPumpWrapped.get
    coil.setRatedCondenserWaterTemperature(48.89)
    coil.autocalculateRatedEvaporatorAirFlowRate
  elsif type == 'PumpedCondenser'
    coil = hpwh.dXCoil.to_CoilWaterHeatingAirToWaterHeatPump.get
    coil.autosizeRatedEvaporatorAirFlowRate
  end

  # set coil properties
  coil.setName("#{hpwh.name} Coil")
  coil.setRatedHeatingCapacity(water_heater_capacity)
  coil.setRatedCOP(cop)
  coil.setRatedSensibleHeatRatio(shr)
  coil.setRatedEvaporatorInletAirDryBulbTemperature(OpenStudio.convert(67.5, 'F', 'C').get)
  coil.setRatedEvaporatorInletAirWetBulbTemperature(OpenStudio.convert(56.426, 'F', 'C').get)
  coil.setEvaporatorFanPowerIncludedinRatedCOP(true)
  coil.setEvaporatorAirTemperatureTypeforCurveObjects('WetBulbTemperature')
  coil.setHeatingCapacityFunctionofTemperatureCurve(hpwh_cap)
  coil.setHeatingCOPFunctionofTemperatureCurve(hpwh_cop)
  coil.setMaximumAmbientTemperatureforCrankcaseHeaterOperation(0.0)

  # set tank properties
  if type == 'WrappedCondenser'
    tank = hpwh.tank.to_WaterHeaterStratified.get
    tank.setTankHeight(tank_height)
    tank.setHeaterPriorityControl('MasterSlave')
    if hpwh_vol_gal <= 50.0
      tank.setHeater1DeadbandTemperatureDifference(25.0)
      tank.setHeater2DeadbandTemperatureDifference(30.0)
    else
      tank.setHeater1DeadbandTemperatureDifference(18.5)
      tank.setHeater2DeadbandTemperatureDifference(3.89)
    end
    hpwh_bottom_element_sp = OpenStudio::Model::ScheduleConstant.new(model)
    hpwh_bottom_element_sp.setName("#{hpwh.name} BottomElementSetpoint")
    hpwh_top_element_sp = OpenStudio::Model::ScheduleConstant.new(model)
    hpwh_top_element_sp.setName("#{hpwh.name} TopElementSetpoint")
    tank.setHeater1Capacity(electric_backup_capacity)
    tank.setHeater1Height(h_ue)
    tank.setHeater1SetpointTemperatureSchedule(hpwh_top_element_sp) # Overwritten later by EMS
    tank.setHeater2Capacity(electric_backup_capacity)
    tank.setHeater2Height(h_le)
    tank.setHeater2SetpointTemperatureSchedule(hpwh_bottom_element_sp)
    tank.setUniformSkinLossCoefficientperUnitAreatoAmbientTemperature(u_tank)
    tank.setNumberofNodes(12)
    tank.setAdditionalDestratificationConductivity(0)
    tank.setNode1AdditionalLossCoefficient(0)
    tank.setNode2AdditionalLossCoefficient(0)
    tank.setNode3AdditionalLossCoefficient(0)
    tank.setNode4AdditionalLossCoefficient(0)
    tank.setNode5AdditionalLossCoefficient(0)
    tank.setNode6AdditionalLossCoefficient(0)
    tank.setNode7AdditionalLossCoefficient(0)
    tank.setNode8AdditionalLossCoefficient(0)
    tank.setNode9AdditionalLossCoefficient(0)
    tank.setNode10AdditionalLossCoefficient(0)
    tank.setNode11AdditionalLossCoefficient(0)
    tank.setNode12AdditionalLossCoefficient(0)
    tank.setUseSideDesignFlowRate(0.9 * water_heater_volume / 60.1)
    tank.setSourceSideDesignFlowRate(0)
    tank.setSourceSideFlowControlMode('')
    tank.setSourceSideInletHeight(0)
    tank.setSourceSideOutletHeight(0)
  elsif type == 'PumpedCondenser'
    tank = hpwh.tank.to_WaterHeaterMixed.get
    tank.setDeadbandTemperatureDifference(3.89)
    tank.setHeaterControlType('Cycle')
    tank.setHeaterMaximumCapacity(electric_backup_capacity)
  end
  tank.setName("#{hpwh.name} Tank")
  tank.setEndUseSubcategory('Service Hot Water')
  tank.setTankVolume(0.9 * water_heater_volume)
  tank.setMaximumTemperatureLimit(90.0)
  tank.setHeaterFuelType('Electricity')
  tank.setHeaterThermalEfficiency(1.0)
  tank.setOffCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
  tank.setOffCycleParasiticFuelType('Electricity')
  tank.setOnCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
  tank.setOnCycleParasiticFuelType('Electricity')

  # set fan properties
  fan = hpwh.fan.to_FanOnOff.get
  fan.setName("#{hpwh.name} Fan")
  fan_power = 0.0462 # watts per cfm
  if hpwh_vol_gal <= 50.0
    fan.setFanEfficiency(23.0 / fan_power * OpenStudio.convert(1.0, 'ft^3/min', 'm^3/s').get)
    fan.setPressureRise(23.0)
  else
    fan.setFanEfficiency(65.0 / fan_power * OpenStudio.convert(1.0, 'ft^3/min', 'm^3/s').get)
    fan.setPressureRise(65.0)
  end
  # determine maximum flow rate from water heater capacity
  # use 5.035E-5 m^3/s/W from EnergyPlus used to autocalculate the evaporator air flow rate in WaterHeater:HeatPump:PumpedCondenser and Coil:WaterHeating:AirToWaterHeatPump:Pumped
  fan_flow_rate_m3_per_s = water_heater_capacity * 5.035e-5
  fan.setMaximumFlowRate(fan_flow_rate_m3_per_s)
  fan.setMotorEfficiency(1.0)
  fan.setMotorInAirstreamFraction(1.0)
  fan.setEndUseSubcategory('Service Hot Water')

  if water_heater_thermal_zone.nil?
    # add in schedules for Tamb, RHamb, and the compressor
    # assume the water heater is indoors at 70F for now
    default_water_heater_ambient_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                            OpenStudio.convert(70.0, 'F', 'C').get,
                                                                                                            name: 'Water Heater Ambient Temp Schedule - 70F',
                                                                                                            schedule_type_limit: 'Temperature')
    if temp_sch_type_limits.nil?
      temp_sch_type_limits = OpenstudioStandards::Schedules.create_schedule_type_limits(model,
                                                                                        name: 'Temperature Schedule Type Limits',
                                                                                        lower_limit_value: 0.0,
                                                                                        upper_limit_value: 100.0,
                                                                                        numeric_type: 'Continuous',
                                                                                        unit_type: 'Temperature')
    end
    default_water_heater_ambient_temp_sch.setScheduleTypeLimits(temp_sch_type_limits)
    tank.setAmbientTemperatureIndicator('Schedule')
    tank.setAmbientTemperatureSchedule(default_water_heater_ambient_temp_sch)
    tank.resetAmbientTemperatureThermalZone
    hpwh_rhamb = OpenStudio::Model::ScheduleConstant.new(model)
    hpwh_rhamb.setName("#{hpwh.name} Ambient Humidity Schedule")
    hpwh_rhamb.setValue(0.5)
    hpwh.setInletAirConfiguration('Schedule')
    hpwh.setInletAirTemperatureSchedule(default_water_heater_ambient_temp_sch)
    hpwh.setInletAirHumiditySchedule(hpwh_rhamb)
    hpwh.setCompressorLocation('Schedule')
    hpwh.setCompressorAmbientTemperatureSchedule(default_water_heater_ambient_temp_sch)
  else
    hpwh.addToThermalZone(water_heater_thermal_zone)
    hpwh.setInletAirConfiguration('ZoneAirOnly')
    hpwh.setCompressorLocation('Zone')
    tank.setAmbientTemperatureIndicator('ThermalZone')
    tank.setAmbientTemperatureThermalZone(water_heater_thermal_zone)
    tank.resetAmbientTemperatureSchedule
  end

  if set_peak_use_flowrate
    rated_flow_rate_m3_per_s = peak_flowrate
    rated_flow_rate_gal_per_min = OpenStudio.convert(rated_flow_rate_m3_per_s, 'm^3/s', 'gal/min').get
    tank.setPeakUseFlowRate(rated_flow_rate_m3_per_s)
    schedule = model_add_schedule(model, flowrate_schedule)
    tank.setUseFlowRateFractionSchedule(schedule)
  end

  # add EMS for overriding HPWH setpoints schedules (for upper/lower heating element in water tank and compressor in heat pump)
  if type == 'WrappedCondenser' && use_ems_control
    hpwh_name_ems_friendly = ems_friendly_name(hpwh.name)

    # create an ambient temperature sensor for the air that blows through the HPWH evaporator
    if water_heater_thermal_zone.nil?
      # assume the condenser is outside
      amb_temp_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Site Outdoor Air Drybulb Temperature')
      amb_temp_sensor.setName("#{hpwh_name_ems_friendly}_amb_temp")
      amb_temp_sensor.setKeyName('Environment')
    else
      amb_temp_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Zone Mean Air Temperature')
      amb_temp_sensor.setName("#{hpwh_name_ems_friendly}_amb_temp")
      amb_temp_sensor.setKeyName(water_heater_thermal_zone.name.to_s)
    end

    # create actuator for heat pump compressor
    if swh_temp_sch.to_ScheduleConstant.is_initialized
      swh_temp_sch = swh_temp_sch.to_ScheduleConstant.get
      schedule_type = 'Schedule:Constant'
    elsif swh_temp_sch.to_ScheduleCompact.is_initialized
      swh_temp_sch = swh_temp_sch.to_ScheduleCompact.get
      schedule_type = 'Schedule:Compact'
    elsif swh_temp_sch.to_ScheduleRuleset.is_initialized
      swh_temp_sch = swh_temp_sch.to_ScheduleRuleset.get
      schedule_type = 'Schedule:Year'
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Prototype.ServiceWaterHeating', "Unsupported schedule type for HPWH setpoint schedule #{swh_temp_sch.name}.")
      return false
    end
    hpwhschedoverride_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(swh_temp_sch, schedule_type, 'Schedule Value')
    hpwhschedoverride_actuator.setName("#{hpwh_name_ems_friendly}_HPWHSchedOverride")

    # create actuator for lower heating element in water tank
    leschedoverride_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(hpwh_bottom_element_sp, 'Schedule:Constant', 'Schedule Value')
    leschedoverride_actuator.setName("#{hpwh_name_ems_friendly}_LESchedOverride")

    # create actuator for upper heating element in water tank
    ueschedoverride_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(hpwh_top_element_sp, 'Schedule:Constant', 'Schedule Value')
    ueschedoverride_actuator.setName("#{hpwh_name_ems_friendly}_UESchedOverride")

    # create sensor for heat pump compressor
    t_set_sensor = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')
    t_set_sensor.setName("#{hpwh_name_ems_friendly}_T_set")
    t_set_sensor.setKeyName(swh_temp_sch.name.to_s)

    # define control configuration
    t_offset = 9.0 # deg-C

    # get tank specifications
    upper_element_db = tank.heater1DeadbandTemperatureDifference

    # define control logic
    hpwh_ctrl_program = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
    hpwh_ctrl_program.setName("#{hpwh_name_ems_friendly}_Control")
    hpwh_ctrl_program.addLine("SET #{hpwhschedoverride_actuator.name} = #{t_set_sensor.name}")
    # lockout hp when ambient temperature is either too high or too low
    hpwh_ctrl_program.addLine("IF (#{amb_temp_sensor.name}<#{hpwh_op_min_temp_c}) || (#{amb_temp_sensor.name}>#{hpwh_op_max_temp_c})")
    hpwh_ctrl_program.addLine("SET #{ueschedoverride_actuator.name} = #{t_set_sensor.name}")
    hpwh_ctrl_program.addLine("SET #{leschedoverride_actuator.name} = #{t_set_sensor.name}")
    hpwh_ctrl_program.addLine('ELSE')
    # upper element setpoint temperature
    hpwh_ctrl_program.addLine("SET #{ueschedoverride_actuator.name} = #{t_set_sensor.name} - #{t_offset}")
    # upper element cut-in temperature
    hpwh_ctrl_program.addLine("SET #{ueschedoverride_actuator.name}_cut_in = #{ueschedoverride_actuator.name} - #{upper_element_db}")
    # lower element disabled
    hpwh_ctrl_program.addLine("SET #{leschedoverride_actuator.name} = 0")
    # lower element disabled
    hpwh_ctrl_program.addLine("SET #{leschedoverride_actuator.name}_cut_in = 0")
    hpwh_ctrl_program.addLine('ENDIF')

    # create a program calling manager
    program_calling_manager = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
    program_calling_manager.setName("#{hpwh_name_ems_friendly}_ProgramManager")
    program_calling_manager.setCallingPoint('InsideHVACSystemIterationLoop')
    program_calling_manager.addProgram(hpwh_ctrl_program)
  end

  return hpwh
end
model_add_high_temp_radiant(model, thermal_zones, heating_type: 'NaturalGas', combustion_efficiency: 0.8, control_type: 'MeanAirTemperature') click to toggle source

Creates a high temp radiant heater for each zone and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param heating_type [String] valid choices are Gas, Electric @param combustion_efficiency [Double] combustion efficiency as decimal @param control_type [String] control type @return [Array<OpenStudio::Model::ZoneHVACHighTemperatureRadiant>] an array of the resulting radiant heaters.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 4344
def model_add_high_temp_radiant(model,
                                thermal_zones,
                                heating_type: 'NaturalGas',
                                combustion_efficiency: 0.8,
                                control_type: 'MeanAirTemperature')

  # make a high temp radiant heater for each zone
  radiant_heaters = []
  thermal_zones.each do |zone|
    high_temp_radiant = OpenStudio::Model::ZoneHVACHighTemperatureRadiant.new(model)
    high_temp_radiant.setName("#{zone.name} High Temp Radiant")

    if heating_type.nil? || heating_type == 'NaturalGas' || heating_type == 'Gas'
      high_temp_radiant.setFuelType('NaturalGas')
    else
      high_temp_radiant.setFuelType(heating_type)
    end

    if combustion_efficiency.nil?
      if heating_type == 'NaturalGas' || heating_type == 'Gas'
        high_temp_radiant.setCombustionEfficiency(0.8)
      elsif heating_type == 'Electric'
        high_temp_radiant.setCombustionEfficiency(1.0)
      end
    else
      high_temp_radiant.setCombustionEfficiency(combustion_efficiency)
    end

    # set heating setpoint schedule
    tstat = zone.thermostatSetpointDualSetpoint.get
    if tstat.heatingSetpointTemperatureSchedule.is_initialized
      htg_sch = tstat.heatingSetpointTemperatureSchedule.get
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "For #{zone.name}: Cannot find a heating setpoint schedule for this zone, cannot apply high temp radiant system.")
      return false
    end

    # set defaults
    high_temp_radiant.setHeatingSetpointTemperatureSchedule(htg_sch)
    high_temp_radiant.setTemperatureControlType(control_type)
    high_temp_radiant.setFractionofInputConvertedtoRadiantEnergy(0.8)
    high_temp_radiant.setHeatingThrottlingRange(2)
    high_temp_radiant.addToThermalZone(zone)
    radiant_heaters << high_temp_radiant
  end

  return radiant_heaters
end
model_add_hp_loop(model, heating_fuel: 'NaturalGas', cooling_fuel: 'Electricity', cooling_type: 'EvaporativeFluidCooler', system_name: 'Heat Pump Loop', sup_wtr_high_temp: 87.0, sup_wtr_low_temp: 67.0, dsgn_sup_wtr_temp: 102.2, dsgn_sup_wtr_temp_delt: 19.8) click to toggle source

Creates a heat pump loop which has a boiler and fluid cooler for supplemental heating/cooling and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param heating_fuel [String] @param cooling_fuel [String] cooling fuel. Valid options are: Electricity, DistrictCooling @param cooling_type [String] cooling type if not DistrictCooling.

Valid options are:
CoolingTower, CoolingTowerSingleSpeed, CoolingTowerTwoSpeed, CoolingTowerVariableSpeed,
FluidCooler, FluidCoolerSingleSpeed, FluidCoolerTwoSpeed,
EvaporativeFluidCooler, EvaporativeFluidCoolerSingleSpeed, EvaporativeFluidCoolerTwoSpeed

@param system_name [String] the name of the system, or nil in which case it will be defaulted @param sup_wtr_high_temp [Double] target supply water temperature to enable cooling in degrees Fahrenheit, default 65.0F @param sup_wtr_low_temp [Double] target supply water temperature to enable heating in degrees Fahrenheit, default 41.0F @param dsgn_sup_wtr_temp [Double] design supply water temperature in degrees Fahrenheit, default 102.2F @param dsgn_sup_wtr_temp_delt [Double] design supply-return water temperature difference in degrees Rankine, default 19.8R @return [OpenStudio::Model::PlantLoop] the resulting plant loop @todo replace cooling tower with fluid cooler after fixing sizing inputs

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 741
def model_add_hp_loop(model,
                      heating_fuel: 'NaturalGas',
                      cooling_fuel: 'Electricity',
                      cooling_type: 'EvaporativeFluidCooler',
                      system_name: 'Heat Pump Loop',
                      sup_wtr_high_temp: 87.0,
                      sup_wtr_low_temp: 67.0,
                      dsgn_sup_wtr_temp: 102.2,
                      dsgn_sup_wtr_temp_delt: 19.8)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', 'Adding heat pump loop.')

  # create heat pump loop
  heat_pump_water_loop = OpenStudio::Model::PlantLoop.new(model)
  heat_pump_water_loop.setLoadDistributionScheme('SequentialLoad')
  if system_name.nil?
    heat_pump_water_loop.setName('Heat Pump Loop')
  else
    heat_pump_water_loop.setName(system_name)
  end

  # hot water loop sizing and controls
  if sup_wtr_high_temp.nil?
    sup_wtr_high_temp = 87.0
    sup_wtr_high_temp_c = OpenStudio.convert(sup_wtr_high_temp, 'F', 'C').get
  else
    sup_wtr_high_temp_c = OpenStudio.convert(sup_wtr_high_temp, 'F', 'C').get
  end
  if sup_wtr_low_temp.nil?
    sup_wtr_low_temp = 67.0
    sup_wtr_low_temp_c = OpenStudio.convert(sup_wtr_low_temp, 'F', 'C').get
  else
    sup_wtr_low_temp_c = OpenStudio.convert(sup_wtr_low_temp, 'F', 'C').get
  end
  if dsgn_sup_wtr_temp.nil?
    dsgn_sup_wtr_temp_c = OpenStudio.convert(102.2, 'F', 'C').get
  else
    dsgn_sup_wtr_temp_c = OpenStudio.convert(dsgn_sup_wtr_temp, 'F', 'C').get
  end
  if dsgn_sup_wtr_temp_delt.nil?
    dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(19.8, 'R', 'K').get
  else
    dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(dsgn_sup_wtr_temp_delt, 'R', 'K').get
  end
  sizing_plant = heat_pump_water_loop.sizingPlant
  sizing_plant.setLoopType('Heating')
  heat_pump_water_loop.setMinimumLoopTemperature(10.0)
  heat_pump_water_loop.setMaximumLoopTemperature(35.0)
  sizing_plant.setDesignLoopExitTemperature(dsgn_sup_wtr_temp_c)
  sizing_plant.setLoopDesignTemperatureDifference(dsgn_sup_wtr_temp_delt_k)
  hp_high_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                     sup_wtr_high_temp_c,
                                                                                     name: "#{heat_pump_water_loop.name} High Temp - #{sup_wtr_high_temp.round(0)}F",
                                                                                     schedule_type_limit: 'Temperature')
  hp_low_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                    sup_wtr_low_temp_c,
                                                                                    name: "#{heat_pump_water_loop.name} Low Temp - #{sup_wtr_low_temp.round(0)}F",
                                                                                    schedule_type_limit: 'Temperature')
  hp_stpt_manager = OpenStudio::Model::SetpointManagerScheduledDualSetpoint.new(model)
  hp_stpt_manager.setName("#{heat_pump_water_loop.name} Scheduled Dual Setpoint")
  hp_stpt_manager.setHighSetpointSchedule(hp_high_temp_sch)
  hp_stpt_manager.setLowSetpointSchedule(hp_low_temp_sch)
  hp_stpt_manager.addToNode(heat_pump_water_loop.supplyOutletNode)

  # create pump
  hp_pump = OpenStudio::Model::PumpConstantSpeed.new(model)
  hp_pump.setName("#{heat_pump_water_loop.name} Pump")
  hp_pump.setRatedPumpHead(OpenStudio.convert(60.0, 'ftH_{2}O', 'Pa').get)
  hp_pump.setPumpControlType('Intermittent')
  hp_pump.addToNode(heat_pump_water_loop.supplyInletNode)

  # add setpoint manager schedule to cooling equipment outlet so correct plant operation scheme is generated
  cooling_equipment_stpt_manager = OpenStudio::Model::SetpointManagerScheduledDualSetpoint.new(model)
  cooling_equipment_stpt_manager.setHighSetpointSchedule(hp_high_temp_sch)
  cooling_equipment_stpt_manager.setLowSetpointSchedule(hp_low_temp_sch)

  # create cooling equipment and add to the loop
  case cooling_fuel
  when 'DistrictCooling'
    cooling_equipment = OpenStudio::Model::DistrictCooling.new(model)
    cooling_equipment.setName("#{heat_pump_water_loop.name} District Cooling")
    cooling_equipment.autosizeNominalCapacity
    heat_pump_water_loop.addSupplyBranchForComponent(cooling_equipment)
    cooling_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} District Cooling Scheduled Dual Setpoint")
  else
    case cooling_type
    when 'CoolingTower', 'CoolingTowerTwoSpeed'
      cooling_equipment = OpenStudio::Model::CoolingTowerTwoSpeed.new(model)
      cooling_equipment.setName("#{heat_pump_water_loop.name} CoolingTowerTwoSpeed")
      heat_pump_water_loop.addSupplyBranchForComponent(cooling_equipment)
      cooling_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} Cooling Tower Scheduled Dual Setpoint")
    when 'CoolingTowerSingleSpeed'
      cooling_equipment = OpenStudio::Model::CoolingTowerSingleSpeed.new(model)
      cooling_equipment.setName("#{heat_pump_water_loop.name} CoolingTowerSingleSpeed")
      heat_pump_water_loop.addSupplyBranchForComponent(cooling_equipment)
      cooling_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} Cooling Tower Scheduled Dual Setpoint")
    when 'CoolingTowerVariableSpeed'
      cooling_equipment = OpenStudio::Model::CoolingTowerVariableSpeed.new(model)
      cooling_equipment.setName("#{heat_pump_water_loop.name} CoolingTowerVariableSpeed")
      heat_pump_water_loop.addSupplyBranchForComponent(cooling_equipment)
      cooling_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} Cooling Tower Scheduled Dual Setpoint")
    when 'FluidCooler', 'FluidCoolerSingleSpeed'
      cooling_equipment = OpenStudio::Model::FluidCoolerSingleSpeed.new(model)
      cooling_equipment.setName("#{heat_pump_water_loop.name} FluidCoolerSingleSpeed")
      heat_pump_water_loop.addSupplyBranchForComponent(cooling_equipment)
      cooling_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} Fluid Cooler Scheduled Dual Setpoint")
      # Remove hard coded default values
      cooling_equipment.setPerformanceInputMethod('UFactorTimesAreaAndDesignWaterFlowRate')
      cooling_equipment.autosizeDesignWaterFlowRate
      cooling_equipment.autosizeDesignAirFlowRate
    when 'FluidCoolerTwoSpeed'
      cooling_equipment = OpenStudio::Model::FluidCoolerTwoSpeed.new(model)
      cooling_equipment.setName("#{heat_pump_water_loop.name} FluidCoolerTwoSpeed")
      heat_pump_water_loop.addSupplyBranchForComponent(cooling_equipment)
      cooling_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} Fluid Cooler Scheduled Dual Setpoint")
      # Remove hard coded default values
      cooling_equipment.setPerformanceInputMethod('UFactorTimesAreaAndDesignWaterFlowRate')
      cooling_equipment.autosizeDesignWaterFlowRate
      cooling_equipment.autosizeHighFanSpeedAirFlowRate
      cooling_equipment.autosizeLowFanSpeedAirFlowRate
    when 'EvaporativeFluidCooler', 'EvaporativeFluidCoolerSingleSpeed'
      cooling_equipment = OpenStudio::Model::EvaporativeFluidCoolerSingleSpeed.new(model)
      cooling_equipment.setName("#{heat_pump_water_loop.name} EvaporativeFluidCoolerSingleSpeed")
      cooling_equipment.setDesignSprayWaterFlowRate(0.002208) # Based on HighRiseApartment
      cooling_equipment.setPerformanceInputMethod('UFactorTimesAreaAndDesignWaterFlowRate')
      heat_pump_water_loop.addSupplyBranchForComponent(cooling_equipment)
      cooling_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} Fluid Cooler Scheduled Dual Setpoint")
    when 'EvaporativeFluidCoolerTwoSpeed'
      cooling_equipment = OpenStudio::Model::EvaporativeFluidCoolerTwoSpeed.new(model)
      cooling_equipment.setName("#{heat_pump_water_loop.name} EvaporativeFluidCoolerTwoSpeed")
      cooling_equipment.setDesignSprayWaterFlowRate(0.002208) # Based on HighRiseApartment
      cooling_equipment.setPerformanceInputMethod('UFactorTimesAreaAndDesignWaterFlowRate')
      heat_pump_water_loop.addSupplyBranchForComponent(cooling_equipment)
      cooling_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} Fluid Cooler Scheduled Dual Setpoint")
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Cooling fuel type #{cooling_type} is not a valid option, no cooling equipment will be added.")
      return false
    end
  end
  cooling_equipment_stpt_manager.addToNode(cooling_equipment.outletModelObject.get.to_Node.get)

  # add setpoint manager schedule to heating equipment outlet so correct plant operation scheme is generated
  heating_equipment_stpt_manager = OpenStudio::Model::SetpointManagerScheduledDualSetpoint.new(model)
  heating_equipment_stpt_manager.setHighSetpointSchedule(hp_high_temp_sch)
  heating_equipment_stpt_manager.setLowSetpointSchedule(hp_low_temp_sch)

  # switch statement to handle district heating name change
  if model.version < OpenStudio::VersionString.new('3.7.0')
    if heating_fuel == 'DistrictHeatingWater' || heating_fuel == 'DistrictHeatingSteam'
      heating_fuel = 'DistrictHeating'
    end
  else
    heating_fuel = 'DistrictHeatingWater' if heating_fuel == 'DistrictHeating'
  end

  # create heating equipment and add to the loop
  case heating_fuel
  when 'DistrictHeating'
    heating_equipment = OpenStudio::Model::DistrictHeating.new(model)
    heating_equipment.setName("#{heat_pump_water_loop.name} District Heating")
    heating_equipment.autosizeNominalCapacity
    heat_pump_water_loop.addSupplyBranchForComponent(heating_equipment)
    heating_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} District Heating Scheduled Dual Setpoint")
  when 'DistrictHeatingWater'
    heating_equipment = OpenStudio::Model::DistrictHeatingWater.new(model)
    heating_equipment.setName("#{heat_pump_water_loop.name} District Heating")
    heating_equipment.autosizeNominalCapacity
    heat_pump_water_loop.addSupplyBranchForComponent(heating_equipment)
    heating_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} District Heating Scheduled Dual Setpoint")
  when 'DistrictHeatingSteam'
    heating_equipment = OpenStudio::Model::DistrictHeatingSteam.new(model)
    heating_equipment.setName("#{heat_pump_water_loop.name} District Heating")
    heating_equipment.autosizeNominalCapacity
    heat_pump_water_loop.addSupplyBranchForComponent(heating_equipment)
    heating_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} District Heating Scheduled Dual Setpoint")
  when 'AirSourceHeatPump', 'ASHP'
    heating_equipment = create_central_air_source_heat_pump(model, heat_pump_water_loop)
    heating_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} ASHP Scheduled Dual Setpoint")
  when 'Electricity', 'Gas', 'NaturalGas', 'Propane', 'PropaneGas', 'FuelOilNo1', 'FuelOilNo2'
    heating_equipment = create_boiler_hot_water(model,
                                                hot_water_loop: heat_pump_water_loop,
                                                name: "#{heat_pump_water_loop.name} Supplemental Boiler",
                                                fuel_type: heating_fuel,
                                                flow_mode: 'ConstantFlow',
                                                lvg_temp_dsgn_f: 86.0, # 30.0 degrees Celsius
                                                min_plr: 0.0,
                                                max_plr: 1.2,
                                                opt_plr: 1.0)
    heating_equipment_stpt_manager.setName("#{heat_pump_water_loop.name} Boiler Scheduled Dual Setpoint")
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Boiler fuel type #{heating_fuel} is not valid, no heating equipment will be added.")
    return false
  end
  heating_equipment_stpt_manager.addToNode(heating_equipment.outletModelObject.get.to_Node.get)

  # add heat pump water loop pipes
  supply_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_bypass_pipe.setName("#{heat_pump_water_loop.name} Supply Bypass")
  heat_pump_water_loop.addSupplyBranchForComponent(supply_bypass_pipe)

  demand_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_bypass_pipe.setName("#{heat_pump_water_loop.name} Demand Bypass")
  heat_pump_water_loop.addDemandBranchForComponent(demand_bypass_pipe)

  supply_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_outlet_pipe.setName("#{heat_pump_water_loop.name} Supply Outlet")
  supply_outlet_pipe.addToNode(heat_pump_water_loop.supplyOutletNode)

  demand_inlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_inlet_pipe.setName("#{heat_pump_water_loop.name} Demand Inlet")
  demand_inlet_pipe.addToNode(heat_pump_water_loop.demandInletNode)

  demand_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_outlet_pipe.setName("#{heat_pump_water_loop.name} Demand Outlet")
  demand_outlet_pipe.addToNode(heat_pump_water_loop.demandOutletNode)

  return heat_pump_water_loop
end
model_add_hvac(model, building_type, climate_zone, prototype_input) click to toggle source

Adds the prototype HVAC system to the model

@param model [OpenStudio::Model::Model] OpenStudio model object @param building_type [String] the building type @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param prototype_input [Hash] hash of prototype inputs @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.hvac.rb, line 9
def model_add_hvac(model, building_type, climate_zone, prototype_input)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Started Adding HVAC')

  # Get the list of HVAC systems, as defined for each building in the Prototype.building_name files

  # Add each HVAC system
  @system_to_space_map.each do |system|
    thermal_zones = model_get_zones_from_spaces_on_system(model, system)
    return_plenum = model_get_return_plenum_from_system(model, system)

    # Add the HVAC systems
    case system['type']
    when 'VAV'
      # Retrieve the existing hot water loop or add a new one if necessary.
      hot_water_loop = nil
      hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                         model.getPlantLoopByName('Hot Water Loop').get
                       else
                         model_add_hw_loop(model,
                                           'NaturalGas',
                                           dsgn_sup_wtr_temp: system['hot_water_design_supply_water_temperature'],
                                           boiler_lvg_temp_dsgn: system['boiler_leaving_temperature_design'],
                                           boiler_out_temp_lmt: system['boiler_outlet_temperature_limit'],
                                           boiler_sizing_factor: system['boiler_sizing_factor'])
                       end

      # Retrieve the existing chilled water loop or add a new one if necessary.
      chilled_water_loop = nil
      if model.getPlantLoopByName('Chilled Water Loop').is_initialized
        chilled_water_loop = model.getPlantLoopByName('Chilled Water Loop').get
      else
        # get num_chillers from prototype_input
        num_chillers = prototype_input['chw_number_chillers']
        if num_chillers.nil? || num_chillers.to_i < 1
          num_chillers = 1
        end
        # update num_chillers if specified in @system_to_space_map
        if !system['chw_number_chillers'].nil? && system['chw_number_chillers'].to_i > 0
          num_chillers = system['chw_number_chillers']
        end

        # get number_cooling_towers if specified in @system_to_space_map
        number_cooling_towers = 1
        if !system['number_cooling_towers'].nil? && system['number_cooling_towers'].to_i > 0
          number_cooling_towers = system['number_cooling_towers']
        end

        condenser_water_loop = nil
        if system['chiller_cooling_type'] == 'WaterCooled'
          condenser_water_loop = model_add_cw_loop(model,
                                                   cooling_tower_type: 'Open Cooling Tower',
                                                   cooling_tower_fan_type: 'Centrifugal',
                                                   cooling_tower_capacity_control: 'Variable Speed Fan',
                                                   number_of_cells_per_tower: 2,
                                                   number_cooling_towers: number_cooling_towers.to_i)
        end
        chilled_water_loop = model_add_chw_loop(model,
                                                cooling_fuel: 'Electricity',
                                                dsgn_sup_wtr_temp: system['chilled_water_design_supply_water_temperature'],
                                                dsgn_sup_wtr_temp_delt: system['chilled_water_design_supply_water_temperature_delta'],
                                                chw_pumping_type: system['chw_pumping_type'],
                                                chiller_cooling_type: system['chiller_cooling_type'],
                                                chiller_condenser_type: system['chiller_condenser_type'],
                                                chiller_compressor_type: system['chiller_compressor_type'],
                                                condenser_water_loop: condenser_water_loop,
                                                num_chillers: num_chillers.to_i)
      end

      # Add the VAV
      model_add_vav_reheat(model,
                           thermal_zones,
                           system_name: system['name'],
                           return_plenum: return_plenum,
                           reheat_type: 'Water',
                           hot_water_loop: hot_water_loop,
                           chilled_water_loop: chilled_water_loop,
                           hvac_op_sch: system['operation_schedule'],
                           oa_damper_sch: system['oa_damper_schedule'],
                           fan_efficiency: 0.62,
                           fan_motor_efficiency: 0.9,
                           fan_pressure_rise: 4.0,
                           min_sys_airflow_ratio: system['min_sys_airflow_ratio'],
                           vav_sizing_option: system['vav_sizing_option'])

    when 'CAV'
      # Retrieve the existing hot water loop or add a new one if necessary.
      hot_water_loop = nil
      hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                         model.getPlantLoopByName('Hot Water Loop').get
                       else
                         model_add_hw_loop(model, 'NaturalGas')
                       end

      chilled_water_loop = nil
      if model.getPlantLoopByName('Chilled Water Loop').is_initialized
        chilled_water_loop = model.getPlantLoopByName('Chilled Water Loop').get
      elsif building_type == 'Hospital'
        condenser_water_loop = nil
        condenser_water_loop = model_add_cw_loop(model, cooling_tower_capacity_control: 'Variable Speed Fan') if system['chiller_cooling_type'] == 'WaterCooled'
        chilled_water_loop = model_add_chw_loop(model,
                                                cooling_fuel: 'Electricity',
                                                dsgn_sup_wtr_temp: system['chilled_water_design_supply_water_temperature'],
                                                dsgn_sup_wtr_temp_delt: system['chilled_water_design_supply_water_temperature_delta'],
                                                chw_pumping_type: system['chw_pumping_type'],
                                                chiller_cooling_type: system['chiller_cooling_type'],
                                                chiller_condenser_type: system['chiller_condenser_type'],
                                                chiller_compressor_type: system['chiller_compressor_type'],
                                                condenser_water_loop: condenser_water_loop)
      end

      # Add the CAV
      model_add_cav(model,
                    thermal_zones,
                    system_name: system['name'],
                    hot_water_loop: hot_water_loop,
                    chilled_water_loop: chilled_water_loop,
                    hvac_op_sch: system['operation_schedule'],
                    oa_damper_sch: system['oa_damper_schedule'],
                    fan_efficiency: 0.62,
                    fan_motor_efficiency: 0.9,
                    fan_pressure_rise: 4.0)

    when 'PSZ-AC'
      # Special logic to make unitary heat pumps all blow-through
      fan_position = 'DrawThrough'
      if system['heating_type'] == 'Single Speed Heat Pump' ||
         system['heating_type'] == 'Water To Air Heat Pump'
        fan_position = 'BlowThrough'
      end

      # Special logic to make a heat pump loop if necessary
      heat_pump_loop = nil
      if system['heating_type'] == 'Water To Air Heat Pump'
        # @note code_sections [90.1-2016_6.5.5.2.1]
        # change highrise apartment heat rejection fan (< 5hp) from single speed to two speed evaporative fluid cooler
        # @todo this is temporary fix, it should be applied to all heat rejection devices smaller than 5hp.
        if system['heat_pump_loop_cooling_type'].nil?
          hp_loop_cooling_type = 'EvaporativeFluidCooler'
        else
          hp_loop_cooling_type = system['heat_pump_loop_cooling_type']
        end
        heat_pump_loop = model_get_or_add_heat_pump_loop(model, 'NaturalGas', 'Electricity', heat_pump_loop_cooling_type: hp_loop_cooling_type)
      end
      # if water to air heat pump is using existing chilled water loop and hot water loop as source
      # get existing loops, and assign heat_pump_cool_loop = chilled_water_loop, heat_pump_heat_loop = hot_water_loop
      # applicable to super tall building elevator machine room that is in the middle of the building

      model_add_psz_ac(model,
                       thermal_zones,
                       system_name: system['name'],
                       cooling_type: system['cooling_type'],
                       chilled_water_loop: heat_pump_loop,
                       heating_type: system['heating_type'],
                       supplemental_heating_type: system['supplemental_heating_type'],
                       hot_water_loop: heat_pump_loop,
                       fan_location: fan_position,
                       fan_type: system['fan_type'],
                       hvac_op_sch: system['operation_schedule'],
                       oa_damper_sch: system['oa_damper_schedule'])

    when 'PVAV'
      # Retrieve the existing hot water loop or add a new one if necessary.
      hot_water_loop = nil
      hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                         model.getPlantLoopByName('Hot Water Loop').get
                       elsif building_type == 'MediumOffice'
                         nil
                       elsif building_type == 'MediumOfficeDetailed'
                         nil
                       else
                         model_add_hw_loop(model,
                                           'NaturalGas',
                                           pump_spd_ctrl: system['hotwater_pump_speed_control'])
                       end
      case system['electric_reheat']
      when true
        electric_reheat = true
      else
        electric_reheat = false
      end
      model_add_pvav(model,
                     thermal_zones,
                     system_name: system['name'],
                     hvac_op_sch: system['operation_schedule'],
                     oa_damper_sch: system['oa_damper_schedule'],
                     electric_reheat: electric_reheat,
                     hot_water_loop: hot_water_loop,
                     return_plenum: return_plenum)

    when 'DOAS Cold Supply'
      # Retrieve the existing hot water loop or add a new one if necessary.
      hot_water_loop = nil
      hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                         model.getPlantLoopByName('Hot Water Loop').get
                       else
                         model_add_hw_loop(model, 'NaturalGas')
                       end

      # Retrieve the existing chilled water loop or add a new one if necessary.
      chilled_water_loop = nil
      if model.getPlantLoopByName('Chilled Water Loop').is_initialized
        chilled_water_loop = model.getPlantLoopByName('Chilled Water Loop').get
      else
        num_chillers = 1
        if !system['num_chillers'].nil? && system['num_chillers'].to_i > 0
          num_chillers = system['num_chillers'].to_i
        end
        condenser_water_loop = nil
        if system['chiller_cooling_type'] == 'WaterCooled'
          condenser_water_loop = model_add_cw_loop(model,
                                                   cooling_tower_type: 'Open Cooling Tower',
                                                   cooling_tower_fan_type: 'Centrifugal',
                                                   cooling_tower_capacity_control: 'Fan Cycling',
                                                   number_of_cells_per_tower: 2,
                                                   number_cooling_towers: num_chillers)
        end
        chilled_water_loop = model_add_chw_loop(model,
                                                cooling_fuel: 'Electricity',
                                                dsgn_sup_wtr_temp: system['chilled_water_design_supply_water_temperature'],
                                                dsgn_sup_wtr_temp_delt: system['chilled_water_design_supply_water_temperature_delta'],
                                                chw_pumping_type: system['chw_pumping_type'],
                                                chiller_cooling_type: system['chiller_cooling_type'],
                                                chiller_condenser_type: system['chiller_condenser_type'],
                                                chiller_compressor_type: system['chiller_compressor_type'],
                                                num_chillers: num_chillers,
                                                condenser_water_loop: condenser_water_loop)
      end
      model_add_doas_cold_supply(model,
                                 thermal_zones,
                                 system_name: system['name'],
                                 hot_water_loop: hot_water_loop,
                                 chilled_water_loop: chilled_water_loop,
                                 hvac_op_sch: system['operation_schedule'],
                                 min_oa_sch: system['oa_damper_schedule'],
                                 min_frac_oa_sch: system['minimum_fraction_of_outdoor_air_schedule'],
                                 fan_maximum_flow_rate: system['fan_maximum_flow_rate'],
                                 econo_ctrl_mthd: system['economizer_control_method'],
                                 doas_control_strategy: system['doas_control_strategy'],
                                 clg_dsgn_sup_air_temp: system['cooling_design_supply_air_temperature'],
                                 htg_dsgn_sup_air_temp: system['heating_design_supply_air_temperature'])

      model_add_four_pipe_fan_coil(model,
                                   thermal_zones,
                                   chilled_water_loop,
                                   hot_water_loop: hot_water_loop,
                                   ventilation: false)

    when 'Packaged DOAS'
      # Retrieve the existing hot water loop or add a new one if necessary.
      hot_water_loop = nil
      hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                         model.getPlantLoopByName('Hot Water Loop').get
                       else
                         model_add_hw_loop(model, 'NaturalGas')
                       end
      # check inputs
      doas_type = system['doas_type'] || 'DOASCV'
      econo_ctrl_mthd = system['economizer_control_method'] || 'NoEconomizer'
      doas_control_strategy = system['doas_control_strategy'] || 'NeutralSupplyAir'
      clg_dsgn_sup_air_temp = system['cooling_design_supply_air_temperature'] || 60.0
      htg_dsgn_sup_air_temp = system['heating_design_supply_air_temperature'] || 70.0

      # for boolean input, this makes sure we get the correct input translation
      if system['include_exhaust_fan'].nil? || true?(system['include_exhaust_fan'])
        include_exhaust_fan = true
      else
        include_exhaust_fan = false
      end
      if true?(system['demand_control_ventilation'])
        demand_control_ventilation = true
      else
        demand_control_ventilation = false
      end

      model_add_doas(model,
                     thermal_zones,
                     system_name: system['name'],
                     doas_type: doas_type,
                     hot_water_loop: hot_water_loop,
                     chilled_water_loop: nil,
                     hvac_op_sch: system['operation_schedule'],
                     min_oa_sch: system['oa_damper_schedule'],
                     min_frac_oa_sch: system['minimum_fraction_of_outdoor_air_schedule'],
                     fan_maximum_flow_rate: system['fan_maximum_flow_rate'],
                     econo_ctrl_mthd: econo_ctrl_mthd,
                     include_exhaust_fan: include_exhaust_fan,
                     demand_control_ventilation: demand_control_ventilation,
                     doas_control_strategy: doas_control_strategy,
                     clg_dsgn_sup_air_temp: clg_dsgn_sup_air_temp,
                     htg_dsgn_sup_air_temp: htg_dsgn_sup_air_temp)

    when 'DC' # Data Center in Large Office building
      # Retrieve the existing hot water loop or add a new one if necessary.
      hot_water_loop = model_get_or_add_hot_water_loop(model, 'NaturalGas')

      # Set heat pump loop cooling type to CoolingTowerTwoSpeed if not specified in system hash
      heat_pump_loop_cooling_type = system['heat_pump_loop_cooling_type'].nil? ? 'CoolingTowerTwoSpeed' : system['heat_pump_loop_cooling_type']

      heat_pump_loop = model_get_or_add_heat_pump_loop(model, 'NaturalGas', 'Electricity',
                                                       heat_pump_loop_cooling_type: heat_pump_loop_cooling_type)
      model_add_data_center_hvac(model,
                                 thermal_zones,
                                 hot_water_loop,
                                 heat_pump_loop,
                                 hvac_op_sch: system['flow_fraction_schedule'],
                                 oa_damper_sch: system['flow_fraction_schedule'],
                                 main_data_center: system['main_data_center'])

    when 'CRAC' # Small Data Center
      model_add_crac(model,
                     thermal_zones,
                     climate_zone,
                     system_name: system['name'],
                     hvac_op_sch: system['CRAC_operation_schedule'],
                     oa_damper_sch: system['CRAC_oa_damper_schedule'],
                     fan_location: 'DrawThrough',
                     fan_type: system['CRAC_fan_type'],
                     cooling_type: system['CRAC_cooling_type'],
                     supply_temp_sch: nil)

    when 'CRAH' # Large Data Center (standalone)
      # Retrieve the existing chilled water loop or add a new one if necessary.
      chilled_water_loop = nil
      if model.getPlantLoopByName('Chilled Water Loop').is_initialized
        chilled_water_loop = model.getPlantLoopByName('Chilled Water Loop').get
      else
        condenser_water_loop = nil
        if system['chiller_cooling_type'] == 'WaterCooled'
          condenser_water_loop = model_add_cw_loop(model,
                                                   cooling_tower_type: 'Open Cooling Tower',
                                                   cooling_tower_fan_type: 'Centrifugal',
                                                   cooling_tower_capacity_control: 'Fan Cycling',
                                                   number_of_cells_per_tower: 2,
                                                   number_cooling_towers: 1)
        end
        chilled_water_loop = model_add_chw_loop(model,
                                                cooling_fuel: 'Electricity',
                                                dsgn_sup_wtr_temp: system['chilled_water_design_supply_water_temperature'],
                                                dsgn_sup_wtr_temp_delt: system['chilled_water_design_supply_water_temperature_delta'],
                                                chw_pumping_type: system['chw_pumping_type'],
                                                chiller_cooling_type: system['chiller_cooling_type'],
                                                chiller_condenser_type: system['chiller_condenser_type'],
                                                chiller_compressor_type: system['chiller_compressor_type'],
                                                condenser_water_loop: condenser_water_loop,
                                                waterside_economizer: system['waterside_economizer'])
      end
      model_add_crah(model,
                     thermal_zones,
                     system_name: system['name'],
                     chilled_water_loop: chilled_water_loop,
                     hvac_op_sch: system['operation_schedule'],
                     oa_damper_sch: system['oa_damper_schedule'],
                     return_plenum: nil,
                     supply_temp_sch: nil)

    when 'SAC'
      model_add_split_ac(model,
                         thermal_zones,
                         cooling_type: system['cooling_type'],
                         heating_type: system['heating_type'],
                         supplemental_heating_type: system['supplemental_heating_type'],
                         fan_type: system['fan_type'],
                         hvac_op_sch: system['operation_schedule'],
                         oa_damper_sch: system['oa_damper_schedule'],
                         econ_max_oa_frac_sch: system['econ_max_oa_frac_sch'])

    when 'UnitHeater'
      model_add_unitheater(model,
                           thermal_zones,
                           hvac_op_sch: system['operation_schedule'],
                           fan_control_type: system['fan_type'],
                           fan_pressure_rise: system['fan_static_pressure'],
                           heating_type: system['heating_type'])

    when 'PTAC'
      model_add_ptac(model,
                     thermal_zones,
                     cooling_type: system['cooling_type'],
                     heating_type: system['heating_type'],
                     fan_type: system['fan_type'])

    when 'PTHP'
      model_add_pthp(model,
                     thermal_zones,
                     fan_type: system['fan_type'])

    when 'Exhaust Fan'
      model_add_exhaust_fan(model,
                            thermal_zones,
                            flow_rate: system['flow_rate'],
                            availability_sch_name: system['operation_schedule'],
                            flow_fraction_schedule_name: system['flow_fraction_schedule'],
                            balanced_exhaust_fraction_schedule_name: system['balanced_exhaust_fraction_schedule'])

    when 'Zone Ventilation'
      model_add_zone_ventilation(model,
                                 thermal_zones,
                                 ventilation_type: system['ventilation_type'],
                                 flow_rate: system['flow_rate'],
                                 availability_sch_name: system['operation_schedule'])

    when 'Refrigeration'
      model_add_refrigeration(model,
                              system['case_type'],
                              system['cooling_capacity_per_length'],
                              system['length'],
                              system['evaporator_fan_pwr_per_length'],
                              system['lighting_per_length'],
                              system['lighting_schedule'],
                              system['defrost_pwr_per_length'],
                              system['restocking_schedule'],
                              system['cop'],
                              system['cop_f_of_t_curve_name'],
                              system['condenser_fan_pwr'],
                              system['condenser_fan_pwr_curve_name'],
                              thermal_zones[0])

    # When multiple cases and walk-ins asssigned to a system
    when 'Refrigeration_system'
      model_add_refrigeration_system(model,
                                     system['compressor_type'],
                                     system['name'],
                                     system['cases'],
                                     system['walkins'],
                                     thermal_zones[0])

    when 'WSHP'
      condenser_loop = case system['heating_type']
                       when 'Gas'
                         model_get_or_add_heat_pump_loop(model,
                                                         system['heating_type'],
                                                         system['cooling_type'],
                                                         heat_pump_loop_cooling_type: 'CoolingTowerTwoSpeed')
                       else
                         model_get_or_add_ambient_water_loop(model)
                       end
      model_add_water_source_hp(model,
                                thermal_zones,
                                condenser_loop,
                                ventilation: true)

    when 'Fan Coil'
      case system['heating_type']
      when 'Gas', 'DistrictHeating', 'DistrictHeatingWater', 'DistrictHeatingSteam', 'Electricity'
        hot_water_loop = model_get_or_add_hot_water_loop(model, system['heating_type'])
      when nil
        hot_water_loop = nil
      end
      case system['cooling_type']
      when 'Electricity', 'DistrictCooling'
        chilled_water_loop = model_get_or_add_chilled_water_loop(model, system['cooling_type'], chilled_water_loop_cooling_type: 'AirCooled')
      when nil
        chilled_water_loop = nil
      end
      model_add_four_pipe_fan_coil(model,
                                   thermal_zones,
                                   chilled_water_loop,
                                   hot_water_loop: hot_water_loop,
                                   ventilation: true)

    when 'Baseboards'
      case system['heating_type']
      when 'Gas', 'DistrictHeating', 'DistrictHeatingWater', 'DistrictHeatingSteam'
        hot_water_loop = model_get_or_add_hot_water_loop(model, system['heating_type'])
      when 'Electricity'
        hot_water_loop = nil
      when nil
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Baseboards must have heating_type specified.')
      end
      model_add_baseboard(model,
                          thermal_zones,
                          hot_water_loop: hot_water_loop)

    when 'Unconditioned'
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'System type is Unconditioned.  No system will be added.')

    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "System type '#{system['type']}' is not recognized for system named '#{system['name']}'.  This system will not be added.")

    end
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Finished adding HVAC')

  return true
end
model_add_hvac_system(model, system_type, main_heat_fuel, zone_heat_fuel, cool_fuel, zones, hot_water_loop_type: 'HighTemperature', chilled_water_loop_cooling_type: 'WaterCooled', heat_pump_loop_cooling_type: 'EvaporativeFluidCooler', air_loop_heating_type: 'Water', air_loop_cooling_type: 'Water', zone_equipment_ventilation: true, fan_coil_capacity_control_method: 'CyclingFan') click to toggle source

Add the specified system type to the specified zones based on the specified template. For multi-zone system types, add one system per story.

@param model [OpenStudio::Model::Model] OpenStudio model object @param system_type [String] The system type @param main_heat_fuel [String] Main heating fuel used for air loops and plant loops @param zone_heat_fuel [String] Zone heating fuel for zone hvac equipment and terminal units @param cool_fuel [String] Cooling fuel used for air loops, plant loops, and zone equipment @param zones [Array<OpenStudio::Model::ThermalZone>] array of thermal zones served by the system @param hot_water_loop_type [String] Archetype for hot water loops

HighTemperature (180F supply) (default) or LowTemperature (120F supply)
only used if HVAC system has a hot water loop

@param chilled_water_loop_cooling_type [String] Archetype for chilled water loops, AirCooled or WaterCooled

only used if HVAC system has a chilled water loop and cool_fuel is Electricity

@param heat_pump_loop_cooling_type [String] the type of cooling equipment for heat pump loops if not DistrictCooling.

Valid options are:
CoolingTower, CoolingTowerSingleSpeed, CoolingTowerTwoSpeed, CoolingTowerVariableSpeed,
FluidCooler, FluidCoolerSingleSpeed, FluidCoolerTwoSpeed,
EvaporativeFluidCooler, EvaporativeFluidCoolerSingleSpeed, EvaporativeFluidCoolerTwoSpeed

@param air_loop_heating_type [String] type of heating coil serving main air loop, options are Gas, DX, or Water @param air_loop_cooling_type [String] type of cooling coil serving main air loop, options are DX or Water @param zone_equipment_ventilation [Boolean] toggle whether to include outdoor air ventilation on zone equipment

including as fan coil units, VRF terminals, or water source heat pumps.

@param fan_coil_capacity_control_method [String] Only applicable to Fan Coil system type.

Capacity control method for the fan coil. Options are ConstantFanVariableFlow, CyclingFan, VariableFanVariableFlow,
and VariableFanConstantFlow.  If VariableFan, the fan will be VariableVolume.

@return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6852
def model_add_hvac_system(model,
                          system_type,
                          main_heat_fuel,
                          zone_heat_fuel,
                          cool_fuel,
                          zones,
                          hot_water_loop_type: 'HighTemperature',
                          chilled_water_loop_cooling_type: 'WaterCooled',
                          heat_pump_loop_cooling_type: 'EvaporativeFluidCooler',
                          air_loop_heating_type: 'Water',
                          air_loop_cooling_type: 'Water',
                          zone_equipment_ventilation: true,
                          fan_coil_capacity_control_method: 'CyclingFan')

  # enforce defaults if fields are nil
  hot_water_loop_type = 'HighTemperature' if hot_water_loop_type.nil?
  chilled_water_loop_cooling_type = 'WaterCooled' if chilled_water_loop_cooling_type.nil?
  heat_pump_loop_cooling_type = 'EvaporativeFluidCooler' if heat_pump_loop_cooling_type.nil?
  air_loop_heating_type = 'Water' if air_loop_heating_type.nil?
  air_loop_cooling_type = 'Water' if air_loop_cooling_type.nil?
  zone_equipment_ventilation = true if zone_equipment_ventilation.nil?
  fan_coil_capacity_control_method = 'CyclingFan' if fan_coil_capacity_control_method.nil?

  # don't do anything if there are no zones
  return true if zones.empty?

  case system_type
  when 'PTAC'
    case main_heat_fuel
    when 'NaturalGas', 'DistrictHeating', 'DistrictHeatingWater', 'DistrictHeatingSteam'
      heating_type = 'Water'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: hot_water_loop_type)
    when 'AirSourceHeatPump'
      heating_type = 'Water'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: 'LowTemperature')
    when 'Electricity'
      heating_type = main_heat_fuel
      hot_water_loop = nil
    else
      heating_type = zone_heat_fuel
      hot_water_loop = nil
    end

    model_add_ptac(model,
                   zones,
                   cooling_type: 'Single Speed DX AC',
                   heating_type: heating_type,
                   hot_water_loop: hot_water_loop,
                   fan_type: 'Cycling',
                   ventilation: zone_equipment_ventilation)

  when 'PTHP'
    model_add_pthp(model,
                   zones,
                   fan_type: 'Cycling',
                   ventilation: zone_equipment_ventilation)

  when 'PSZ-AC'
    case main_heat_fuel
    when 'NaturalGas', 'Gas'
      heating_type = main_heat_fuel
      supplemental_heating_type = 'Electricity'
      if air_loop_heating_type == 'Water'
        hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                         hot_water_loop_type: hot_water_loop_type)
        heating_type = 'Water'
      else
        hot_water_loop = nil
      end
    when 'DistrictHeating', 'DistrictHeatingWater', 'DistrictHeatingSteam'
      heating_type = 'Water'
      supplemental_heating_type = 'Electricity'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: hot_water_loop_type)
    when 'AirSourceHeatPump', 'ASHP'
      heating_type = 'Water'
      supplemental_heating_type = 'Electricity'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: 'LowTemperature')
    when 'Electricity'
      heating_type = main_heat_fuel
      supplemental_heating_type = 'Electricity'
    else
      heating_type = zone_heat_fuel
      supplemental_heating_type = nil
      hot_water_loop = nil
    end

    case cool_fuel
    when 'DistrictCooling'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel)
      cooling_type = 'Water'
    else
      chilled_water_loop = nil
      cooling_type = 'Single Speed DX AC'
    end

    model_add_psz_ac(model,
                     zones,
                     cooling_type: cooling_type,
                     chilled_water_loop: chilled_water_loop,
                     hot_water_loop: hot_water_loop,
                     heating_type: heating_type,
                     supplemental_heating_type: supplemental_heating_type,
                     fan_location: 'DrawThrough',
                     fan_type: 'ConstantVolume')

  when 'PSZ-HP'
    model_add_psz_ac(model,
                     zones,
                     system_name: 'PSZ-HP',
                     cooling_type: 'Single Speed Heat Pump',
                     heating_type: 'Single Speed Heat Pump',
                     supplemental_heating_type: 'Electricity',
                     fan_location: 'DrawThrough',
                     fan_type: 'ConstantVolume')

  when 'PSZ-VAV'
    if main_heat_fuel.nil?
      supplemental_heating_type = nil
    else
      supplemental_heating_type = 'Electricity'
    end
    model_add_psz_vav(model,
                      zones,
                      system_name: 'PSZ-VAV',
                      heating_type: main_heat_fuel,
                      supplemental_heating_type: supplemental_heating_type,
                      hvac_op_sch: nil,
                      oa_damper_sch: nil)

  when 'VRF'
    model_add_vrf(model,
                  zones,
                  ventilation: zone_equipment_ventilation)

  when 'Fan Coil'
    case main_heat_fuel
    when 'NaturalGas', 'DistrictHeating', 'DistrictHeatingWater', 'DistrictHeatingSteam', 'Electricity'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: hot_water_loop_type)
    when 'AirSourceHeatPump'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: 'LowTemperature')
    else
      hot_water_loop = nil
    end

    case cool_fuel
    when 'Electricity', 'DistrictCooling'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                               chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    else
      chilled_water_loop = nil
    end

    model_add_four_pipe_fan_coil(model,
                                 zones,
                                 chilled_water_loop,
                                 hot_water_loop: hot_water_loop,
                                 ventilation: zone_equipment_ventilation,
                                 capacity_control_method: fan_coil_capacity_control_method)

  when 'Radiant Slab'
    case main_heat_fuel
    when 'NaturalGas', 'DistrictHeating', 'DistrictHeatingWater', 'DistrictHeatingSteam', 'Electricity'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: hot_water_loop_type)
    when 'AirSourceHeatPump'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: 'LowTemperature')
    else
      hot_water_loop = nil
    end

    case cool_fuel
    when 'Electricity', 'DistrictCooling'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                               chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    else
      chilled_water_loop = nil
    end

    model_add_low_temp_radiant(model,
                               zones,
                               hot_water_loop,
                               chilled_water_loop)

  when 'Baseboards'
    case main_heat_fuel
    when 'NaturalGas', 'DistrictHeating', 'DistrictHeatingWater', 'DistrictHeatingSteam'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: hot_water_loop_type)
    when 'AirSourceHeatPump'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: 'LowTemperature')
    when 'Electricity'
      hot_water_loop = nil
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Baseboards must have heating_type specified.')
      return false
    end
    model_add_baseboard(model,
                        zones,
                        hot_water_loop: hot_water_loop)

  when 'Unit Heaters'
    model_add_unitheater(model,
                         zones,
                         hvac_op_sch: nil,
                         fan_control_type: 'ConstantVolume',
                         fan_pressure_rise: 0.2,
                         heating_type: main_heat_fuel)

  when 'High Temp Radiant'
    model_add_high_temp_radiant(model,
                                zones,
                                heating_type: main_heat_fuel,
                                combustion_efficiency: 0.8)

  when 'Window AC'
    model_add_window_ac(model,
                        zones)

  when 'Residential AC'
    model_add_furnace_central_ac(model,
                                 zones,
                                 heating: false,
                                 cooling: true,
                                 ventilation: false)

  when 'Forced Air Furnace'
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', 'If a Forced Air Furnace with ventilation serves a core zone, make sure the outdoor air is included in design sizing for the systems (typically occupancy, and therefore ventilation is zero during winter sizing), otherwise it may not be sized large enough to meet the heating load in some situations.')
    model_add_furnace_central_ac(model,
                                 zones,
                                 heating: true,
                                 cooling: false,
                                 ventilation: true)

  when 'Residential Forced Air Furnace'
    model_add_furnace_central_ac(model,
                                 zones,
                                 heating: true,
                                 cooling: false,
                                 ventilation: false)

  when 'Residential Forced Air Furnace with AC'
    model_add_furnace_central_ac(model,
                                 zones,
                                 heating: true,
                                 cooling: true,
                                 ventilation: false)

  when 'Residential Air Source Heat Pump'
    heating = true unless main_heat_fuel.nil?
    cooling = true unless cool_fuel.nil?
    model_add_central_air_source_heat_pump(model,
                                           zones,
                                           heating: heating,
                                           cooling: cooling,
                                           ventilation: false)

  when 'Residential Minisplit Heat Pumps'
    model_add_minisplit_hp(model,
                           zones)

  when 'VAV Reheat'
    case main_heat_fuel
    when 'NaturalGas', 'Gas', 'HeatPump', 'DistrictHeating', 'DistrictHeatingWater', 'DistrictHeatingSteam'
      heating_type = main_heat_fuel
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: hot_water_loop_type)
    when 'AirSourceHeatPump'
      heating_type = main_heat_fuel
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: 'LowTemperature')
    else
      heating_type = 'Electricity'
      hot_water_loop = nil
    end

    case air_loop_cooling_type
    when 'Water'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                               chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    else
      chilled_water_loop = nil
    end

    if hot_water_loop.nil?
      case zone_heat_fuel
      when 'NaturalGas', 'Gas'
        reheat_type = 'NaturalGas'
      when 'Electricity'
        reheat_type = 'Electricity'
      else
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "zone_heat_fuel '#{zone_heat_fuel}' not supported with main_heat_fuel '#{main_heat_fuel}' for a 'VAV Reheat' system type.")
        return false
      end
    else
      reheat_type = 'Water'
    end

    model_add_vav_reheat(model,
                         zones,
                         heating_type: heating_type,
                         reheat_type: reheat_type,
                         hot_water_loop: hot_water_loop,
                         chilled_water_loop: chilled_water_loop,
                         fan_efficiency: 0.62,
                         fan_motor_efficiency: 0.9,
                         fan_pressure_rise: 4.0)

  when 'VAV No Reheat'
    case main_heat_fuel
    when 'NaturalGas', 'Gas', 'HeatPump', 'DistrictHeating', 'DistrictHeatingWater', 'DistrictHeatingSteam'
      heating_type = main_heat_fuel
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: hot_water_loop_type)
    when 'AirSourceHeatPump'
      heating_type = main_heat_fuel
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: 'LowTemperature')
    else
      heating_type = 'Electricity'
      hot_water_loop = nil
    end

    if air_loop_cooling_type == 'Water'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                               chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    else
      chilled_water_loop = nil
    end
    model_add_vav_reheat(model,
                         zones,
                         heating_type: heating_type,
                         reheat_type: nil,
                         hot_water_loop: hot_water_loop,
                         chilled_water_loop: chilled_water_loop,
                         fan_efficiency: 0.62,
                         fan_motor_efficiency: 0.9,
                         fan_pressure_rise: 4.0)

  when 'VAV Gas Reheat'
    if air_loop_cooling_type == 'Water'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                               chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    else
      chilled_water_loop = nil
    end
    model_add_vav_reheat(model,
                         zones,
                         heating_type: 'NaturalGas',
                         reheat_type: 'NaturalGas',
                         chilled_water_loop: chilled_water_loop,
                         fan_efficiency: 0.62,
                         fan_motor_efficiency: 0.9,
                         fan_pressure_rise: 4.0)

  when 'PVAV Reheat'
    case main_heat_fuel
    when 'AirSourceHeatPump'
      hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                       hot_water_loop_type: 'LowTemperature')
    else
      if air_loop_heating_type == 'Water'
        hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                         hot_water_loop_type: hot_water_loop_type)
      else
        heating_type = main_heat_fuel
      end
    end

    case cool_fuel
    when 'Electricity'
      chilled_water_loop = nil
    else
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                               chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    end

    if zone_heat_fuel == 'Electricity'
      electric_reheat = true
    else
      electric_reheat = false
    end

    model_add_pvav(model,
                   zones,
                   hot_water_loop: hot_water_loop,
                   chilled_water_loop: chilled_water_loop,
                   heating_type: heating_type,
                   electric_reheat: electric_reheat)

  when 'PVAV PFP Boxes'
    case cool_fuel
    when 'DistrictCooling'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel)
    else
      chilled_water_loop = nil
    end
    model_add_pvav_pfp_boxes(model,
                             zones,
                             chilled_water_loop: chilled_water_loop,
                             fan_efficiency: 0.62,
                             fan_motor_efficiency: 0.9,
                             fan_pressure_rise: 4.0)

  when 'VAV PFP Boxes'
    chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                             chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    model_add_pvav_pfp_boxes(model,
                             zones,
                             chilled_water_loop: chilled_water_loop,
                             fan_efficiency: 0.62,
                             fan_motor_efficiency: 0.9,
                             fan_pressure_rise: 4.0)

  when 'Water Source Heat Pumps'
    if main_heat_fuel.include?('DistrictHeating') && cool_fuel == 'DistrictCooling'
      condenser_loop = model_get_or_add_ambient_water_loop(model)
    elsif main_heat_fuel == 'AmbientLoop' && cool_fuel == 'AmbientLoop'
      condenser_loop = model_get_or_add_ambient_water_loop(model)
    else
      condenser_loop = model_get_or_add_heat_pump_loop(model, main_heat_fuel, cool_fuel,
                                                       heat_pump_loop_cooling_type: heat_pump_loop_cooling_type)
    end
    model_add_water_source_hp(model,
                              zones,
                              condenser_loop,
                              ventilation: zone_equipment_ventilation)

  when 'Ground Source Heat Pumps'
    condenser_loop = model_get_or_add_ground_hx_loop(model)
    model_add_water_source_hp(model,
                              zones,
                              condenser_loop,
                              ventilation: zone_equipment_ventilation)

  when 'DOAS Cold Supply'
    hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                     hot_water_loop_type: hot_water_loop_type)
    chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                             chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    model_add_doas_cold_supply(model,
                               zones,
                               hot_water_loop: hot_water_loop,
                               chilled_water_loop: chilled_water_loop)

  when 'DOAS'
    if air_loop_heating_type == 'Water'
      case main_heat_fuel
      when nil
        hot_water_loop = nil
      when 'AirSourceHeatPump'
        hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                         hot_water_loop_type: 'LowTemperature')
      when 'Electricity'
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "air_loop_heating_type '#{air_loop_heating_type}' is not supported with main_heat_fuel '#{main_heat_fuel}' for a 'DOAS' system type.")
        return false
      else
        hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                         hot_water_loop_type: hot_water_loop_type)
      end
    else
      hot_water_loop = nil
    end
    if air_loop_cooling_type == 'Water'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                               chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    else
      chilled_water_loop = nil
    end

    model_add_doas(model,
                   zones,
                   hot_water_loop: hot_water_loop,
                   chilled_water_loop: chilled_water_loop)

  when 'DOAS with DCV'
    if air_loop_heating_type == 'Water'
      case main_heat_fuel
      when nil
        hot_water_loop = nil
      when 'AirSourceHeatPump'
        hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                         hot_water_loop_type: 'LowTemperature')
      else
        hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                         hot_water_loop_type: hot_water_loop_type)
      end
    else
      hot_water_loop = nil
    end
    if air_loop_cooling_type == 'Water'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                               chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    else
      chilled_water_loop = nil
    end

    model_add_doas(model,
                   zones,
                   hot_water_loop: hot_water_loop,
                   chilled_water_loop: chilled_water_loop,
                   doas_type: 'DOASVAV',
                   demand_control_ventilation: true)

  when 'DOAS with Economizing'
    if air_loop_heating_type == 'Water'
      case main_heat_fuel
      when nil
        hot_water_loop = nil
      when 'AirSourceHeatPump'
        hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                         hot_water_loop_type: 'LowTemperature')
      else
        hot_water_loop = model_get_or_add_hot_water_loop(model, main_heat_fuel,
                                                         hot_water_loop_type: hot_water_loop_type)
      end
    else
      hot_water_loop = nil
    end
    if air_loop_cooling_type == 'Water'
      chilled_water_loop = model_get_or_add_chilled_water_loop(model, cool_fuel,
                                                               chilled_water_loop_cooling_type: chilled_water_loop_cooling_type)
    else
      chilled_water_loop = nil
    end

    model_add_doas(model,
                   zones,
                   hot_water_loop: hot_water_loop,
                   chilled_water_loop: chilled_water_loop,
                   doas_type: 'DOASVAV',
                   econo_ctrl_mthd: 'FixedDryBulb')

  when 'ERVs'
    model_add_zone_erv(model, zones)

  when 'Evaporative Cooler'
    model_add_evap_cooler(model, zones)

  when 'Ideal Air Loads'
    model_add_ideal_air_loads(model, zones)

  else
    # Combination Systems
    if system_type.include? 'with DOAS with DCV'
      # add DOAS DCV system
      model_add_hvac_system(model, 'DOAS with DCV', main_heat_fuel, zone_heat_fuel, cool_fuel, zones,
                            hot_water_loop_type: hot_water_loop_type,
                            chilled_water_loop_cooling_type: chilled_water_loop_cooling_type,
                            heat_pump_loop_cooling_type: heat_pump_loop_cooling_type,
                            air_loop_heating_type: air_loop_heating_type,
                            air_loop_cooling_type: air_loop_cooling_type,
                            zone_equipment_ventilation: false,
                            fan_coil_capacity_control_method: fan_coil_capacity_control_method)
      # add paired system type
      paired_system_type = system_type.gsub(' with DOAS with DCV', '')
      model_add_hvac_system(model, paired_system_type, main_heat_fuel, zone_heat_fuel, cool_fuel, zones,
                            hot_water_loop_type: hot_water_loop_type,
                            chilled_water_loop_cooling_type: chilled_water_loop_cooling_type,
                            heat_pump_loop_cooling_type: heat_pump_loop_cooling_type,
                            air_loop_heating_type: air_loop_heating_type,
                            air_loop_cooling_type: air_loop_cooling_type,
                            zone_equipment_ventilation: false,
                            fan_coil_capacity_control_method: fan_coil_capacity_control_method)
    elsif system_type.include? 'with DOAS'
      # add DOAS system
      model_add_hvac_system(model, 'DOAS', main_heat_fuel, zone_heat_fuel, cool_fuel, zones,
                            hot_water_loop_type: hot_water_loop_type,
                            chilled_water_loop_cooling_type: chilled_water_loop_cooling_type,
                            heat_pump_loop_cooling_type: heat_pump_loop_cooling_type,
                            air_loop_heating_type: air_loop_heating_type,
                            air_loop_cooling_type: air_loop_cooling_type,
                            zone_equipment_ventilation: false,
                            fan_coil_capacity_control_method: fan_coil_capacity_control_method)
      # add paired system type
      paired_system_type = system_type.gsub(' with DOAS', '')
      model_add_hvac_system(model, paired_system_type, main_heat_fuel, zone_heat_fuel, cool_fuel, zones,
                            hot_water_loop_type: hot_water_loop_type,
                            chilled_water_loop_cooling_type: chilled_water_loop_cooling_type,
                            heat_pump_loop_cooling_type: heat_pump_loop_cooling_type,
                            air_loop_heating_type: air_loop_heating_type,
                            air_loop_cooling_type: air_loop_cooling_type,
                            zone_equipment_ventilation: false,
                            fan_coil_capacity_control_method: fan_coil_capacity_control_method)
    elsif system_type.include? 'with ERVs'
      # add DOAS system
      model_add_hvac_system(model, 'ERVs', main_heat_fuel, zone_heat_fuel, cool_fuel, zones,
                            hot_water_loop_type: hot_water_loop_type,
                            chilled_water_loop_cooling_type: chilled_water_loop_cooling_type,
                            heat_pump_loop_cooling_type: heat_pump_loop_cooling_type,
                            air_loop_heating_type: air_loop_heating_type,
                            air_loop_cooling_type: air_loop_cooling_type,
                            zone_equipment_ventilation: false,
                            fan_coil_capacity_control_method: fan_coil_capacity_control_method)
      # add paired system type
      paired_system_type = system_type.gsub(' with ERVs', '')
      model_add_hvac_system(model, paired_system_type, main_heat_fuel, zone_heat_fuel, cool_fuel, zones,
                            hot_water_loop_type: hot_water_loop_type,
                            chilled_water_loop_cooling_type: chilled_water_loop_cooling_type,
                            heat_pump_loop_cooling_type: heat_pump_loop_cooling_type,
                            air_loop_heating_type: air_loop_heating_type,
                            air_loop_cooling_type: air_loop_cooling_type,
                            zone_equipment_ventilation: false,
                            fan_coil_capacity_control_method: fan_coil_capacity_control_method)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "HVAC system type '#{system_type}' not recognized")
      return false
    end
  end

  # rename air loop and plant loop nodes for readability
  rename_air_loop_nodes(model)
  rename_plant_loop_nodes(model)
end
model_add_hw_loop(model, boiler_fuel_type, ambient_loop: nil, system_name: 'Hot Water Loop', dsgn_sup_wtr_temp: 180.0, dsgn_sup_wtr_temp_delt: 20.0, pump_spd_ctrl: 'Variable', pump_tot_hd: nil, boiler_draft_type: nil, boiler_eff_curve_temp_eval_var: nil, boiler_lvg_temp_dsgn: nil, boiler_out_temp_lmt: nil, boiler_max_plr: nil, boiler_sizing_factor: nil) click to toggle source

Creates a hot water loop with a boiler, district heating, or a water-to-water heat pump and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param boiler_fuel_type [String] valid choices are Electricity, NaturalGas, Propane, PropaneGas, FuelOilNo1, FuelOilNo2,

DistrictHeating, DistrictHeatingWater, DistrictHeatingSteam, HeatPump

@param ambient_loop [OpenStudio::Model::PlantLoop] The condenser loop for the heat pump. Only used when boiler_fuel_type is HeatPump. @param system_name [String] the name of the system, or nil in which case it will be defaulted @param dsgn_sup_wtr_temp [Double] design supply water temperature in degrees Fahrenheit, default 180F @param dsgn_sup_wtr_temp_delt [Double] design supply-return water temperature difference in degrees Rankine, default 20R @param pump_spd_ctrl [String] pump speed control type, Constant or Variable (default) @param pump_tot_hd [Double] pump head in ft H2O @param boiler_draft_type [String] Boiler type Condensing, MechanicalNoncondensing, Natural (default) @param boiler_eff_curve_temp_eval_var [String] LeavingBoiler or EnteringBoiler temperature for the boiler efficiency curve @param boiler_lvg_temp_dsgn [Double] boiler leaving design temperature in degrees Fahrenheit @param boiler_out_temp_lmt [Double] boiler outlet temperature limit in degrees Fahrenheit @param boiler_max_plr [Double] boiler maximum part load ratio @param boiler_sizing_factor [Double] boiler oversizing factor @return [OpenStudio::Model::PlantLoop] the resulting hot water loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 42
def model_add_hw_loop(model,
                      boiler_fuel_type,
                      ambient_loop: nil,
                      system_name: 'Hot Water Loop',
                      dsgn_sup_wtr_temp: 180.0,
                      dsgn_sup_wtr_temp_delt: 20.0,
                      pump_spd_ctrl: 'Variable',
                      pump_tot_hd: nil,
                      boiler_draft_type: nil,
                      boiler_eff_curve_temp_eval_var: nil,
                      boiler_lvg_temp_dsgn: nil,
                      boiler_out_temp_lmt: nil,
                      boiler_max_plr: nil,
                      boiler_sizing_factor: nil)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', 'Adding hot water loop.')

  # create hot water loop
  hot_water_loop = OpenStudio::Model::PlantLoop.new(model)
  if system_name.nil?
    hot_water_loop.setName('Hot Water Loop')
  else
    hot_water_loop.setName(system_name)
  end

  # hot water loop sizing and controls
  if dsgn_sup_wtr_temp.nil?
    dsgn_sup_wtr_temp = 180.0
    dsgn_sup_wtr_temp_c = OpenStudio.convert(dsgn_sup_wtr_temp, 'F', 'C').get
  else
    dsgn_sup_wtr_temp_c = OpenStudio.convert(dsgn_sup_wtr_temp, 'F', 'C').get
  end
  if dsgn_sup_wtr_temp_delt.nil?
    dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(20.0, 'R', 'K').get
  else
    dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(dsgn_sup_wtr_temp_delt, 'R', 'K').get
  end

  sizing_plant = hot_water_loop.sizingPlant
  sizing_plant.setLoopType('Heating')
  sizing_plant.setDesignLoopExitTemperature(dsgn_sup_wtr_temp_c)
  sizing_plant.setLoopDesignTemperatureDifference(dsgn_sup_wtr_temp_delt_k)
  hot_water_loop.setMinimumLoopTemperature(10.0)
  hw_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                dsgn_sup_wtr_temp_c,
                                                                                name: "#{hot_water_loop.name} Temp - #{dsgn_sup_wtr_temp.round(0)}F",
                                                                                schedule_type_limit: 'Temperature')
  hw_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, hw_temp_sch)
  hw_stpt_manager.setName("#{hot_water_loop.name} Setpoint Manager")
  hw_stpt_manager.addToNode(hot_water_loop.supplyOutletNode)

  # create hot water pump
  if pump_spd_ctrl == 'Constant'
    hw_pump = OpenStudio::Model::PumpConstantSpeed.new(model)
  elsif pump_spd_ctrl == 'Variable'
    hw_pump = OpenStudio::Model::PumpVariableSpeed.new(model)
  else
    hw_pump = OpenStudio::Model::PumpVariableSpeed.new(model)
  end
  hw_pump.setName("#{hot_water_loop.name} Pump")
  if pump_tot_hd.nil?
    pump_tot_hd_pa = OpenStudio.convert(60, 'ftH_{2}O', 'Pa').get
  else
    pump_tot_hd_pa = OpenStudio.convert(pump_tot_hd, 'ftH_{2}O', 'Pa').get
  end
  hw_pump.setRatedPumpHead(pump_tot_hd_pa)
  hw_pump.setMotorEfficiency(0.9)
  hw_pump.setPumpControlType('Intermittent')
  hw_pump.addToNode(hot_water_loop.supplyInletNode)

  # switch statement to handle district heating name change
  if model.version < OpenStudio::VersionString.new('3.7.0')
    if boiler_fuel_type == 'DistrictHeatingWater' || boiler_fuel_type == 'DistrictHeatingSteam'
      boiler_fuel_type = 'DistrictHeating'
    end
  else
    boiler_fuel_type = 'DistrictHeatingWater' if boiler_fuel_type == 'DistrictHeating'
  end

  # create boiler and add to loop
  case boiler_fuel_type
    # District Heating
    when 'DistrictHeating'
      district_heat = OpenStudio::Model::DistrictHeating.new(model)
      district_heat.setName("#{hot_water_loop.name} District Heating")
      district_heat.autosizeNominalCapacity
      hot_water_loop.addSupplyBranchForComponent(district_heat)
    when 'DistrictHeatingWater'
      district_heat = OpenStudio::Model::DistrictHeatingWater.new(model)
      district_heat.setName("#{hot_water_loop.name} District Heating")
      district_heat.autosizeNominalCapacity
      hot_water_loop.addSupplyBranchForComponent(district_heat)
    when 'DistrictHeatingSteam'
      district_heat = OpenStudio::Model::DistrictHeatingSteam.new(model)
      district_heat.setName("#{hot_water_loop.name} District Heating")
      district_heat.autosizeNominalCapacity
      hot_water_loop.addSupplyBranchForComponent(district_heat)
    when 'HeatPump', 'AmbientLoop'
      # Ambient Loop
      water_to_water_hp = OpenStudio::Model::HeatPumpWaterToWaterEquationFitHeating.new(model)
      water_to_water_hp.setName("#{hot_water_loop.name} Water to Water Heat Pump")
      hot_water_loop.addSupplyBranchForComponent(water_to_water_hp)
      # Get or add an ambient loop
      if ambient_loop.nil?
        ambient_loop = model_get_or_add_ambient_water_loop(model)
      end
      ambient_loop.addDemandBranchForComponent(water_to_water_hp)
    # Central Air Source Heat Pump
    when 'AirSourceHeatPump', 'ASHP'
      create_central_air_source_heat_pump(model, hot_water_loop)
    # Boiler
    when 'Electricity', 'Gas', 'NaturalGas', 'Propane', 'PropaneGas', 'FuelOilNo1', 'FuelOilNo2'
      if boiler_lvg_temp_dsgn.nil?
        lvg_temp_dsgn_f = dsgn_sup_wtr_temp
      else
        lvg_temp_dsgn_f = boiler_lvg_temp_dsgn
      end

      if boiler_out_temp_lmt.nil?
        out_temp_lmt_f = 203.0
      else
        out_temp_lmt_f = boiler_out_temp_lmt
      end

      boiler = create_boiler_hot_water(model,
                                       hot_water_loop: hot_water_loop,
                                       fuel_type: boiler_fuel_type,
                                       draft_type: boiler_draft_type,
                                       nominal_thermal_efficiency: 0.78,
                                       eff_curve_temp_eval_var: boiler_eff_curve_temp_eval_var,
                                       lvg_temp_dsgn_f: lvg_temp_dsgn_f,
                                       out_temp_lmt_f: out_temp_lmt_f,
                                       max_plr: boiler_max_plr,
                                       sizing_factor: boiler_sizing_factor)

      # @todo Yixing. Adding temperature setpoint controller at boiler outlet causes simulation errors
      # boiler_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(self, hw_temp_sch)
      # boiler_stpt_manager.setName("Boiler outlet setpoint manager")
      # boiler_stpt_manager.addToNode(boiler.outletModelObject.get.to_Node.get)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Boiler fuel type #{boiler_fuel_type} is not valid, no boiler will be added.")
  end

  # add hot water loop pipes
  supply_equipment_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_equipment_bypass_pipe.setName("#{hot_water_loop.name} Supply Equipment Bypass")
  hot_water_loop.addSupplyBranchForComponent(supply_equipment_bypass_pipe)

  coil_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  coil_bypass_pipe.setName("#{hot_water_loop.name} Coil Bypass")
  hot_water_loop.addDemandBranchForComponent(coil_bypass_pipe)

  supply_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_outlet_pipe.setName("#{hot_water_loop.name} Supply Outlet")
  supply_outlet_pipe.addToNode(hot_water_loop.supplyOutletNode)

  demand_inlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_inlet_pipe.setName("#{hot_water_loop.name} Demand Inlet")
  demand_inlet_pipe.addToNode(hot_water_loop.demandInletNode)

  demand_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_outlet_pipe.setName("#{hot_water_loop.name} Demand Outlet")
  demand_outlet_pipe.addToNode(hot_water_loop.demandOutletNode)

  return hot_water_loop
end
model_add_ideal_air_loads(model, thermal_zones, hvac_op_sch: nil, heat_avail_sch: nil, cool_avail_sch: nil, heat_limit_type: 'NoLimit', cool_limit_type: 'NoLimit', dehumid_limit_type: 'ConstantSensibleHeatRatio', cool_sensible_heat_ratio: 0.7, humid_ctrl_type: 'None', include_outdoor_air: true, enable_dcv: false, econo_ctrl_mthd: 'NoEconomizer', heat_recovery_type: 'None', heat_recovery_sensible_eff: 0.7, heat_recovery_latent_eff: 0.65, add_output_meters: false) click to toggle source

Adds ideal air loads systems for each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to enable ideal air loads @param hvac_op_sch [String] name of the HVAC operation schedule, default is always on @param heat_avail_sch [String] name of the heating availability schedule, default is always on @param cool_avail_sch [String] name of the cooling availability schedule, default is always on @param heat_limit_type [String] heating limit type

options are 'NoLimit', 'LimitFlowRate', 'LimitCapacity', and 'LimitFlowRateAndCapacity'

@param cool_limit_type [String] cooling limit type

options are 'NoLimit', 'LimitFlowRate', 'LimitCapacity', and 'LimitFlowRateAndCapacity'

@param dehumid_limit_type [String] dehumidification limit type

options are 'None', 'ConstantSensibleHeatRatio', 'Humidistat', 'ConstantSupplyHumidityRatio'

@param cool_sensible_heat_ratio [Double] cooling sensible heat ratio if dehumidification limit type is ‘ConstantSensibleHeatRatio’ @param humid_ctrl_type [String] humidification control type

options are 'None', 'Humidistat', 'ConstantSupplyHumidityRatio'

@param include_outdoor_air [Boolean] include design specification outdoor air ventilation @param enable_dcv [Boolean] include demand control ventilation, uses occupancy schedule if true @param econo_ctrl_mthd [String] economizer control method (require a cool_limit_type and include_outdoor_air set to true)

options are 'NoEconomizer', 'DifferentialDryBulb', 'DifferentialEnthalpy'

@param heat_recovery_type [String] heat recovery type

options are 'None', 'Sensible', 'Enthalpy'

@param heat_recovery_sensible_eff [Double] heat recovery sensible effectivness if heat recovery specified @param heat_recovery_latent_eff [Double] heat recovery latent effectivness if heat recovery specified @param add_output_meters [Boolean] include and output custom meter objects to sum all ideal air loads values @return [Array<OpenStudio::Model::ZoneHVACIdealLoadsAirSystem>] an array of ideal air loads systems

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 5775
def model_add_ideal_air_loads(model,
                              thermal_zones,
                              hvac_op_sch: nil,
                              heat_avail_sch: nil,
                              cool_avail_sch: nil,
                              heat_limit_type: 'NoLimit',
                              cool_limit_type: 'NoLimit',
                              dehumid_limit_type: 'ConstantSensibleHeatRatio',
                              cool_sensible_heat_ratio: 0.7,
                              humid_ctrl_type: 'None',
                              include_outdoor_air: true,
                              enable_dcv: false,
                              econo_ctrl_mthd: 'NoEconomizer',
                              heat_recovery_type: 'None',
                              heat_recovery_sensible_eff: 0.7,
                              heat_recovery_latent_eff: 0.65,
                              add_output_meters: false)

  # set availability schedules
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # set heating availability schedules
  if heat_avail_sch.nil?
    heat_avail_sch = model.alwaysOnDiscreteSchedule
  else
    heat_avail_sch = model_add_schedule(model, heat_avail_sch)
  end

  # set cooling availability schedules
  if cool_avail_sch.nil?
    cool_avail_sch = model.alwaysOnDiscreteSchedule
  else
    cool_avail_sch = model_add_schedule(model, cool_avail_sch)
  end

  ideal_systems = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding ideal air loads for for #{zone.name}.")
    ideal_loads = OpenStudio::Model::ZoneHVACIdealLoadsAirSystem.new(model)
    ideal_loads.setName("#{zone.name} Ideal Loads Air System")
    ideal_loads.setAvailabilitySchedule(hvac_op_sch)
    ideal_loads.setHeatingAvailabilitySchedule(heat_avail_sch)
    ideal_loads.setCoolingAvailabilitySchedule(cool_avail_sch)
    ideal_loads.setHeatingLimit(heat_limit_type)
    ideal_loads.setCoolingLimit(cool_limit_type)
    ideal_loads.setDehumidificationControlType(dehumid_limit_type)
    ideal_loads.setCoolingSensibleHeatRatio(cool_sensible_heat_ratio)
    ideal_loads.setHumidificationControlType(humid_ctrl_type)
    if include_outdoor_air
      # get the design specification outdoor air of the largest space in the zone
      # @todo create a new design specification outdoor air object that sums ventilation rates and schedules if multiple design specification outdoor air objects
      space_areas = zone.spaces.map(&:floorArea)
      largest_space = zone.spaces.select { |s| s.floorArea == space_areas.max }
      largest_space = largest_space[0]
      design_spec_oa = largest_space.designSpecificationOutdoorAir
      if design_spec_oa.is_initialized
        design_spec_oa = design_spec_oa.get
        ideal_loads.setDesignSpecificationOutdoorAirObject(design_spec_oa)
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "Outdoor air requested for ideal loads object, but space #{largest_space.name} in thermal zone #{zone.name} does not have a design specification outdoor air object.")
      end
    end
    if enable_dcv
      ideal_loads.setDemandControlledVentilationType('OccupancySchedule')
    else
      ideal_loads.setDemandControlledVentilationType('None')
    end
    ideal_loads.setOutdoorAirEconomizerType(econo_ctrl_mthd)
    ideal_loads.setHeatRecoveryType(heat_recovery_type)
    ideal_loads.setSensibleHeatRecoveryEffectiveness(heat_recovery_sensible_eff)
    ideal_loads.setLatentHeatRecoveryEffectiveness(heat_recovery_latent_eff)
    ideal_loads.addToThermalZone(zone)
    ideal_systems << ideal_loads

    # set zone sizing parameters
    zone_sizing = zone.sizingZone
    zone_sizing.setHeatingMaximumAirFlowFraction(1.0)
  end

  if add_output_meters
    # ideal air loads system variables to include
    ideal_air_loads_system_variables = [
      'Zone Ideal Loads Supply Air Sensible Heating Energy',
      'Zone Ideal Loads Supply Air Latent Heating Energy',
      'Zone Ideal Loads Supply Air Total Heating Energy',
      'Zone Ideal Loads Supply Air Sensible Cooling Energy',
      'Zone Ideal Loads Supply Air Latent Cooling Energy',
      'Zone Ideal Loads Supply Air Total Cooling Energy',
      'Zone Ideal Loads Zone Sensible Heating Energy',
      'Zone Ideal Loads Zone Latent Heating Energy',
      'Zone Ideal Loads Zone Total Heating Energy',
      'Zone Ideal Loads Zone Sensible Cooling Energy',
      'Zone Ideal Loads Zone Latent Cooling Energy',
      'Zone Ideal Loads Zone Total Cooling Energy',
      'Zone Ideal Loads Outdoor Air Sensible Heating Energy',
      'Zone Ideal Loads Outdoor Air Latent Heating Energy',
      'Zone Ideal Loads Outdoor Air Total Heating Energy',
      'Zone Ideal Loads Outdoor Air Sensible Cooling Energy',
      'Zone Ideal Loads Outdoor Air Latent Cooling Energy',
      'Zone Ideal Loads Outdoor Air Total Cooling Energy',
      'Zone Ideal Loads Heat Recovery Sensible Heating Energy',
      'Zone Ideal Loads Heat Recovery Latent Heating Energy',
      'Zone Ideal Loads Heat Recovery Total Heating Energy',
      'Zone Ideal Loads Heat Recovery Sensible Cooling Energy',
      'Zone Ideal Loads Heat Recovery Latent Cooling Energy',
      'Zone Ideal Loads Heat Recovery Total Cooling Energy'
    ]

    meters_added = 0
    outputs_added = 0
    ideal_air_loads_system_variables.each do |variable|
      # create meter definition for variable
      meter_definition = OpenStudio::Model::MeterCustom.new(model)
      meter_definition.setName("Sum #{variable}")
      meter_definition.setFuelType('Generic')
      model.getZoneHVACIdealLoadsAirSystems.each { |sys| meter_definition.addKeyVarGroup(sys.name.to_s, variable) }
      meters_added += 1

      # add output meter
      output_meter_definition = OpenStudio::Model::OutputMeter.new(model)
      output_meter_definition.setName("Sum #{variable}")
      output_meter_definition.setReportingFrequency('Hourly')
      output_meter_definition.setMeterFileOnly(true)
      output_meter_definition.setCumulative(false)
      outputs_added += 1
    end
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Added #{meters_added} custom meter objects and #{outputs_added} meter outputs for ideal loads air systems.")
  end

  return ideal_systems
end
model_add_low_temp_radiant(model, thermal_zones, hot_water_loop, chilled_water_loop, two_pipe_system: false, two_pipe_control_strategy: 'outdoor_air_lockout', two_pipe_lockout_temperature: 65.0, plant_supply_water_temperature_control: false, plant_supply_water_temperature_control_strategy: 'outdoor_air', hwsp_at_oat_low: 120.0, hw_oat_low: 55.0, hwsp_at_oat_high: 80.0, hw_oat_high: 70.0, chwsp_at_oat_low: 70.0, chw_oat_low: 65.0, chwsp_at_oat_high: 55.0, chw_oat_high: 75.0, radiant_type: 'floor', radiant_temperature_control_type: 'SurfaceFaceTemperature', radiant_setpoint_control_type: 'ZeroFlowPower', include_carpet: true, carpet_thickness_in: 0.25, control_strategy: 'proportional_control', use_zone_occupancy_for_control: true, occupied_percentage_threshold: 0.10, model_occ_hr_start: 6.0, model_occ_hr_end: 18.0, proportional_gain: 0.3, switch_over_time: 24.0, slab_sp_at_oat_low: 73, slab_oat_low: 65, slab_sp_at_oat_high: 68, slab_oat_high: 80, radiant_availability_type: 'precool', radiant_lockout: false, radiant_lockout_start_time: 12.0, radiant_lockout_end_time: 20.0) click to toggle source

Adds low temperature radiant loop systems to each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to add radiant loops @param hot_water_loop [OpenStudio::Model::PlantLoop] the hot water loop that serves the radiant loop. @param chilled_water_loop [OpenStudio::Model::PlantLoop] the chilled water loop that serves the radiant loop. @param two_pipe_system [Boolean] when set to true, it converts the default 4-pipe water plant HVAC system to a 2-pipe system. @param two_pipe_control_strategy [String] Method to determine whether the loop is in heating or cooling mode

'outdoor_air_lockout' - The system will be in heating below the two_pipe_lockout_temperature variable,
   and cooling above the two_pipe_lockout_temperature. Requires the two_pipe_lockout_temperature variable.
'zone_demand' - Create EMS code to determine heating or cooling mode based on zone heating or cooling load requests.
   Requires thermal_zones defined.

@param two_pipe_lockout_temperature [Double] hot water plant lockout in degrees Fahrenheit, default 65F.

Hot water plant is unavailable when outdoor drybulb is above the specified threshold.

@param plant_supply_water_temperature_control [Bool] Set to true if the plant supply water temperature

is to be controlled else it is held constant, default to false.

@param plant_supply_water_temperature_control_strategy [String] Method to determine how to control the plant’s supply water temperature.

'outdoor_air' - Set the supply water temperature based on the outdoor air temperature.
'zone_demand' - Set the supply water temperature based on the preponderance of zone demand.
  Requires thermal_zone defined.

@param hwsp_at_oat_low [Double] hot water plant supply water temperature setpoint, in F, at the outdoor low temperature.

Requires

@param hw_oat_low [Double] outdoor drybulb air temperature, in F, for low setpoint for hot water plant. @param hwsp_at_oat_high [Double] hot water plant supply water temperature setpoint, in F, at the outdoor high temperature. @param hw_oat_high [Double] outdoor drybulb air temperature, in F, for high setpoint for hot water plant. @param chwsp_at_oat_low [Double] chilled water plant supply water temperature setpoint, in F, at the outdoor low temperature. @param chw_oat_low [Double] outdoor drybulb air temperature, in F, for low setpoint for chilled water plant. @param chwsp_at_oat_high [Double] chilled water plant supply water temperature setpoint, in F, at the outdoor high temperature. @param chw_oat_high [Double] outdoor drybulb air temperature, in F, for high setpoint for chilled water plant. @param radiant_type [String] type of radiant system, floor or ceiling, to create in zone. @param radiant_temperature_control_type [String] determines the controlled temperature for the radiant system

options are 'MeanAirTemperature', 'MeanRadiantTemperature', 'OperativeTemperature', 'OutdoorDryBulbTemperature',
'OutdoorWetBulbTemperature', 'SurfaceFaceTemperature', 'SurfaceInteriorTemperature'

@param radiant_setpoint_control_type [String] determines the response of the radiant system at setpoint temperature

options are 'ZeroFlowPower', 'HalfFlowPower'

@param include_carpet [Boolean] boolean to include thin carpet tile over radiant slab, default to true @param carpet_thickness_in [Double] thickness of carpet in inches @param control_strategy [String] name of control strategy. Options are ‘proportional_control’, ‘oa_based_control’,

'constant_control', and 'none'.
If control strategy is 'proportional_control', the method will apply the CBE radiant control sequences
detailed in Raftery et al. (2017), 'A new control strategy for high thermal mass radiant systems'.
If control strategy is 'oa_based_control', the method will apply native EnergyPlus objects/parameters
to vary slab setpoint based on outdoor weather.
If control strategy is 'constant_control', the method will apply native EnergyPlus objects/parameters to
maintain a constant slab setpoint.
Otherwise no control strategy will be applied and the radiant system will assume the EnergyPlus default controls.

@param use_zone_occupancy_for_control [Boolean] Set to true if radiant system is to use specific zone occupancy objects

for CBE control strategy. If false, then it will use values in model_occ_hr_start and model_occ_hr_end
for all radiant zones. default to true.

@param occupied_percentage_threshold [Double] the minimum fraction (0 to 1) that counts as occupied

if this parameter is set, the returned ScheduleRuleset will be 0 = unoccupied, 1 = occupied
otherwise the ScheduleRuleset will be the weighted fractional occupancy schedule.
Only used if use_zone_occupancy_for_control is set to true.

@param model_occ_hr_start [Double] (Optional) Only applies if control_strategy is ‘proportional_control’.

Starting hour of building occupancy.

@param model_occ_hr_end [Double] (Optional) Only applies if control_strategy is ‘proportional_control’.

Ending hour of building occupancy.

@param proportional_gain [Double] (Optional) Only applies if control_strategy is ‘proportional_control’.

Proportional gain constant (recommended 0.3 or less).

@param switch_over_time [Double] Time limitation for when the system can switch between heating and cooling @param slab_sp_at_oat_low [Double] radiant slab temperature setpoint, in F, at the outdoor high temperature. @param slab_oat_low [Double] outdoor drybulb air temperature, in F, for low radiant slab setpoint. @param slab_sp_at_oat_high [Double] radiant slab temperature setpoint, in F, at the outdoor low temperature. @param slab_oat_high [Double] outdoor drybulb air temperature, in F, for high radiant slab setpoint. @param radiant_availability_type [String] a preset that determines the availability of the radiant system

options are 'all_day', 'precool', 'afternoon_shutoff', 'occupancy'
If preset is set to 'all_day' radiant system is available 24 hours a day, 'precool' primarily operates
radiant system during night-time hours, 'afternoon_shutoff' avoids operation during peak grid demand,
and 'occupancy' operates radiant system during building occupancy hours.

@param radiant_lockout [Boolean] True if system contains a radiant lockout. If true, it will overwrite radiant_availability_type. @param radiant_lockout_start_time [double] decimal hour of when radiant lockout starts

Only used if radiant_lockout is true

@param radiant_lockout_end_time [double] decimal hour of when radiant lockout ends

Only used if radiant_lockout is true

@return [Array<OpenStudio::Model::ZoneHVACLowTemperatureRadiantVariableFlow>] array of radiant objects. @todo Once the OpenStudio API supports it, make chilled water loops optional for heating only systems @todo Lookup occupany start and end hours from zone occupancy schedule

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 4809
def model_add_low_temp_radiant(model,
                               thermal_zones,
                               hot_water_loop,
                               chilled_water_loop,
                               two_pipe_system: false,
                               two_pipe_control_strategy: 'outdoor_air_lockout',
                               two_pipe_lockout_temperature: 65.0,
                               plant_supply_water_temperature_control: false,
                               plant_supply_water_temperature_control_strategy: 'outdoor_air',
                               hwsp_at_oat_low: 120.0,
                               hw_oat_low: 55.0,
                               hwsp_at_oat_high: 80.0,
                               hw_oat_high: 70.0,
                               chwsp_at_oat_low: 70.0,
                               chw_oat_low: 65.0,
                               chwsp_at_oat_high: 55.0,
                               chw_oat_high: 75.0,
                               radiant_type: 'floor',
                               radiant_temperature_control_type: 'SurfaceFaceTemperature',
                               radiant_setpoint_control_type: 'ZeroFlowPower',
                               include_carpet: true,
                               carpet_thickness_in: 0.25,
                               control_strategy: 'proportional_control',
                               use_zone_occupancy_for_control: true,
                               occupied_percentage_threshold: 0.10,
                               model_occ_hr_start: 6.0,
                               model_occ_hr_end: 18.0,
                               proportional_gain: 0.3,
                               switch_over_time: 24.0,
                               slab_sp_at_oat_low: 73,
                               slab_oat_low: 65,
                               slab_sp_at_oat_high: 68,
                               slab_oat_high: 80,
                               radiant_availability_type: 'precool',
                               radiant_lockout: false,
                               radiant_lockout_start_time: 12.0,
                               radiant_lockout_end_time: 20.0)

  # create internal source constructions for surfaces
  OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "Replacing #{radiant_type} constructions with new radiant slab constructions.")

  # determine construction insulation thickness by climate zone
  climate_zone = OpenstudioStandards::Weather.model_get_climate_zone(model)
  if climate_zone.empty?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', 'Unable to determine climate zone for radiant slab insulation determination.  Defaulting to climate zone 5, R-20 insulation, 110F heating design supply water temperature.')
    cz_mult = 4
    radiant_htg_dsgn_sup_wtr_temp_f = 110
  else
    climate_zone_set = model_find_climate_zone_set(model, climate_zone)
    case climate_zone_set.gsub('ClimateZone ', '').gsub('CEC T24 ', '')
    when '1'
      cz_mult = 2
      radiant_htg_dsgn_sup_wtr_temp_f = 90
    when '2', '2A', '2B', 'CEC15'
      cz_mult = 2
      radiant_htg_dsgn_sup_wtr_temp_f = 100
    when '3', '3A', '3B', '3C', 'CEC3', 'CEC4', 'CEC5', 'CEC6', 'CEC7', 'CEC8', 'CEC9', 'CEC10', 'CEC11', 'CEC12', 'CEC13', 'CEC14'
      cz_mult = 3
      radiant_htg_dsgn_sup_wtr_temp_f = 100
    when '4', '4A', '4B', '4C', 'CEC1', 'CEC2'
      cz_mult = 4
      radiant_htg_dsgn_sup_wtr_temp_f = 100
    when '5', '5A', '5B', '5C', 'CEC16'
      cz_mult = 4
      radiant_htg_dsgn_sup_wtr_temp_f = 110
    when '6', '6A', '6B'
      cz_mult = 4
      radiant_htg_dsgn_sup_wtr_temp_f = 120
    when '7', '8'
      cz_mult = 5
      radiant_htg_dsgn_sup_wtr_temp_f = 120
    else # default to 4
      cz_mult = 4
      radiant_htg_dsgn_sup_wtr_temp_f = 100
    end
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "Based on model climate zone #{climate_zone} using R-#{(cz_mult * 5).to_i} slab insulation, R-#{((cz_mult + 1) * 5).to_i} exterior floor insulation, R-#{((cz_mult + 1) * 2 * 5).to_i} exterior roof insulation, and #{radiant_htg_dsgn_sup_wtr_temp_f}F heating design supply water temperature.")
  end

  # create materials
  mat_concrete_3_5in = OpenStudio::Model::StandardOpaqueMaterial.new(model, 'MediumRough', 0.0889, 2.31, 2322, 832)
  mat_concrete_3_5in.setName('Radiant Slab Concrete - 3.5 in.')

  mat_concrete_1_5in = OpenStudio::Model::StandardOpaqueMaterial.new(model, 'MediumRough', 0.0381, 2.31, 2322, 832)
  mat_concrete_1_5in.setName('Radiant Slab Concrete - 1.5 in')

  mat_refl_roof_membrane = model.getStandardOpaqueMaterialByName('Roof Membrane - Highly Reflective')
  if mat_refl_roof_membrane.is_initialized
    mat_refl_roof_membrane = model.getStandardOpaqueMaterialByName('Roof Membrane - Highly Reflective').get
  else
    mat_refl_roof_membrane = OpenStudio::Model::StandardOpaqueMaterial.new(model, 'VeryRough', 0.0095, 0.16, 1121.29, 1460)
    mat_refl_roof_membrane.setThermalAbsorptance(0.75)
    mat_refl_roof_membrane.setSolarAbsorptance(0.45)
    mat_refl_roof_membrane.setVisibleAbsorptance(0.7)
    mat_refl_roof_membrane.setName('Roof Membrane - Highly Reflective')
  end

  if include_carpet
    carpet_thickness_m = OpenStudio.convert(carpet_thickness_in / 12.0, 'ft', 'm').get
    conductivity_si = 0.06
    conductivity_ip = OpenStudio.convert(conductivity_si, 'W/m*K', 'Btu*in/hr*ft^2*R').get
    r_value_ip = carpet_thickness_in * (1 / conductivity_ip)
    mat_thin_carpet_tile = OpenStudio::Model::StandardOpaqueMaterial.new(model, 'MediumRough', carpet_thickness_m, conductivity_si, 288, 1380)
    mat_thin_carpet_tile.setThermalAbsorptance(0.9)
    mat_thin_carpet_tile.setSolarAbsorptance(0.7)
    mat_thin_carpet_tile.setVisibleAbsorptance(0.8)
    mat_thin_carpet_tile.setName("Radiant Slab Thin Carpet Tile R-#{r_value_ip.round(2)}")
  end

  # set exterior slab insulation thickness based on climate zone
  slab_insulation_thickness_m = 0.0254 * cz_mult
  mat_slab_insulation = OpenStudio::Model::StandardOpaqueMaterial.new(model, 'Rough', slab_insulation_thickness_m, 0.02, 56.06, 1210)
  mat_slab_insulation.setName("Radiant Ground Slab Insulation - #{cz_mult} in.")

  ext_insulation_thickness_m = 0.0254 * (cz_mult + 1)
  mat_ext_insulation = OpenStudio::Model::StandardOpaqueMaterial.new(model, 'Rough', ext_insulation_thickness_m, 0.02, 56.06, 1210)
  mat_ext_insulation.setName("Radiant Exterior Slab Insulation - #{cz_mult + 1} in.")

  roof_insulation_thickness_m = 0.0254 * (cz_mult + 1) * 2
  mat_roof_insulation = OpenStudio::Model::StandardOpaqueMaterial.new(model, 'Rough', roof_insulation_thickness_m, 0.02, 56.06, 1210)
  mat_roof_insulation.setName("Radiant Exterior Ceiling Insulation - #{(cz_mult + 1) * 2} in.")

  # create radiant internal source constructions
  OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', 'New constructions exclude the metal deck, as high thermal diffusivity materials cause errors in EnergyPlus internal source construction calculations.')

  layers = []
  layers << mat_slab_insulation
  layers << mat_concrete_3_5in
  layers << mat_concrete_1_5in
  layers << mat_thin_carpet_tile if include_carpet
  radiant_ground_slab_construction = OpenStudio::Model::ConstructionWithInternalSource.new(layers)
  radiant_ground_slab_construction.setName('Radiant Ground Slab Construction')
  radiant_ground_slab_construction.setSourcePresentAfterLayerNumber(2)
  radiant_ground_slab_construction.setTemperatureCalculationRequestedAfterLayerNumber(3)
  radiant_ground_slab_construction.setTubeSpacing(0.2286) # 9 inches

  layers = []
  layers << mat_ext_insulation
  layers << mat_concrete_3_5in
  layers << mat_concrete_1_5in
  layers << mat_thin_carpet_tile if include_carpet
  radiant_exterior_slab_construction = OpenStudio::Model::ConstructionWithInternalSource.new(layers)
  radiant_exterior_slab_construction.setName('Radiant Exterior Slab Construction')
  radiant_exterior_slab_construction.setSourcePresentAfterLayerNumber(2)
  radiant_exterior_slab_construction.setTemperatureCalculationRequestedAfterLayerNumber(3)
  radiant_exterior_slab_construction.setTubeSpacing(0.2286) # 9 inches

  layers = []
  layers << mat_concrete_3_5in
  layers << mat_concrete_1_5in
  layers << mat_thin_carpet_tile if include_carpet
  radiant_interior_floor_slab_construction = OpenStudio::Model::ConstructionWithInternalSource.new(layers)
  radiant_interior_floor_slab_construction.setName('Radiant Interior Floor Slab Construction')
  radiant_interior_floor_slab_construction.setSourcePresentAfterLayerNumber(1)
  radiant_interior_floor_slab_construction.setTemperatureCalculationRequestedAfterLayerNumber(1)
  radiant_interior_floor_slab_construction.setTubeSpacing(0.2286) # 9 inches

  # create reversed interior floor construction
  rev_radiant_interior_floor_slab_construction = OpenStudio::Model::ConstructionWithInternalSource.new(layers.reverse)
  rev_radiant_interior_floor_slab_construction.setName('Radiant Interior Floor Slab Construction - Reversed')
  rev_radiant_interior_floor_slab_construction.setSourcePresentAfterLayerNumber(layers.length - 1)
  rev_radiant_interior_floor_slab_construction.setTemperatureCalculationRequestedAfterLayerNumber(layers.length - 1)
  rev_radiant_interior_floor_slab_construction.setTubeSpacing(0.2286) # 9 inches

  layers = []
  layers << mat_thin_carpet_tile if include_carpet
  layers << mat_concrete_3_5in
  layers << mat_concrete_1_5in
  radiant_interior_ceiling_slab_construction = OpenStudio::Model::ConstructionWithInternalSource.new(layers)
  radiant_interior_ceiling_slab_construction.setName('Radiant Interior Ceiling Slab Construction')
  slab_src_loc = include_carpet ? 2 : 1
  radiant_interior_ceiling_slab_construction.setSourcePresentAfterLayerNumber(slab_src_loc)
  radiant_interior_ceiling_slab_construction.setTemperatureCalculationRequestedAfterLayerNumber(slab_src_loc)
  radiant_interior_ceiling_slab_construction.setTubeSpacing(0.2286) # 9 inches

  # create reversed interior ceiling construction
  rev_radiant_interior_ceiling_slab_construction = OpenStudio::Model::ConstructionWithInternalSource.new(layers.reverse)
  rev_radiant_interior_ceiling_slab_construction.setName('Radiant Interior Ceiling Slab Construction - Reversed')
  rev_radiant_interior_ceiling_slab_construction.setSourcePresentAfterLayerNumber(layers.length - slab_src_loc)
  rev_radiant_interior_ceiling_slab_construction.setTemperatureCalculationRequestedAfterLayerNumber(layers.length - slab_src_loc)
  rev_radiant_interior_ceiling_slab_construction.setTubeSpacing(0.2286) # 9 inches

  layers = []
  layers << mat_refl_roof_membrane
  layers << mat_roof_insulation
  layers << mat_concrete_3_5in
  layers << mat_concrete_1_5in
  radiant_ceiling_slab_construction = OpenStudio::Model::ConstructionWithInternalSource.new(layers)
  radiant_ceiling_slab_construction.setName('Radiant Exterior Ceiling Slab Construction')
  radiant_ceiling_slab_construction.setSourcePresentAfterLayerNumber(3)
  radiant_ceiling_slab_construction.setTemperatureCalculationRequestedAfterLayerNumber(4)
  radiant_ceiling_slab_construction.setTubeSpacing(0.2286) # 9 inches

  # adjust hot and chilled water loop temperatures and set new setpoint schedules
  radiant_htg_dsgn_sup_wtr_temp_delt_r = 10.0
  radiant_htg_dsgn_sup_wtr_temp_c = OpenStudio.convert(radiant_htg_dsgn_sup_wtr_temp_f, 'F', 'C').get
  radiant_htg_dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(radiant_htg_dsgn_sup_wtr_temp_delt_r, 'R', 'K').get
  hot_water_loop.sizingPlant.setDesignLoopExitTemperature(radiant_htg_dsgn_sup_wtr_temp_c)
  hot_water_loop.sizingPlant.setLoopDesignTemperatureDifference(radiant_htg_dsgn_sup_wtr_temp_delt_k)
  hw_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                radiant_htg_dsgn_sup_wtr_temp_c,
                                                                                name: "#{hot_water_loop.name} Temp - #{radiant_htg_dsgn_sup_wtr_temp_f.round(0)}F",
                                                                                schedule_type_limit: 'Temperature')
  hot_water_loop.supplyOutletNode.setpointManagers.each do |spm|
    if spm.to_SetpointManagerScheduled.is_initialized
      spm = spm.to_SetpointManagerScheduled.get
      spm.setSchedule(hw_temp_sch)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Changing hot water loop setpoint for '#{hot_water_loop.name}' to '#{hw_temp_sch.name}' to account for the radiant system.")
    end
  end

  radiant_clg_dsgn_sup_wtr_temp_f = 55.0
  radiant_clg_dsgn_sup_wtr_temp_delt_r = 5.0
  radiant_clg_dsgn_sup_wtr_temp_c = OpenStudio.convert(radiant_clg_dsgn_sup_wtr_temp_f, 'F', 'C').get
  radiant_clg_dsgn_sup_wtr_temp_delt_k = OpenStudio.convert(radiant_clg_dsgn_sup_wtr_temp_delt_r, 'R', 'K').get
  chilled_water_loop.sizingPlant.setDesignLoopExitTemperature(radiant_clg_dsgn_sup_wtr_temp_c)
  chilled_water_loop.sizingPlant.setLoopDesignTemperatureDifference(radiant_clg_dsgn_sup_wtr_temp_delt_k)
  chw_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                 radiant_clg_dsgn_sup_wtr_temp_c,
                                                                                 name: "#{chilled_water_loop.name} Temp - #{radiant_clg_dsgn_sup_wtr_temp_f.round(0)}F",
                                                                                 schedule_type_limit: 'Temperature')
  chilled_water_loop.supplyOutletNode.setpointManagers.each do |spm|
    if spm.to_SetpointManagerScheduled.is_initialized
      spm = spm.to_SetpointManagerScheduled.get
      spm.setSchedule(chw_temp_sch)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Changing chilled water loop setpoint for '#{chilled_water_loop.name}' to '#{chw_temp_sch.name}' to account for the radiant system.")
    end
  end

  # default temperature controls for radiant system
  zn_radiant_htg_dsgn_temp_f = 68.0
  zn_radiant_htg_dsgn_temp_c = OpenStudio.convert(zn_radiant_htg_dsgn_temp_f, 'F', 'C').get
  zn_radiant_clg_dsgn_temp_f = 74.0
  zn_radiant_clg_dsgn_temp_c = OpenStudio.convert(zn_radiant_clg_dsgn_temp_f, 'F', 'C').get

  htg_control_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                         zn_radiant_htg_dsgn_temp_c,
                                                                                         name: "Zone Radiant Loop Heating Threshold Temperature Schedule - #{zn_radiant_htg_dsgn_temp_f.round(0)}F",
                                                                                         schedule_type_limit: 'Temperature')
  clg_control_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                         zn_radiant_clg_dsgn_temp_c,
                                                                                         name: "Zone Radiant Loop Cooling Threshold Temperature Schedule - #{zn_radiant_clg_dsgn_temp_f.round(0)}F",
                                                                                         schedule_type_limit: 'Temperature')
  throttling_range_f = 4.0 # 2 degF on either side of control temperature
  throttling_range_c = OpenStudio.convert(throttling_range_f, 'F', 'C').get

  # create preset availability schedule for radiant loop
  radiant_avail_sch = OpenStudio::Model::ScheduleRuleset.new(model)
  radiant_avail_sch.setName('Radiant System Availability Schedule')

  unless radiant_lockout
    case radiant_availability_type.downcase
    when 'all_day'
      start_hour = 24
      start_minute = 0
      end_hour = 24
      end_minute = 0
    when 'afternoon_shutoff'
      start_hour = 15
      start_minute = 0
      end_hour = 22
      end_minute = 0
    when 'precool'
      start_hour = 10
      start_minute = 0
      end_hour = 22
      end_minute = 0
    when 'occupancy'
      start_hour = model_occ_hr_end.to_i
      start_minute = ((model_occ_hr_end % 1) * 60).to_i
      end_hour = model_occ_hr_start.to_i
      end_minute = ((model_occ_hr_start % 1) * 60).to_i
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "Unsupported radiant availability preset '#{radiant_availability_type}'. Defaulting to all day operation.")
      start_hour = 24
      start_minute = 0
      end_hour = 24
      end_minute = 0
    end
  end

  # create custom availability schedule for radiant loop
  if radiant_lockout
    start_hour = radiant_lockout_start_time.to_i
    start_minute = ((radiant_lockout_start_time % 1) * 60).to_i
    end_hour = radiant_lockout_end_time.to_i
    end_minute = ((radiant_lockout_end_time % 1) * 60).to_i
  end

  # create availability schedules
  if end_hour > start_hour
    radiant_avail_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, start_hour, start_minute, 0), 1.0)
    radiant_avail_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, end_hour, end_minute, 0), 0.0)
    radiant_avail_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 1.0) if end_hour < 24
  elsif start_hour > end_hour
    radiant_avail_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, end_hour, end_minute, 0), 0.0)
    radiant_avail_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, start_hour, start_minute, 0), 1.0)
    radiant_avail_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0.0) if start_hour < 24
  else
    radiant_avail_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 1.0)
  end

  # convert to a two-pipe system if required
  if two_pipe_system
    model_two_pipe_loop(model, hot_water_loop, chilled_water_loop,
                        control_strategy: two_pipe_control_strategy,
                        lockout_temperature: two_pipe_lockout_temperature,
                        thermal_zones: thermal_zones)
  end

  # add supply water temperature control if enabled
  if plant_supply_water_temperature_control
    # add supply water temperature for heating plant loop
    model_add_plant_supply_water_temperature_control(model, hot_water_loop,
                                                     control_strategy: plant_supply_water_temperature_control_strategy,
                                                     sp_at_oat_low: hwsp_at_oat_low,
                                                     oat_low: hw_oat_low,
                                                     sp_at_oat_high: hwsp_at_oat_high,
                                                     oat_high: hw_oat_high,
                                                     thermal_zones: thermal_zones)

    # add supply water temperature for cooling plant loop
    model_add_plant_supply_water_temperature_control(model, chilled_water_loop,
                                                     control_strategy: plant_supply_water_temperature_control_strategy,
                                                     sp_at_oat_low: chwsp_at_oat_low,
                                                     oat_low: chw_oat_low,
                                                     sp_at_oat_high: chwsp_at_oat_high,
                                                     oat_high: chw_oat_high,
                                                     thermal_zones: thermal_zones)
  end

  # make a low temperature radiant loop for each zone
  radiant_loops = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding radiant loop for #{zone.name}.")
    if zone.name.to_s.include? ':'
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Thermal zone '#{zone.name}' has a restricted character ':' in the name and will not work with some EMS and output reporting objects. Please rename the zone.")
    end

    # create radiant coils
    if hot_water_loop
      radiant_loop_htg_coil = OpenStudio::Model::CoilHeatingLowTempRadiantVarFlow.new(model, htg_control_temp_sch)
      radiant_loop_htg_coil.setName("#{zone.name} Radiant Loop Heating Coil")
      radiant_loop_htg_coil.setHeatingControlThrottlingRange(throttling_range_c)
      hot_water_loop.addDemandBranchForComponent(radiant_loop_htg_coil)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'Radiant loops require a hot water loop, but none was provided.')
    end

    if chilled_water_loop
      radiant_loop_clg_coil = OpenStudio::Model::CoilCoolingLowTempRadiantVarFlow.new(model, clg_control_temp_sch)
      radiant_loop_clg_coil.setName("#{zone.name} Radiant Loop Cooling Coil")
      radiant_loop_clg_coil.setCoolingControlThrottlingRange(throttling_range_c)
      chilled_water_loop.addDemandBranchForComponent(radiant_loop_clg_coil)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'Radiant loops require a chilled water loop, but none was provided.')
    end

    radiant_loop = OpenStudio::Model::ZoneHVACLowTempRadiantVarFlow.new(model,
                                                                        radiant_avail_sch,
                                                                        radiant_loop_htg_coil,
                                                                        radiant_loop_clg_coil)

    # assign internal source construction to floors in zone
    zone.spaces.each do |space|
      space.surfaces.each do |surface|
        if radiant_type == 'floor'
          if surface.surfaceType == 'Floor'
            if surface.outsideBoundaryCondition.include? 'Ground'
              surface.setConstruction(radiant_ground_slab_construction)
            elsif surface.outsideBoundaryCondition == 'Outdoors'
              surface.setConstruction(radiant_exterior_slab_construction)
            else # interior floor
              surface.setConstruction(radiant_interior_floor_slab_construction)

              # also assign construction to adjacent surface
              if surface.adjacentSurface.is_initialized
                adjacent_surface = surface.adjacentSurface.get
                adjacent_surface.setConstruction(rev_radiant_interior_floor_slab_construction)
              end
            end
          end
        elsif radiant_type == 'ceiling'
          if surface.surfaceType == 'RoofCeiling'
            if surface.outsideBoundaryCondition == 'Outdoors'
              surface.setConstruction(radiant_ceiling_slab_construction)
            else # interior ceiling
              surface.setConstruction(radiant_interior_ceiling_slab_construction)

              # also assign construction to adjacent surface
              if surface.adjacentSurface.is_initialized
                adjacent_surface = surface.adjacentSurface.get
                adjacent_surface.setConstruction(rev_radiant_interior_ceiling_slab_construction)
              end
            end
          end
        end
      end
    end

    # radiant loop surfaces
    radiant_loop.setName("#{zone.name} Radiant Loop")
    if radiant_type == 'floor'
      radiant_loop.setRadiantSurfaceType('Floors')
    elsif radiant_type == 'ceiling'
      radiant_loop.setRadiantSurfaceType('Ceilings')
    end

    # radiant loop layout details
    radiant_loop.setHydronicTubingInsideDiameter(0.015875) # 5/8 in. ID, 3/4 in. OD
    # @todo include a method to determine tubing length in the zone
    # loop_length = 7*zone.floorArea
    # radiant_loop.setHydronicTubingLength()
    radiant_loop.setNumberofCircuits('CalculateFromCircuitLength')
    radiant_loop.setCircuitLength(106.7)

    # radiant loop temperature controls
    radiant_loop.setTemperatureControlType(radiant_temperature_control_type)

    # radiant loop setpoint temperature response
    radiant_loop.setSetpointControlType(radiant_setpoint_control_type)
    radiant_loop.addToThermalZone(zone)
    radiant_loops << radiant_loop

    # rename nodes before adding EMS code
    rename_plant_loop_nodes(model)

    # set radiant loop controls
    case control_strategy.downcase
    when 'proportional_control'
      # slab setpoint varies based on previous day zone conditions
      model_add_radiant_proportional_controls(model, zone, radiant_loop,
                                              radiant_temperature_control_type: radiant_temperature_control_type,
                                              use_zone_occupancy_for_control: use_zone_occupancy_for_control,
                                              occupied_percentage_threshold: occupied_percentage_threshold,
                                              model_occ_hr_start: model_occ_hr_start,
                                              model_occ_hr_end: model_occ_hr_end,
                                              proportional_gain: proportional_gain,
                                              switch_over_time: switch_over_time)
    when 'oa_based_control'
      # slab setpoint varies based on outdoor weather
      model_add_radiant_basic_controls(model, zone, radiant_loop,
                                       radiant_temperature_control_type: radiant_temperature_control_type,
                                       slab_setpoint_oa_control: true,
                                       switch_over_time: switch_over_time,
                                       slab_sp_at_oat_low: slab_sp_at_oat_low,
                                       slab_oat_low: slab_oat_low,
                                       slab_sp_at_oat_high: slab_sp_at_oat_high,
                                       slab_oat_high: slab_oat_high)
    when 'constant_control'
      # constant slab setpoint control
      model_add_radiant_basic_controls(model, zone, radiant_loop,
                                       radiant_temperature_control_type: radiant_temperature_control_type,
                                       slab_setpoint_oa_control: false,
                                       switch_over_time: switch_over_time,
                                       slab_sp_at_oat_low: slab_sp_at_oat_low,
                                       slab_oat_low: slab_oat_low,
                                       slab_sp_at_oat_high: slab_sp_at_oat_high,
                                       slab_oat_high: slab_oat_high)
    end
  end
  return radiant_loops
end
model_add_material(model, material_name) click to toggle source

Create a material from the openstudio standards dataset.

@param model [OpenStudio::Model::Model] OpenStudio model object @param material_name [String] name of the material @return [OpenStudio::Model::Material] material object

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2887
def model_add_material(model, material_name)
  # First check model and return material if it already exists
  model.getMaterials.sort.each do |material|
    if material.name.get.to_s == material_name
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Already added material: #{material_name}")
      return material
    end
  end

  # Get the object data
  # For Simple Glazing materials:
  # Attempt to get properties from the name of the material
  material_type = nil
  if material_name.downcase.include?('simple glazing')
    material_type = 'SimpleGlazing'
    u_factor = nil
    shgc = nil
    vt = nil
    material_name.split.each_with_index do |item, i|
      prop_value = material_name.split[i + 1].to_f
      if item == 'U'
        unless u_factor.nil?
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Multiple U-Factor values have been identified for #{material_name}: previous = #{u_factor}, new = #{prop_value}. Please check the material name. New U-Factor will be used.")
        end
        u_factor = prop_value
      elsif item == 'SHGC'
        unless shgc.nil?
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Multiple SHGC values have been identified for #{material_name}: previous = #{shgc}, new = #{prop_value}. Please check the material name. New SHGC will be used.")
        end
        shgc = prop_value
      elsif item == 'VT'
        unless vt.nil?
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Multiple VT values have been identified for #{material_name}: previous = #{vt}, new = #{prop_value}. Please check the material name. New SHGC will be used.")
        end
        vt = prop_value
      end
    end
    if u_factor.nil? && shgc.nil? && vt.nil?
      material_type = nil
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Properties of the simple glazing material named #{material_name} could not be identified from its name.")
    else
      if u_factor.nil?
        u_factor = 1.23
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Cannot find the U-Factor for the simple glazing material named #{material_name}, a default value of 1.23 is used.")
      end
      if shgc.nil?
        shgc = 0.61
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Cannot find the SHGC for the simple glazing material named #{material_name}, a default value of 0.61 is used.")
      end
      if vt.nil?
        vt = 0.81
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Cannot find the VT for the simple glazing material named #{material_name}, a default value of 0.81 is used.")
      end
    end
  end
  # If no properties could be found or the material
  # is not of the simple glazing type, search the database
  if material_type.nil?
    data = model_find_object(standards_data['materials'], 'name' => material_name)
    unless data
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Cannot find data for material: #{material_name}, will not be created.")
      return OpenStudio::Model::OptionalMaterial.new
    end
    material_type = data['material_type']
  end

  material = nil
  if material_type == 'StandardOpaqueMaterial'
    material = OpenStudio::Model::StandardOpaqueMaterial.new(model)
    material.setName(material_name)

    material.setRoughness(data['roughness'].to_s)
    material.setThickness(OpenStudio.convert(data['thickness'].to_f, 'in', 'm').get)
    material.setThermalConductivity(OpenStudio.convert(data['conductivity'].to_f, 'Btu*in/hr*ft^2*R', 'W/m*K').get)
    material.setDensity(OpenStudio.convert(data['density'].to_f, 'lb/ft^3', 'kg/m^3').get)
    material.setSpecificHeat(OpenStudio.convert(data['specific_heat'].to_f, 'Btu/lb*R', 'J/kg*K').get)
    material.setThermalAbsorptance(data['thermal_absorptance'].to_f)
    material.setSolarAbsorptance(data['solar_absorptance'].to_f)
    material.setVisibleAbsorptance(data['visible_absorptance'].to_f)

  elsif material_type == 'MasslessOpaqueMaterial'
    material = OpenStudio::Model::MasslessOpaqueMaterial.new(model)
    material.setName(material_name)
    material.setThermalResistance(OpenStudio.convert(data['resistance'].to_f, 'hr*ft^2*R/Btu', 'm^2*K/W').get)
    material.setThermalConductivity(OpenStudio.convert(data['conductivity'].to_f, 'Btu*in/hr*ft^2*R', 'W/m*K').get)
    material.setThermalAbsorptance(data['thermal_absorptance'].to_f)
    material.setSolarAbsorptance(data['solar_absorptance'].to_f)
    material.setVisibleAbsorptance(data['visible_absorptance'].to_f)

  elsif material_type == 'AirGap'
    material = OpenStudio::Model::AirGap.new(model)
    material.setName(material_name)

    material.setThermalResistance(OpenStudio.convert(data['resistance'].to_f, 'hr*ft^2*R/Btu*in', 'm*K/W').get)

  elsif material_type == 'Gas'
    material = OpenStudio::Model::Gas.new(model)
    material.setName(material_name)

    material.setThickness(OpenStudio.convert(data['thickness'].to_f, 'in', 'm').get)
    material.setGasType(data['gas_type'].to_s)

  elsif material_type == 'SimpleGlazing'
    material = OpenStudio::Model::SimpleGlazing.new(model)
    material.setName(material_name)

    material.setUFactor(OpenStudio.convert(u_factor.to_f, 'Btu/hr*ft^2*R', 'W/m^2*K').get)
    material.setSolarHeatGainCoefficient(shgc.to_f)
    material.setVisibleTransmittance(vt.to_f)

  elsif material_type == 'StandardGlazing'
    material = OpenStudio::Model::StandardGlazing.new(model)
    material.setName(material_name)

    material.setOpticalDataType(data['optical_data_type'].to_s)
    material.setThickness(OpenStudio.convert(data['thickness'].to_f, 'in', 'm').get)
    material.setSolarTransmittanceatNormalIncidence(data['solar_transmittance_at_normal_incidence'].to_f)
    material.setFrontSideSolarReflectanceatNormalIncidence(data['front_side_solar_reflectance_at_normal_incidence'].to_f)
    material.setBackSideSolarReflectanceatNormalIncidence(data['back_side_solar_reflectance_at_normal_incidence'].to_f)
    material.setVisibleTransmittanceatNormalIncidence(data['visible_transmittance_at_normal_incidence'].to_f)
    material.setFrontSideVisibleReflectanceatNormalIncidence(data['front_side_visible_reflectance_at_normal_incidence'].to_f)
    material.setBackSideVisibleReflectanceatNormalIncidence(data['back_side_visible_reflectance_at_normal_incidence'].to_f)
    material.setInfraredTransmittanceatNormalIncidence(data['infrared_transmittance_at_normal_incidence'].to_f)
    material.setFrontSideInfraredHemisphericalEmissivity(data['front_side_infrared_hemispherical_emissivity'].to_f)
    material.setBackSideInfraredHemisphericalEmissivity(data['back_side_infrared_hemispherical_emissivity'].to_f)
    material.setThermalConductivity(OpenStudio.convert(data['conductivity'].to_f, 'Btu*in/hr*ft^2*R', 'W/m*K').get)
    material.setDirtCorrectionFactorforSolarandVisibleTransmittance(data['dirt_correction_factor_for_solar_and_visible_transmittance'].to_f)
    if /true/i =~ data['solar_diffusing'].to_s
      material.setSolarDiffusing(true)
    else
      material.setSolarDiffusing(false)
    end

  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Unknown material type #{material_type}, cannot add material called #{material_name}.")
    exit
  end

  return material
end
model_add_minisplit_hp(model, thermal_zones, cooling_type: 'Two Speed DX AC', heating_type: 'Single Speed DX', hvac_op_sch: nil) click to toggle source

Creates a minisplit heatpump system for each zone and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param cooling_type [String] valid choices are Two Speed DX AC, Single Speed DX AC, Single Speed Heat Pump @param heating_type [String] valid choices are Single Speed DX @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @return [OpenStudio::Model::AirLoopHVAC] the resulting split AC air loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 3903
def model_add_minisplit_hp(model,
                           thermal_zones,
                           cooling_type: 'Two Speed DX AC',
                           heating_type: 'Single Speed DX',
                           hvac_op_sch: nil)

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # default design temperatures across all air loops
  dsgn_temps = standard_design_sizing_temperatures

  # adjusted temperatures for minisplit
  dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
  dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['htg_dsgn_sup_air_temp_f'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_f']
  dsgn_temps['htg_dsgn_sup_air_temp_c'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_c']

  minisplit_hps = []
  thermal_zones.each do |zone|
    air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
    air_loop.setName("#{zone.name} Minisplit Heat Pump")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding minisplit HP for #{zone.name}.")

    # default design settings used across all air loops
    sizing_system = adjust_sizing_system(air_loop, dsgn_temps, sizing_option: 'NonCoincident')
    sizing_system.setAllOutdoorAirinCooling(false)
    sizing_system.setAllOutdoorAirinHeating(false)

    # create heating coil
    case heating_type
    when 'Single Speed DX'
      htg_coil = create_coil_heating_dx_single_speed(model,
                                                     name: "#{air_loop.name} Heating Coil",
                                                     type: 'Residential Minisplit HP')
      htg_coil.setMinimumOutdoorDryBulbTemperatureforCompressorOperation(OpenStudio.convert(-30.0, 'F', 'C').get)
      htg_coil.setMaximumOutdoorDryBulbTemperatureforDefrostOperation(OpenStudio.convert(40.0, 'F', 'C').get)
      htg_coil.setCrankcaseHeaterCapacity(0)
      htg_coil.setDefrostStrategy('ReverseCycle')
      htg_coil.setDefrostControl('OnDemand')
      htg_coil.resetDefrostTimePeriodFraction
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "No heating coil type selected for minisplit HP for #{zone.name}.")
      htg_coil = nil
    end

    # create backup heating coil
    supplemental_htg_coil = create_coil_heating_electric(model,
                                                         name: "#{air_loop.name} Electric Backup Htg Coil")

    # create cooling coil
    case cooling_type
    when 'Two Speed DX AC'
      clg_coil = create_coil_cooling_dx_two_speed(model,
                                                  name: "#{air_loop.name} 2spd DX AC Clg Coil",
                                                  type: 'Residential Minisplit HP')
    when 'Single Speed DX AC'
      clg_coil = create_coil_cooling_dx_single_speed(model,
                                                     name: "#{air_loop.name} 1spd DX AC Clg Coil", type: 'Split AC')
    when 'Single Speed Heat Pump'
      clg_coil = create_coil_cooling_dx_single_speed(model,
                                                     name: "#{air_loop.name} 1spd DX HP Clg Coil", type: 'Heat Pump')
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "No cooling coil type selected for minisplit HP for #{zone.name}.")
      clg_coil = nil
    end

    # create fan
    fan = create_fan_by_name(model,
                             'Minisplit_HP_Fan',
                             fan_name: "#{air_loop.name} Fan",
                             end_use_subcategory: 'Minisplit HP Fans')
    fan.setAvailabilitySchedule(hvac_op_sch)

    # create unitary system (holds the coils and fan)
    unitary = OpenStudio::Model::AirLoopHVACUnitarySystem.new(model)
    unitary.setName("#{air_loop.name} Unitary System")
    unitary.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
    unitary.setMaximumSupplyAirTemperature(OpenStudio.convert(200.0, 'F', 'C').get)
    unitary.setMaximumOutdoorDryBulbTemperatureforSupplementalHeaterOperation(OpenStudio.convert(40.0, 'F', 'C').get)
    unitary.setControllingZoneorThermostatLocation(zone)
    unitary.addToNode(air_loop.supplyInletNode)
    unitary.setSupplyAirFlowRateWhenNoCoolingorHeatingisRequired(0.0)

    # attach the coils and fan
    unitary.setHeatingCoil(htg_coil) if htg_coil
    unitary.setCoolingCoil(clg_coil) if clg_coil
    unitary.setSupplementalHeatingCoil(supplemental_htg_coil) if supplemental_htg_coil
    unitary.setSupplyFan(fan)
    unitary.setFanPlacement('BlowThrough')
    unitary.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)

    # create a diffuser
    diffuser = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)
    diffuser.setName(" #{zone.name} Direct Air")
    air_loop.multiAddBranchForZone(zone, diffuser.to_HVACComponent.get)

    minisplit_hps << air_loop
  end

  return minisplit_hps
end
model_add_piping_losses_to_swh_system(model, swh_loop, circulating, pipe_insulation_thickness: 0, floor_area_served: 465, number_of_stories: 1, air_temp_surrounding_piping: 21.1111) click to toggle source

Adds insulated 0.75in copper piping to the model. For circulating systems, assume length of piping is proportional to the area and number of stories in the building. For non-circulating systems, assume that the water heaters are close to the point of use. Assume that piping is located in a zone

@param model [OpenStudio::Model::Model] OpenStudio model object @param swh_loop [OpenStudio::Model::PlantLoop] the service water heating loop @param floor_area_served [Double] the area of building served by the service water heating loop, in m^2 @param number_of_stories [Integer] the number of stories served by the service water heating loop @param pipe_insulation_thickness [Double] the thickness of the pipe insulation, in m. Use 0 for no insulation @param circulating [Boolean] use true for circulating systems, false for non-circulating systems @param air_temp_surrounding_piping [Double] the temperature of the air surrounding the piping, in C. @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ServiceWaterHeating.rb, line 1149
def model_add_piping_losses_to_swh_system(model,
                                          swh_loop,
                                          circulating,
                                          pipe_insulation_thickness: 0,
                                          floor_area_served: 465,
                                          number_of_stories: 1,
                                          air_temp_surrounding_piping: 21.1111)

  # Estimate pipe length
  if circulating
    # For circulating systems, get pipe length based on the size of the building.
    # Formula from A.3.1 PrototypeModelEnhancements_2014_0.pdf
    floor_area_ft2 = OpenStudio.convert(floor_area_served, 'm^2', 'ft^2').get
    pipe_length_ft = 2.0 * (Math.sqrt(floor_area_ft2 / number_of_stories) + (10.0 * (number_of_stories - 1.0)))
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Pipe length #{pipe_length_ft.round}ft = 2.0 * ( (#{floor_area_ft2.round}ft2 / #{number_of_stories} stories)^0.5 + (10.0ft * (#{number_of_stories} stories - 1.0) ) )")
  else
    # For non-circulating systems, assume water heater is close to point of use
    pipe_length_ft = 20.0
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Pipe length #{pipe_length_ft.round}ft. For non-circulating systems, assume water heater is close to point of use.")
  end

  # For systems whose water heater object represents multiple pieces
  # of equipment, multiply the piping length by the number of pieces of equipment.
  swh_loop.supplyComponents('OS_WaterHeater_Mixed'.to_IddObjectType).each do |sc|
    next unless sc.to_WaterHeaterMixed.is_initialized

    water_heater = sc.to_WaterHeaterMixed.get

    # get number of water heaters
    if water_heater.additionalProperties.getFeatureAsInteger('component_quantity').is_initialized
      comp_qty = water_heater.additionalProperties.getFeatureAsInteger('component_quantity').get
    else
      comp_qty = 1
    end

    if comp_qty > 1
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Piping length has been multiplied by #{comp_qty}X because #{water_heater.name} represents #{comp_qty} pieces of equipment.")
      pipe_length_ft *= comp_qty
      break
    end
  end

  # Service water heating piping heat loss scheduled air temperature
  swh_piping_air_temp_c = air_temp_surrounding_piping
  swh_piping_air_temp_f = OpenStudio.convert(swh_piping_air_temp_c, 'C', 'F').get
  swh_piping_air_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                            swh_piping_air_temp_c,
                                                                                            name: "#{swh_loop.name} Piping Air Temp - #{swh_piping_air_temp_f.round}F",
                                                                                            schedule_type_limit: 'Temperature')

  # Service water heating piping heat loss scheduled air velocity
  swh_piping_air_velocity_m_per_s = 0.3
  swh_piping_air_velocity_mph = OpenStudio.convert(swh_piping_air_velocity_m_per_s, 'm/s', 'mile/hr').get
  swh_piping_air_velocity_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                swh_piping_air_velocity_m_per_s,
                                                                                                name: "#{swh_loop.name} Piping Air Velocity - #{swh_piping_air_velocity_mph.round(2)}mph",
                                                                                                schedule_type_limit: 'Dimensionless')

  # Material for 3/4in type L (heavy duty) copper pipe
  copper_pipe = OpenStudio::Model::StandardOpaqueMaterial.new(model)
  copper_pipe.setName('Copper pipe 0.75in type L')
  copper_pipe.setRoughness('Smooth')
  copper_pipe.setThickness(OpenStudio.convert(0.045, 'in', 'm').get)
  copper_pipe.setThermalConductivity(386.0)
  copper_pipe.setDensity(OpenStudio.convert(556, 'lb/ft^3', 'kg/m^3').get)
  copper_pipe.setSpecificHeat(OpenStudio.convert(0.092, 'Btu/lb*R', 'J/kg*K').get)
  copper_pipe.setThermalAbsorptance(0.9) # @todo find reference for property
  copper_pipe.setSolarAbsorptance(0.7) # @todo find reference for property
  copper_pipe.setVisibleAbsorptance(0.7) # @todo find reference for property

  # Construction for pipe
  pipe_construction = OpenStudio::Model::Construction.new(model)

  # Add insulation material to insulated pipe
  if pipe_insulation_thickness > 0
    # Material for fiberglass insulation
    # R-value from Owens-Corning 1/2in fiberglass pipe insulation
    # https://www.grainger.com/product/OWENS-CORNING-1-2-Thick-40PP22
    # but modified until simulated heat loss = 17.7 Btu/hr/ft of pipe with 140F water and 70F air
    pipe_insulation_thickness_in = OpenStudio.convert(pipe_insulation_thickness, 'm', 'in').get
    insulation = OpenStudio::Model::StandardOpaqueMaterial.new(model)
    insulation.setName("Fiberglass batt #{pipe_insulation_thickness_in.round(2)}in")
    insulation.setRoughness('Smooth')
    insulation.setThickness(OpenStudio.convert(pipe_insulation_thickness_in, 'in', 'm').get)
    insulation.setThermalConductivity(OpenStudio.convert(0.46, 'Btu*in/hr*ft^2*R', 'W/m*K').get)
    insulation.setDensity(OpenStudio.convert(0.7, 'lb/ft^3', 'kg/m^3').get)
    insulation.setSpecificHeat(OpenStudio.convert(0.2, 'Btu/lb*R', 'J/kg*K').get)
    insulation.setThermalAbsorptance(0.9) # Irrelevant for Pipe:Indoor; no radiation model is used
    insulation.setSolarAbsorptance(0.7) # Irrelevant for Pipe:Indoor; no radiation model is used
    insulation.setVisibleAbsorptance(0.7) # Irrelevant for Pipe:Indoor; no radiation model is used

    pipe_construction.setName("Copper pipe 0.75in type L with #{pipe_insulation_thickness_in.round(2)}in fiberglass batt")
    pipe_construction.setLayers([insulation, copper_pipe])
  else
    pipe_construction.setName('Uninsulated copper pipe 0.75in type L')
    pipe_construction.setLayers([copper_pipe])
  end

  heat_loss_pipe = OpenStudio::Model::PipeIndoor.new(model)
  heat_loss_pipe.setName("#{swh_loop.name} Pipe #{pipe_length_ft}ft")
  heat_loss_pipe.setEnvironmentType('Schedule')
  # @todoschedule type registry error for this setter
  # heat_loss_pipe.setAmbientTemperatureSchedule(swh_piping_air_temp_sch)
  heat_loss_pipe.setPointer(7, swh_piping_air_temp_sch.handle)
  # @todo schedule type registry error for this setter
  # heat_loss_pipe.setAmbientAirVelocitySchedule(model.alwaysOffDiscreteSchedule)
  heat_loss_pipe.setPointer(8, swh_piping_air_velocity_sch.handle)
  heat_loss_pipe.setConstruction(pipe_construction)
  heat_loss_pipe.setPipeInsideDiameter(OpenStudio.convert(0.785, 'in', 'm').get)
  heat_loss_pipe.setPipeLength(OpenStudio.convert(pipe_length_ft, 'ft', 'm').get)

  heat_loss_pipe.addToNode(swh_loop.demandInletNode)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Added #{pipe_length_ft.round}ft of #{pipe_construction.name} losing heat to #{swh_piping_air_temp_f.round}F air to #{swh_loop.name}.")
  return true
end
model_add_plant_supply_water_temperature_control(model, plant_water_loop, control_strategy: 'outdoor_air', sp_at_oat_low: nil, oat_low: nil, sp_at_oat_high: nil, oat_high: nil, thermal_zones: []) click to toggle source

Adds supply water temperature control on specified plant water loops.

@param model [OpenStudio::Model::Model] OpenStudio model object @param plant_water_loop [OpenStudio::Model::PlantLoop] plant water loop to add supply water temperature control. @param control_strategy [String] Method to determine how to control the plant’s supply water temperature (swt).

'outdoor_air' - The plant's swt will be proportional to the outdoor air based on the next 4 parameters.
'zone_demand' - The plant's swt will be determined by preponderance of zone demand.
  Requires thermal_zone defined.

@param sp_at_oat_low [Double] supply water temperature setpoint, in F, at the outdoor low temperature. @param oat_low [Double] outdoor drybulb air temperature, in F, for low setpoint. @param sp_at_oat_high [Double] supply water temperature setpoint, in F, at the outdoor high temperature. @param oat_high [Double] outdoor drybulb air temperature, in F, for high setpoint. @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6289
  def model_add_plant_supply_water_temperature_control(model, plant_water_loop,
                                                       control_strategy: 'outdoor_air',
                                                       sp_at_oat_low: nil,
                                                       oat_low: nil,
                                                       sp_at_oat_high: nil,
                                                       oat_high: nil,
                                                       thermal_zones: [])

    # check that all required temperature parameters are defined
    if sp_at_oat_low.nil? && oat_low.nil? && sp_at_oat_high.nil? && oat_high.nil?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'At least one of the required temperature parameter is nil.')
    end

    # remove any existing setpoint manager on the plant water loop
    exisiting_setpoint_managers = plant_water_loop.loopTemperatureSetpointNode.setpointManagers
    exisiting_setpoint_managers.each(&:disconnect)

    if control_strategy == 'outdoor_air'
      # create supply water temperature setpoint managers for plant based on outdoor temperature
      water_loop_setpoint_manager = OpenStudio::Model::SetpointManagerOutdoorAirReset.new(model)
      water_loop_setpoint_manager.setName("#{plant_water_loop.name.get} Supply Water Temperature Control")
      water_loop_setpoint_manager.setControlVariable('Temperature')
      water_loop_setpoint_manager.setSetpointatOutdoorLowTemperature(OpenStudio.convert(sp_at_oat_low, 'F', 'C').get)
      water_loop_setpoint_manager.setOutdoorLowTemperature(OpenStudio.convert(oat_low, 'F', 'C').get)
      water_loop_setpoint_manager.setSetpointatOutdoorHighTemperature(OpenStudio.convert(sp_at_oat_high, 'F', 'C').get)
      water_loop_setpoint_manager.setOutdoorHighTemperature(OpenStudio.convert(oat_high, 'F', 'C').get)
      water_loop_setpoint_manager.addToNode(plant_water_loop.loopTemperatureSetpointNode)
    else
      # create supply water temperature setpoint managers for plant based on zone heating and cooling demand
      # check if zone heat and cool requests program exists, if not create it
      determine_zone_cooling_needs_prg = model.getEnergyManagementSystemProgramByName('Determine_Zone_Cooling_Needs')
      determine_zone_heating_needs_prg = model.getEnergyManagementSystemProgramByName('Determine_Zone_Heating_Needs')
      unless determine_zone_cooling_needs_prg.is_initialized && determine_zone_heating_needs_prg.is_initialized
        model_add_zone_heat_cool_request_count_program(model, thermal_zones)
      end

      plant_water_loop_name = ems_friendly_name(plant_water_loop.name)

      if plant_water_loop.componentType.valueName == 'Heating'
        swt_upper_limit = sp_at_oat_low.nil? ? OpenStudio.convert(120, 'F', 'C').get : OpenStudio.convert(sp_at_oat_low, 'F', 'C').get
        swt_lower_limit = sp_at_oat_high.nil? ? OpenStudio.convert(80, 'F', 'C').get : OpenStudio.convert(sp_at_oat_high, 'F', 'C').get
        swt_init = OpenStudio.convert(100, 'F', 'C').get
        zone_demand_var = 'Zone_Heating_Ratio'
        swt_inc_condition_var = '> 0.70'
        swt_dec_condition_var = '< 0.30'
      else
        swt_upper_limit = sp_at_oat_low.nil? ? OpenStudio.convert(70, 'F', 'C').get : OpenStudio.convert(sp_at_oat_low, 'F', 'C').get
        swt_lower_limit = sp_at_oat_high.nil? ? OpenStudio.convert(55, 'F', 'C').get : OpenStudio.convert(sp_at_oat_high, 'F', 'C').get
        swt_init = OpenStudio.convert(62, 'F', 'C').get
        zone_demand_var = 'Zone_Cooling_Ratio'
        swt_inc_condition_var = '< 0.30'
        swt_dec_condition_var = '> 0.70'
      end

      # plant loop supply water control actuator
      sch_plant_swt_ctrl = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                           swt_init,
                                                                                           name: "#{plant_water_loop_name}_Sch_Supply_Water_Temperature",
                                                                                           schedule_type_limit: 'Temperature')

      cmd_plant_water_ctrl = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_plant_swt_ctrl,
                                                                                   'Schedule:Year',
                                                                                   'Schedule Value')
      cmd_plant_water_ctrl.setName("#{plant_water_loop_name}_supply_water_ctrl")

      # create plant loop setpoint manager
      water_loop_setpoint_manager = OpenStudio::Model::SetpointManagerScheduled.new(model,
                                                                                    sch_plant_swt_ctrl)
      water_loop_setpoint_manager.setName("#{plant_water_loop.name.get} Supply Water Temperature Control")
      water_loop_setpoint_manager.setControlVariable('Temperature')
      water_loop_setpoint_manager.addToNode(plant_water_loop.loopTemperatureSetpointNode)

      # add uninitialized variables into constant program
      set_constant_values_prg_body = <<-EMS
        SET #{plant_water_loop_name}_supply_water_ctrl = #{swt_init}
      EMS

      set_constant_values_prg = model.getEnergyManagementSystemProgramByName('Set_Plant_Constant_Values')
      if set_constant_values_prg.is_initialized
        set_constant_values_prg = set_constant_values_prg.get
        set_constant_values_prg.addLine(set_constant_values_prg_body)
      else
        set_constant_values_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
        set_constant_values_prg.setName('Set_Plant_Constant_Values')
        set_constant_values_prg.setBody(set_constant_values_prg_body)
      end

      # program for supply water temperature control in the plot
      determine_plant_swt_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
      determine_plant_swt_prg.setName("Determine_#{plant_water_loop_name}_Supply_Water_Temperature")
      determine_plant_swt_prg_body = <<-EMS
        SET SWT_Increase = 1,
        SET SWT_Decrease = 1,
        SET SWT_upper_limit = #{swt_upper_limit},
        SET SWT_lower_limit = #{swt_lower_limit},
        IF #{zone_demand_var} #{swt_inc_condition_var} && (@Mod CurrentTime 1) == 0,
          SET #{plant_water_loop_name}_supply_water_ctrl = #{plant_water_loop_name}_supply_water_ctrl + SWT_Increase,
        ELSEIF #{zone_demand_var} #{swt_dec_condition_var} && (@Mod CurrentTime 1) == 0,
          SET #{plant_water_loop_name}_supply_water_ctrl = #{plant_water_loop_name}_supply_water_ctrl - SWT_Decrease,
        ELSE,
          SET #{plant_water_loop_name}_supply_water_ctrl = #{plant_water_loop_name}_supply_water_ctrl,
        ENDIF,
        IF #{plant_water_loop_name}_supply_water_ctrl > SWT_upper_limit,
          SET #{plant_water_loop_name}_supply_water_ctrl = SWT_upper_limit
        ENDIF,
        IF #{plant_water_loop_name}_supply_water_ctrl < SWT_lower_limit,
          SET #{plant_water_loop_name}_supply_water_ctrl = SWT_lower_limit
        ENDIF
      EMS
      determine_plant_swt_prg.setBody(determine_plant_swt_prg_body)

      # create EMS program manager objects
      programs_at_beginning_of_timestep = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
      programs_at_beginning_of_timestep.setName("#{plant_water_loop_name}_Demand_Based_Supply_Water_Temperature_At_Beginning_Of_Timestep")
      programs_at_beginning_of_timestep.setCallingPoint('BeginTimestepBeforePredictor')
      programs_at_beginning_of_timestep.addProgram(determine_plant_swt_prg)

      initialize_constant_parameters = model.getEnergyManagementSystemProgramCallingManagerByName('Initialize_Constant_Parameters')
      if initialize_constant_parameters.is_initialized
        initialize_constant_parameters = initialize_constant_parameters.get
        # add program if it does not exist in manager
        existing_program_names = initialize_constant_parameters.programs.collect { |prg| prg.name.get.downcase }
        unless existing_program_names.include? set_constant_values_prg.name.get.downcase
          initialize_constant_parameters.addProgram(set_constant_values_prg)
        end
      else
        initialize_constant_parameters = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
        initialize_constant_parameters.setName('Initialize_Constant_Parameters')
        initialize_constant_parameters.setCallingPoint('BeginNewEnvironment')
        initialize_constant_parameters.addProgram(set_constant_values_prg)
      end

      initialize_constant_parameters_after_warmup = model.getEnergyManagementSystemProgramCallingManagerByName('Initialize_Constant_Parameters_After_Warmup')
      if initialize_constant_parameters_after_warmup.is_initialized
        initialize_constant_parameters_after_warmup = initialize_constant_parameters_after_warmup.get
        # add program if it does not exist in manager
        existing_program_names = initialize_constant_parameters_after_warmup.programs.collect { |prg| prg.name.get.downcase }
        unless existing_program_names.include? set_constant_values_prg.name.get.downcase
          initialize_constant_parameters_after_warmup.addProgram(set_constant_values_prg)
        end
      else
        initialize_constant_parameters_after_warmup = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
        initialize_constant_parameters_after_warmup.setName('Initialize_Constant_Parameters_After_Warmup')
        initialize_constant_parameters_after_warmup.setCallingPoint('AfterNewEnvironmentWarmUpIsComplete')
        initialize_constant_parameters_after_warmup.addProgram(set_constant_values_prg)
      end
    end
  end
model_add_prm_baseline_system(model, system_type, main_heat_fuel, zone_heat_fuel, cool_fuel, zones, zone_fan_scheds) click to toggle source

Add the specified baseline system type to the specified zones based on the specified template. For some multi-zone system types, the standards require identifying zones whose loads or schedules are outliers and putting these systems on separate single-zone systems. This method does that.

@param model [OpenStudio::Model::Model] OpenStudio model object @param system_type [String] The system type. Valid choices are PTHP, PTAC, PSZ_AC, PSZ_HP, PVAV_Reheat,

PVAV_PFP_Boxes, VAV_Reheat, VAV_PFP_Boxes, Gas_Furnace, Electric_Furnace,
which are also returned by the method OpenStudio::Model::Model.prm_baseline_system_type.

@param main_heat_fuel [String] main heating fuel. Valid choices are Electricity, NaturalGas, DistrictHeating, DistrictHeatingWater, DistrictHeatingSteam @param zone_heat_fuel [String] zone heating/reheat fuel. Valid choices are Electricity, NaturalGas, DistrictHeating, DistrictHeatingWater, DistrictHeatingSteam @param cool_fuel [String] cooling fuel. Valid choices are Electricity, DistrictCooling @param zones [Array<OpenStudio::Model::ThermalZone>] an array of zones @return [Boolean] returns true if successful, false if not @todo Add 90.1-2013 systems 11-13

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1396
def model_add_prm_baseline_system(model, system_type, main_heat_fuel, zone_heat_fuel, cool_fuel, zones, zone_fan_scheds)
  case system_type
    when 'PTAC' # System 1
      unless zones.empty?
        # Retrieve the existing hot water loop or add a new one if necessary.
        hot_water_loop = nil
        hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                           model.getPlantLoopByName('Hot Water Loop').get
                         else
                           model_add_hw_loop(model, main_heat_fuel)
                         end

        # Add a hot water PTAC to each zone
        model_add_ptac(model,
                       zones,
                       cooling_type: 'Single Speed DX AC',
                       heating_type: 'Water',
                       hot_water_loop: hot_water_loop,
                       fan_type: 'ConstantVolume')
      end

    when 'PTHP' # System 2
      unless zones.empty?
        # add an air-source packaged terminal heat pump with electric supplemental heat to each zone.
        model_add_pthp(model,
                       zones,
                       fan_type: 'ConstantVolume')
      end

    when 'PSZ_AC' # System 3
      unless zones.empty?
        heating_type = 'Gas'
        # if district heating
        hot_water_loop = nil
        if main_heat_fuel.include?('DistrictHeating')
          heating_type = 'Water'
          hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                             model.getPlantLoopByName('Hot Water Loop').get
                           else
                             model_add_hw_loop(model, main_heat_fuel)
                           end
        end

        cooling_type = 'Single Speed DX AC'
        # If district cooling
        chilled_water_loop = nil
        if cool_fuel == 'DistrictCooling'
          cooling_type = 'Water'
          chilled_water_loop = if model.getPlantLoopByName('Chilled Water Loop').is_initialized
                                 model.getPlantLoopByName('Chilled Water Loop').get
                               else
                                 model_add_chw_loop(model,
                                                    cooling_fuel: cool_fuel,
                                                    chw_pumping_type: 'const_pri')
                               end
        end

        # Add a PSZ-AC to each zone
        model_add_psz_ac(model,
                         zones,
                         cooling_type: cooling_type,
                         chilled_water_loop: chilled_water_loop,
                         heating_type: heating_type,
                         supplemental_heating_type: 'Gas',
                         hot_water_loop: hot_water_loop,
                         fan_location: 'DrawThrough',
                         fan_type: 'ConstantVolume')
      end

    when 'PSZ_HP' # System 4
      unless zones.empty?
        # Add an air-source packaged single zone heat pump with electric supplemental heat to each zone.
        model_add_psz_ac(model,
                         zones,
                         system_name: 'PSZ-HP',
                         cooling_type: 'Single Speed Heat Pump',
                         heating_type: 'Single Speed Heat Pump',
                         supplemental_heating_type: 'Electric',
                         fan_location: 'DrawThrough',
                         fan_type: 'ConstantVolume')
      end

    when 'PVAV_Reheat' # System 5
      # Retrieve the existing hot water loop or add a new one if necessary.
      hot_water_loop = nil
      hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                         model.getPlantLoopByName('Hot Water Loop').get
                       else
                         model_add_hw_loop(model, main_heat_fuel)
                       end

      # If district cooling
      chilled_water_loop = nil
      if cool_fuel == 'DistrictCooling'
        chilled_water_loop = if model.getPlantLoopByName('Chilled Water Loop').is_initialized
                               model.getPlantLoopByName('Chilled Water Loop').get
                             else
                               model_add_chw_loop(model,
                                                  cooling_fuel: cool_fuel,
                                                  chw_pumping_type: 'const_pri')
                             end
      end

      # If electric zone heat
      electric_reheat = false
      if zone_heat_fuel == 'Electricity'
        electric_reheat = true
      end

      # Group zones by story
      story_zone_lists = OpenstudioStandards::Geometry.model_group_thermal_zones_by_building_story(model, zones)

      # For the array of zones on each story,
      # separate the primary zones from the secondary zones.
      # Add the baseline system type to the primary zones
      # and add the suplemental system type to the secondary zones.
      story_zone_lists.each do |story_group|
        # Differentiate primary and secondary zones
        pri_sec_zone_lists = model_differentiate_primary_secondary_thermal_zones(model, story_group, zone_fan_scheds)
        pri_zones = pri_sec_zone_lists['primary']
        sec_zones = pri_sec_zone_lists['secondary']
        zone_op_hrs = pri_sec_zone_lists['zone_op_hrs']

        # Add a PVAV with Reheat for the primary zones
        stories = []
        story_group[0].spaces.each do |space|
          min_z = OpenstudioStandards::Geometry.building_story_get_minimum_height(space.buildingStory.get)
          stories << [space.buildingStory.get.name.get, min_z]
        end
        story_name = stories.min_by { |nm, z| z }[0]
        system_name = "#{story_name} PVAV_Reheat (Sys5)"

        # If and only if there are primary zones to attach to the loop
        # counter example: floor with only one elevator machine room that get classified as sec_zones
        unless pri_zones.empty?
          air_loop = model_add_pvav(model,
                                    pri_zones,
                                    system_name: system_name,
                                    hot_water_loop: hot_water_loop,
                                    chilled_water_loop: chilled_water_loop,
                                    electric_reheat: electric_reheat)
          model_system_outdoor_air_sizing_vrp_method(air_loop)
          air_loop_hvac_apply_vav_damper_action(air_loop)
          model_create_multizone_fan_schedule(model, zone_op_hrs, pri_zones, system_name)
        end

        # Add a PSZ_AC for each secondary zone
        unless sec_zones.empty?
          model_add_prm_baseline_system(model, 'PSZ_AC', main_heat_fuel, zone_heat_fuel, cool_fuel, sec_zones, zone_fan_scheds)
        end
      end

    when 'PVAV_PFP_Boxes' # System 6
      # If district cooling
      chilled_water_loop = nil
      if cool_fuel == 'DistrictCooling'
        chilled_water_loop = if model.getPlantLoopByName('Chilled Water Loop').is_initialized
                               model.getPlantLoopByName('Chilled Water Loop').get
                             else
                               model_add_chw_loop(model,
                                                  cooling_fuel: cool_fuel,
                                                  chw_pumping_type: 'const_pri')
                             end
      end

      # Group zones by story
      story_zone_lists = OpenstudioStandards::Geometry.model_group_thermal_zones_by_building_story(model, zones)

      # For the array of zones on each story,
      # separate the primary zones from the secondary zones.
      # Add the baseline system type to the primary zones
      # and add the suplemental system type to the secondary zones.
      story_zone_lists.each do |story_group|
        # Differentiate primary and secondary zones
        pri_sec_zone_lists = model_differentiate_primary_secondary_thermal_zones(model, story_group, zone_fan_scheds)
        pri_zones = pri_sec_zone_lists['primary']
        sec_zones = pri_sec_zone_lists['secondary']
        zone_op_hrs = pri_sec_zone_lists['zone_op_hrs']

        # Add an VAV for the primary zones
        stories = []
        story_group[0].spaces.each do |space|
          min_z = OpenstudioStandards::Geometry.building_story_get_minimum_height(space.buildingStory.get)
          stories << [space.buildingStory.get.name.get, min_z]
        end
        story_name = stories.min_by { |nm, z| z }[0]
        system_name = "#{story_name} PVAV_PFP_Boxes (Sys6)"
        # If and only if there are primary zones to attach to the loop
        unless pri_zones.empty?
          model_add_pvav_pfp_boxes(model,
                                   pri_zones,
                                   system_name: system_name,
                                   chilled_water_loop: chilled_water_loop,
                                   fan_efficiency: 0.62,
                                   fan_motor_efficiency: 0.9,
                                   fan_pressure_rise: 4.0)
          model_create_multizone_fan_schedule(model, zone_op_hrs, pri_zones, system_name)
        end
        # Add a PSZ_HP for each secondary zone
        unless sec_zones.empty?
          model_add_prm_baseline_system(model, 'PSZ_HP', main_heat_fuel, zone_heat_fuel, cool_fuel, sec_zones, zone_fan_scheds)
        end
      end

    when 'VAV_Reheat' # System 7
      # Retrieve the existing hot water loop or add a new one if necessary.
      hot_water_loop = nil
      hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                         model.getPlantLoopByName('Hot Water Loop').get
                       else
                         model_add_hw_loop(model, main_heat_fuel)
                       end

      # Retrieve the existing chilled water loop or add a new one if necessary.
      chilled_water_loop = nil
      if model.getPlantLoopByName('Chilled Water Loop').is_initialized
        chilled_water_loop = model.getPlantLoopByName('Chilled Water Loop').get
      else
        if cool_fuel == 'DistrictCooling'
          chilled_water_loop = model_add_chw_loop(model,
                                                  cooling_fuel: cool_fuel,
                                                  chw_pumping_type: 'const_pri')
        else
          fan_type = model_cw_loop_cooling_tower_fan_type(model)
          condenser_water_loop = model_add_cw_loop(model,
                                                   cooling_tower_type: 'Open Cooling Tower',
                                                   cooling_tower_fan_type: 'Propeller or Axial',
                                                   cooling_tower_capacity_control: fan_type,
                                                   number_of_cells_per_tower: 1,
                                                   number_cooling_towers: 1)
          chilled_water_loop = model_add_chw_loop(model,
                                                  chw_pumping_type: 'const_pri_var_sec',
                                                  chiller_cooling_type: 'WaterCooled',
                                                  chiller_compressor_type: 'Rotary Screw',
                                                  condenser_water_loop: condenser_water_loop)
        end
      end

      # If electric zone heat
      reheat_type = 'Water'
      if zone_heat_fuel == 'Electricity'
        reheat_type = 'Electricity'
      end

      # Group zones by story
      story_zone_lists = OpenstudioStandards::Geometry.model_group_thermal_zones_by_building_story(model, zones)

      # For the array of zones on each story, separate the primary zones from the secondary zones.
      # Add the baseline system type to the primary zones and add the suplemental system type to the secondary zones.
      story_zone_lists.each do |story_group|
        # The OpenstudioStandards::Geometry.model_group_thermal_zones_by_building_story(model)  NO LONGER returns empty lists when a given floor doesn't have any of the zones
        # So NO need to filter it out otherwise you get an error undefined method `spaces' for nil:NilClass
        # next if zones.empty?

        # Differentiate primary and secondary zones
        pri_sec_zone_lists = model_differentiate_primary_secondary_thermal_zones(model, story_group, zone_fan_scheds)
        pri_zones = pri_sec_zone_lists['primary']
        sec_zones = pri_sec_zone_lists['secondary']
        zone_op_hrs = pri_sec_zone_lists['zone_op_hrs']

        # Add a VAV for the primary zones
        stories = []
        story_group[0].spaces.each do |space|
          min_z = OpenstudioStandards::Geometry.building_story_get_minimum_height(space.buildingStory.get)
          stories << [space.buildingStory.get.name.get, min_z]
        end
        story_name = stories.min_by { |nm, z| z }[0]
        system_name = "#{story_name} VAV_Reheat (Sys7)"

        # If and only if there are primary zones to attach to the loop
        # counter example: floor with only one elevator machine room that get classified as sec_zones
        unless pri_zones.empty?
          # if the loop configuration is primary / secondary loop
          if chilled_water_loop.additionalProperties.hasFeature('secondary_loop_name')
            chilled_water_loop = model.getPlantLoopByName(chilled_water_loop.additionalProperties.getFeatureAsString('secondary_loop_name').get).get
          end
          air_loop = model_add_vav_reheat(model,
                                          pri_zones,
                                          system_name: system_name,
                                          reheat_type: reheat_type,
                                          hot_water_loop: hot_water_loop,
                                          chilled_water_loop: chilled_water_loop,
                                          fan_efficiency: 0.62,
                                          fan_motor_efficiency: 0.9,
                                          fan_pressure_rise: 4.0)
          model_system_outdoor_air_sizing_vrp_method(air_loop)
          air_loop_hvac_apply_vav_damper_action(air_loop)
          model_create_multizone_fan_schedule(model, zone_op_hrs, pri_zones, system_name)
        end

        # Add a PSZ_AC for each secondary zone
        unless sec_zones.empty?
          model_add_prm_baseline_system(model, 'PSZ_AC', main_heat_fuel, zone_heat_fuel, cool_fuel, sec_zones, zone_fan_scheds)
        end
      end

    when 'VAV_PFP_Boxes' # System 8
      # Retrieve the existing chilled water loop or add a new one if necessary.
      chilled_water_loop = nil
      if model.getPlantLoopByName('Chilled Water Loop').is_initialized
        chilled_water_loop = model.getPlantLoopByName('Chilled Water Loop').get
      else
        if cool_fuel == 'DistrictCooling'
          chilled_water_loop = model_add_chw_loop(model,
                                                  cooling_fuel: cool_fuel,
                                                  chw_pumping_type: 'const_pri')
        else
          fan_type = model_cw_loop_cooling_tower_fan_type(model)
          condenser_water_loop = model_add_cw_loop(model,
                                                   cooling_tower_type: 'Open Cooling Tower',
                                                   cooling_tower_fan_type: 'Propeller or Axial',
                                                   cooling_tower_capacity_control: fan_type,
                                                   number_of_cells_per_tower: 1,
                                                   number_cooling_towers: 1)
          chilled_water_loop = model_add_chw_loop(model,
                                                  chw_pumping_type: 'const_pri_var_sec',
                                                  chiller_cooling_type: 'WaterCooled',
                                                  chiller_compressor_type: 'Rotary Screw',
                                                  condenser_water_loop: condenser_water_loop)
        end
      end

      # Group zones by story
      story_zone_lists = OpenstudioStandards::Geometry.model_group_thermal_zones_by_building_story(model, zones)

      # For the array of zones on each story,
      # separate the primary zones from the secondary zones.
      # Add the baseline system type to the primary zones
      # and add the suplemental system type to the secondary zones.
      story_zone_lists.each do |story_group|
        # Differentiate primary and secondary zones
        pri_sec_zone_lists = model_differentiate_primary_secondary_thermal_zones(model, story_group, zone_fan_scheds)
        pri_zones = pri_sec_zone_lists['primary']
        sec_zones = pri_sec_zone_lists['secondary']
        zone_op_hrs = pri_sec_zone_lists['zone_op_hrs']

        # Add an VAV for the primary zones
        stories = []
        story_group[0].spaces.each do |space|
          min_z = OpenstudioStandards::Geometry.building_story_get_minimum_height(space.buildingStory.get)
          stories << [space.buildingStory.get.name.get, min_z]
        end
        story_name = stories.min_by { |nm, z| z }[0]
        system_name = "#{story_name} VAV_PFP_Boxes (Sys8)"
        # If and only if there are primary zones to attach to the loop
        unless pri_zones.empty?
          if chilled_water_loop.additionalProperties.hasFeature('secondary_loop_name')
            chilled_water_loop = model.getPlantLoopByName(chilled_water_loop.additionalProperties.getFeatureAsString('secondary_loop_name').get).get
          end
          model_add_vav_pfp_boxes(model,
                                  pri_zones,
                                  system_name: system_name,
                                  chilled_water_loop: chilled_water_loop,
                                  fan_efficiency: 0.62,
                                  fan_motor_efficiency: 0.9,
                                  fan_pressure_rise: 4.0)

          model_create_multizone_fan_schedule(model, zone_op_hrs, pri_zones, system_name)
        end
        # Add a PSZ_HP for each secondary zone
        unless sec_zones.empty?
          model_add_prm_baseline_system(model, 'PSZ_HP', main_heat_fuel, zone_heat_fuel, cool_fuel, sec_zones, zone_fan_scheds)
        end
      end

    when 'Gas_Furnace' # System 9
      unless zones.empty?
        # If district heating
        hot_water_loop = nil
        if main_heat_fuel.include?('DistrictHeating')
          hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                             model.getPlantLoopByName('Hot Water Loop').get
                           else
                             model_add_hw_loop(model, main_heat_fuel)
                           end
        end
        # Add a System 9 - Gas Unit Heater to each zone
        model_add_unitheater(model,
                             zones,
                             fan_control_type: 'ConstantVolume',
                             fan_pressure_rise: 0.2,
                             heating_type: main_heat_fuel,
                             hot_water_loop: hot_water_loop)
      end

    when 'Electric_Furnace' # System 10
      unless zones.empty?
        # Add a System 10 - Electric Unit Heater to each zone
        model_add_unitheater(model,
                             zones,
                             fan_control_type: 'ConstantVolume',
                             fan_pressure_rise: 0.2,
                             heating_type: main_heat_fuel)
      end

    when 'SZ_CV' # System 12 (gas or district heat) or System 13 (electric resistance heat)
      unless zones.empty?
        hot_water_loop = nil
        if zone_heat_fuel.include?('DistrictHeating') || zone_heat_fuel == 'NaturalGas'
          heating_type = 'Water'
          hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                             model.getPlantLoopByName('Hot Water Loop').get
                           else
                             model_add_hw_loop(model, main_heat_fuel)
                           end
        else
          # If no hot water loop is defined, heat will default to electric resistance
          heating_type = 'Electric'
        end
        cooling_type = 'Water'
        chilled_water_loop = if model.getPlantLoopByName('Chilled Water Loop').is_initialized
                               model.getPlantLoopByName('Chilled Water Loop').get
                             else
                               model_add_chw_loop(model,
                                                  cooling_fuel: cool_fuel,
                                                  chw_pumping_type: 'const_pri')
                             end

        model_add_four_pipe_fan_coil(model,
                                     zones,
                                     chilled_water_loop,
                                     hot_water_loop: hot_water_loop,
                                     ventilation: true,
                                     capacity_control_method: 'ConstantVolume')
      end
    when 'SZ_VAV' # System 11, chilled water, heating type varies by climate zone
      unless zones.empty?
        # htg type
        climate_zone = OpenstudioStandards::Weather.model_get_climate_zone(model)
        case climate_zone
          when 'ASHRAE 169-2006-0A',
            'ASHRAE 169-2006-0B',
            'ASHRAE 169-2006-1A',
            'ASHRAE 169-2006-1B',
            'ASHRAE 169-2006-2A',
            'ASHRAE 169-2006-2B',
            'ASHRAE 169-2013-0A',
            'ASHRAE 169-2013-0B',
            'ASHRAE 169-2013-1A',
            'ASHRAE 169-2013-1B',
            'ASHRAE 169-2013-2A',
            'ASHRAE 169-2013-2B'
            heating_type = 'Electric'
            hot_water_loop = nil
          else
            hot_water_loop = if model.getPlantLoopByName('Hot Water Loop').is_initialized
                               model.getPlantLoopByName('Hot Water Loop').get
                             else
                               hot_water_loop = model_add_hw_loop(model, main_heat_fuel)
                             end
            heating_type = 'Water'
        end

        # clg type
        chilled_water_loop = if model.getPlantLoopByName('Chilled Water Loop').is_initialized
                               model.getPlantLoopByName('Chilled Water Loop').get
                             else
                               chilled_water_loop = model_add_chw_loop(model, chw_pumping_type: 'const_pri')
                             end

        model_add_psz_vav(model,
                          zones,
                          heating_type: heating_type,
                          cooling_type: 'WaterCooled',
                          supplemental_heating_type: nil,
                          hvac_op_sch: nil,
                          fan_type: 'PSZ_VAV_System_Fan',
                          oa_damper_sch: nil,
                          hot_water_loop: hot_water_loop,
                          chilled_water_loop: chilled_water_loop,
                          minimum_volume_setpoint: 0.5)
      end
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "System type #{system_type} is not a valid choice, nothing will be added to the model.")
      return false
  end
  return true
end
model_add_prm_elevators(model) click to toggle source

Function to add baseline elevators based on user data Only applicable to stable baseline @param model [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4729
def model_add_prm_elevators(model)
  return false
end
model_add_psz_ac(model, thermal_zones, system_name: nil, cooling_type: 'Single Speed DX AC', chilled_water_loop: nil, hot_water_loop: nil, heating_type: nil, supplemental_heating_type: nil, fan_location: 'DrawThrough', fan_type: 'ConstantVolume', hvac_op_sch: nil, oa_damper_sch: nil) click to toggle source

Creates a PSZ-AC system for each zone and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param system_name [String] the name of the system, or nil in which case it will be defaulted @param cooling_type [String] valid choices are Water, Two Speed DX AC, Single Speed DX AC, Single Speed Heat Pump, Water To Air Heat Pump @param chilled_water_loop [OpenStudio::Model::PlantLoop] chilled water loop to connect cooling coil to, or nil @param hot_water_loop [OpenStudio::Model::PlantLoop] hot water loop to connect heating coil to, or nil @param heating_type [String] valid choices are NaturalGas, Electricity, Water, Single Speed Heat Pump, Water To Air Heat Pump, or nil (no heat) @param supplemental_heating_type [String] valid choices are Electricity, NaturalGas, nil (no heat) @param fan_location [String] valid choices are BlowThrough, DrawThrough @param fan_type [String] valid choices are ConstantVolume, Cycling @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [String] name of the oa damper schedule or nil in which case will be defaulted to always open @return [Array<OpenStudio::Model::AirLoopHVAC>] an array of the resulting PSZ-AC air loops

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 2715
def model_add_psz_ac(model,
                     thermal_zones,
                     system_name: nil,
                     cooling_type: 'Single Speed DX AC',
                     chilled_water_loop: nil,
                     hot_water_loop: nil,
                     heating_type: nil,
                     supplemental_heating_type: nil,
                     fan_location: 'DrawThrough',
                     fan_type: 'ConstantVolume',
                     hvac_op_sch: nil,
                     oa_damper_sch: nil)

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # create a PSZ-AC for each zone
  air_loops = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding PSZ-AC for #{zone.name}.")

    air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
    if system_name.nil?
      air_loop.setName("#{zone.name} PSZ-AC")
    else
      air_loop.setName("#{zone.name} #{system_name}")
    end

    # default design temperatures and settings used across all air loops
    dsgn_temps = standard_design_sizing_temperatures
    unless hot_water_loop.nil?
      hw_temp_c = hot_water_loop.sizingPlant.designLoopExitTemperature
      hw_delta_t_k = hot_water_loop.sizingPlant.loopDesignTemperatureDifference
    end

    # adjusted design heating temperature for psz_ac
    dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
    dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
    dsgn_temps['htg_dsgn_sup_air_temp_f'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_f']
    dsgn_temps['htg_dsgn_sup_air_temp_c'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_c']

    # default design settings used across all air loops
    sizing_system = adjust_sizing_system(air_loop, dsgn_temps, min_sys_airflow_ratio: 1.0)

    # air handler controls
    # add a setpoint manager single zone reheat to control the supply air temperature
    setpoint_mgr_single_zone_reheat = OpenStudio::Model::SetpointManagerSingleZoneReheat.new(model)
    setpoint_mgr_single_zone_reheat.setName("#{zone.name} Setpoint Manager SZ Reheat")
    setpoint_mgr_single_zone_reheat.setControlZone(zone)
    setpoint_mgr_single_zone_reheat.setMinimumSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    setpoint_mgr_single_zone_reheat.setMaximumSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    setpoint_mgr_single_zone_reheat.addToNode(air_loop.supplyOutletNode)

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])

    # create heating coil
    case heating_type
    when 'NaturalGas', 'Gas'
      htg_coil = create_coil_heating_gas(model,
                                         name: "#{air_loop.name} Gas Htg Coil")
    when 'Water'
      if hot_water_loop.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'No hot water plant loop supplied')
        return false
      end
      htg_coil = create_coil_heating_water(model,
                                           hot_water_loop,
                                           name: "#{air_loop.name} Water Htg Coil",
                                           rated_inlet_water_temperature: hw_temp_c,
                                           rated_outlet_water_temperature: (hw_temp_c - hw_delta_t_k),
                                           rated_inlet_air_temperature: dsgn_temps['prehtg_dsgn_sup_air_temp_c'],
                                           rated_outlet_air_temperature: dsgn_temps['htg_dsgn_sup_air_temp_c'])
    when 'Single Speed Heat Pump'
      htg_coil = create_coil_heating_dx_single_speed(model,
                                                     name: "#{zone.name} HP Htg Coil",
                                                     type: 'PSZ-AC',
                                                     cop: 3.3)
    when 'Water To Air Heat Pump'
      htg_coil = create_coil_heating_water_to_air_heat_pump_equation_fit(model,
                                                                         hot_water_loop,
                                                                         name: "#{air_loop.name} Water-to-Air HP Htg Coil")
    when 'Electricity', 'Electric'
      htg_coil = create_coil_heating_electric(model,
                                              name: "#{air_loop.name} Electric Htg Coil")
    else
      # zero-capacity, always-off electric heating coil
      htg_coil = create_coil_heating_electric(model,
                                              name: "#{air_loop.name} No Heat",
                                              schedule: model.alwaysOffDiscreteSchedule,
                                              nominal_capacity: 0.0)
    end

    # create supplemental heating coil
    case supplemental_heating_type
    when 'Electricity', 'Electric'
      supplemental_htg_coil = create_coil_heating_electric(model,
                                                           name: "#{air_loop.name} Electric Backup Htg Coil")
    when 'NaturalGas', 'Gas'
      supplemental_htg_coil = create_coil_heating_gas(model,
                                                      name: "#{air_loop.name} Gas Backup Htg Coil")
    else
      # Zero-capacity, always-off electric heating coil
      supplemental_htg_coil = create_coil_heating_electric(model,
                                                           name: "#{air_loop.name} No Heat",
                                                           schedule: model.alwaysOffDiscreteSchedule,
                                                           nominal_capacity: 0.0)
    end

    # create cooling coil
    case cooling_type
    when 'Water'
      if chilled_water_loop.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'No chilled water plant loop supplied')
        return false
      end
      clg_coil = create_coil_cooling_water(model,
                                           chilled_water_loop,
                                           name: "#{air_loop.name} Water Clg Coil")
    when 'Two Speed DX AC'
      clg_coil = create_coil_cooling_dx_two_speed(model,
                                                  name: "#{air_loop.name} 2spd DX AC Clg Coil")
    when 'Single Speed DX AC'
      clg_coil = create_coil_cooling_dx_single_speed(model,
                                                     name: "#{air_loop.name} 1spd DX AC Clg Coil",
                                                     type: 'PSZ-AC')
    when 'Single Speed Heat Pump'
      clg_coil = create_coil_cooling_dx_single_speed(model,
                                                     name: "#{air_loop.name} 1spd DX HP Clg Coil",
                                                     type: 'Heat Pump')
      # clg_coil.setMaximumOutdoorDryBulbTemperatureForCrankcaseHeaterOperation(OpenStudio::OptionalDouble.new(10.0))
      # clg_coil.setRatedSensibleHeatRatio(0.69)
      # clg_coil.setBasinHeaterCapacity(10)
      # clg_coil.setBasinHeaterSetpointTemperature(2.0)
    when 'Water To Air Heat Pump'
      if chilled_water_loop.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'No chilled water plant loop supplied')
        return false
      end
      clg_coil = create_coil_cooling_water_to_air_heat_pump_equation_fit(model,
                                                                         chilled_water_loop,
                                                                         name: "#{air_loop.name} Water-to-Air HP Clg Coil")
    else
      clg_coil = nil
    end

    # Use a Fan:OnOff in the unitary system object
    case fan_type
    when 'Cycling'
      fan = create_fan_by_name(model,
                               'Packaged_RTU_SZ_AC_Cycling_Fan',
                               fan_name: "#{air_loop.name} Fan")
    when 'ConstantVolume'
      fan = create_fan_by_name(model,
                               'Packaged_RTU_SZ_AC_CAV_OnOff_Fan',
                               fan_name: "#{air_loop.name} Fan")
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Invalid fan_type')
      return false
    end

    # fan location
    if fan_location.nil?
      fan_location = 'DrawThrough'
    end
    case fan_location
    when 'DrawThrough', 'BlowThrough'
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "Setting fan location for #{fan.name} to #{fan_location}.")
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Invalid fan_location #{fan_location} for fan #{fan.name}.")
      return false
    end

    # construct unitary system object
    unitary_system = OpenStudio::Model::AirLoopHVACUnitarySystem.new(model)
    unitary_system.setSupplyFan(fan) unless fan.nil?
    unitary_system.setHeatingCoil(htg_coil) unless htg_coil.nil?
    unitary_system.setCoolingCoil(clg_coil) unless clg_coil.nil?
    unitary_system.setSupplementalHeatingCoil(supplemental_htg_coil) unless supplemental_htg_coil.nil?
    unitary_system.setControllingZoneorThermostatLocation(zone)
    unitary_system.setFanPlacement(fan_location)
    unitary_system.addToNode(air_loop.supplyInletNode)

    # added logic and naming for heat pumps
    case heating_type
    when 'Water To Air Heat Pump'
      unitary_system.setMaximumOutdoorDryBulbTemperatureforSupplementalHeaterOperation(OpenStudio.convert(40.0, 'F', 'C').get)
      unitary_system.setName("#{air_loop.name} Unitary HP")
      unitary_system.setMaximumSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
      if model.version < OpenStudio::VersionString.new('3.7.0')
        unitary_system.setSupplyAirFlowRateMethodDuringCoolingOperation('SupplyAirFlowRate')
        unitary_system.setSupplyAirFlowRateMethodDuringHeatingOperation('SupplyAirFlowRate')
        unitary_system.setSupplyAirFlowRateMethodWhenNoCoolingorHeatingisRequired('SupplyAirFlowRate')
      else
        unitary_system.autosizeSupplyAirFlowRateDuringCoolingOperation
        unitary_system.autosizeSupplyAirFlowRateDuringHeatingOperation
        unitary_system.autosizeSupplyAirFlowRateWhenNoCoolingorHeatingisRequired
      end
    when 'Single Speed Heat Pump'
      unitary_system.setMaximumOutdoorDryBulbTemperatureforSupplementalHeaterOperation(OpenStudio.convert(40.0, 'F', 'C').get)
      unitary_system.setName("#{air_loop.name} Unitary HP")
    else
      unitary_system.setName("#{air_loop.name} Unitary AC")
    end

    # specify control logic
    unitary_system.setAvailabilitySchedule(hvac_op_sch)
    if fan_type == 'Cycling'
      unitary_system.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)
    else # constant volume operation
      unitary_system.setSupplyAirFanOperatingModeSchedule(hvac_op_sch)
    end

    # add the OA system
    oa_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
    oa_controller.setName("#{air_loop.name} OA System Controller")
    oa_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
    oa_controller.autosizeMinimumOutdoorAirFlowRate
    oa_controller.resetEconomizerMinimumLimitDryBulbTemperature
    oa_system = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_controller)
    oa_system.setName("#{air_loop.name} OA System")
    oa_system.addToNode(air_loop.supplyInletNode)

    # @todo enable economizer maximum fraction outdoor air schedule input
    # econ_eff_sch = model_add_schedule(model, 'RetailStandalone PSZ_Econ_MaxOAFrac_Sch')

    # set air loop availability controls and night cycle manager, after oa system added
    air_loop.setAvailabilitySchedule(hvac_op_sch)
    air_loop.setNightCycleControlType('CycleOnAny')

    if model.version < OpenStudio::VersionString.new('3.5.0')
      avail_mgr = air_loop.availabilityManager
      if avail_mgr.is_initialized
        avail_mgr = avail_mgr.get
      else
        avail_mgr = nil
      end
    else
      avail_mgr = air_loop.availabilityManagers[0]
    end

    if !avail_mgr.nil? && avail_mgr.to_AvailabilityManagerNightCycle.is_initialized
      avail_mgr = avail_mgr.to_AvailabilityManagerNightCycle.get
      avail_mgr.setCyclingRunTime(1800)
    end

    # create a diffuser and attach the zone/diffuser pair to the air loop
    diffuser = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)
    diffuser.setName("#{air_loop.name} Diffuser")
    air_loop.multiAddBranchForZone(zone, diffuser.to_HVACComponent.get)
    air_loops << air_loop
  end

  return air_loops
end
model_add_psz_vav(model, thermal_zones, system_name: nil, heating_type: nil, cooling_type: 'AirCooled', supplemental_heating_type: nil, hvac_op_sch: nil, fan_type: 'VAV_System_Fan', oa_damper_sch: nil, hot_water_loop: nil, chilled_water_loop: nil, minimum_volume_setpoint: nil) click to toggle source

Creates a packaged single zone VAV system for each zone and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param system_name [String] the name of the system, or nil in which case it will be defaulted @param heating_type [String] valid choices are NaturalGas, Electricity, Water, nil (no heat) @param supplemental_heating_type [String] valid choices are Electricity, NaturalGas, nil (no heat) @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [String] name of the oa damper schedule or nil in which case will be defaulted to always open @return [Array<OpenStudio::Model::AirLoopHVAC>] an array of the resulting PSZ-AC air loops

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 2994
def model_add_psz_vav(model,
                      thermal_zones,
                      system_name: nil,
                      heating_type: nil,
                      cooling_type: 'AirCooled',
                      supplemental_heating_type: nil,
                      hvac_op_sch: nil,
                      fan_type: 'VAV_System_Fan',
                      oa_damper_sch: nil,
                      hot_water_loop: nil,
                      chilled_water_loop: nil,
                      minimum_volume_setpoint: nil)

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # create a PSZ-VAV for each zone
  air_loops = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding PSZ-VAV for #{zone.name}.")

    air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
    if system_name.nil?
      air_loop.setName("#{zone.name} PSZ-VAV")
    else
      air_loop.setName("#{zone.name} #{system_name}")
    end

    # default design temperatures used across all air loops
    dsgn_temps = standard_design_sizing_temperatures

    # adjusted zone design heating temperature for psz_vav
    dsgn_temps['htg_dsgn_sup_air_temp_f'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_f']
    dsgn_temps['htg_dsgn_sup_air_temp_c'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_c']

    # default design settings used across all air loops
    sizing_system = adjust_sizing_system(air_loop, dsgn_temps)

    # air handler controls
    # add a setpoint manager single zone reheat to control the supply air temperature
    setpoint_mgr_single_zone_reheat = OpenStudio::Model::SetpointManagerSingleZoneReheat.new(model)
    setpoint_mgr_single_zone_reheat.setName("#{zone.name} Setpoint Manager SZ Reheat")
    setpoint_mgr_single_zone_reheat.setControlZone(zone)
    setpoint_mgr_single_zone_reheat.setMinimumSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    setpoint_mgr_single_zone_reheat.setMaximumSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    setpoint_mgr_single_zone_reheat.addToNode(air_loop.supplyOutletNode)

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])

    # create fan
    # @type [OpenStudio::Model::FanVariableVolume] fan
    fan = create_fan_by_name(model,
                             fan_type,
                             fan_name: "#{air_loop.name} Fan",
                             end_use_subcategory: 'VAV System Fans')
    fan.setAvailabilitySchedule(hvac_op_sch)

    # create heating coil
    case heating_type
    when 'NaturalGas', 'Gas'
      htg_coil = create_coil_heating_gas(model,
                                         name: "#{air_loop.name} Gas Htg Coil")
    when 'Electricity', 'Electric'
      htg_coil = create_coil_heating_electric(model,
                                              name: "#{air_loop.name} Electric Htg Coil")
    when 'Water'
      htg_coil = create_coil_heating_water(model,
                                           hot_water_loop,
                                           name: "#{air_loop.name} Water Htg Coil")
    else
      # Zero-capacity, always-off electric heating coil
      htg_coil = create_coil_heating_electric(model,
                                              name: "#{air_loop.name} No Heat",
                                              schedule: model.alwaysOffDiscreteSchedule,
                                              nominal_capacity: 0.0)
    end

    # create supplemental heating coil
    case supplemental_heating_type
    when 'Electricity', 'Electric'
      supplemental_htg_coil = create_coil_heating_electric(model,
                                                           name: "#{air_loop.name} Electric Backup Htg Coil")
    when 'NaturalGas', 'Gas'
      supplemental_htg_coil = create_coil_heating_gas(model,
                                                      name: "#{air_loop.name} Gas Backup Htg Coil")
    else
      # zero-capacity, always-off electric heating coil
      supplemental_htg_coil = create_coil_heating_electric(model,
                                                           name: "#{air_loop.name} No Backup Heat",
                                                           schedule: model.alwaysOffDiscreteSchedule,
                                                           nominal_capacity: 0.0)
    end

    # create cooling coil
    case cooling_type
    when 'WaterCooled'
      clg_coil = create_coil_cooling_water(model,
                                           chilled_water_loop,
                                           name: "#{air_loop.name} Clg Coil")
    else # 'AirCooled'
      clg_coil = OpenStudio::Model::CoilCoolingDXVariableSpeed.new(model)
      clg_coil.setName("#{air_loop.name} Var spd DX AC Clg Coil")
      clg_coil.setBasinHeaterCapacity(10.0)
      clg_coil.setBasinHeaterSetpointTemperature(2.0)
      # first speed level
      clg_spd_1 = OpenStudio::Model::CoilCoolingDXVariableSpeedSpeedData.new(model)
      clg_coil.addSpeed(clg_spd_1)
      clg_coil.setNominalSpeedLevel(1)
    end

    # @todo enable economizer maximum fraction outdoor air schedule input
    # econ_eff_sch = model_add_schedule(model, 'RetailStandalone PSZ_Econ_MaxOAFrac_Sch')

    # wrap coils in a unitary system
    unitary_system = OpenStudio::Model::AirLoopHVACUnitarySystem.new(model)
    unitary_system.setSupplyFan(fan)
    unitary_system.setHeatingCoil(htg_coil)
    unitary_system.setCoolingCoil(clg_coil)
    unitary_system.setSupplementalHeatingCoil(supplemental_htg_coil)
    unitary_system.setName("#{zone.name} Unitary PSZ-VAV")
    # The following control strategy can lead to "Developer Error: Component sizing incomplete."
    # EnergyPlus severe (not fatal) errors if there is no heating design load
    unitary_system.setControlType('SingleZoneVAV')
    unitary_system.setControllingZoneorThermostatLocation(zone)
    unitary_system.setMaximumSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    unitary_system.setFanPlacement('BlowThrough')
    if model.version < OpenStudio::VersionString.new('3.7.0')
      unitary_system.setSupplyAirFlowRateMethodDuringCoolingOperation('SupplyAirFlowRate')
      unitary_system.setSupplyAirFlowRateMethodDuringHeatingOperation('SupplyAirFlowRate')
      if minimum_volume_setpoint.nil?
        unitary_system.setSupplyAirFlowRateMethodWhenNoCoolingorHeatingisRequired('SupplyAirFlowRate')
      else
        unitary_system.setSupplyAirFlowRateMethodWhenNoCoolingorHeatingisRequired('FractionOfAutosizedCoolingValue')
        unitary_system.setFractionofAutosizedDesignCoolingSupplyAirFlowRateWhenNoCoolingorHeatingisRequired(minimum_volume_setpoint)
      end
    else
      unitary_system.autosizeSupplyAirFlowRateDuringCoolingOperation
      unitary_system.autosizeSupplyAirFlowRateDuringHeatingOperation
      if minimum_volume_setpoint.nil?
        unitary_system.autosizeSupplyAirFlowRateWhenNoCoolingorHeatingisRequired
      else
        unitary_system.setFractionofAutosizedDesignCoolingSupplyAirFlowRateWhenNoCoolingorHeatingisRequired(minimum_volume_setpoint)
      end
    end
    unitary_system.setSupplyAirFanOperatingModeSchedule(model.alwaysOnDiscreteSchedule)
    unitary_system.addToNode(air_loop.supplyInletNode)

    # create outdoor air system
    oa_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
    oa_controller.setName("#{air_loop.name} OA Sys Controller")
    oa_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
    oa_controller.autosizeMinimumOutdoorAirFlowRate
    oa_controller.resetEconomizerMinimumLimitDryBulbTemperature
    oa_controller.setHeatRecoveryBypassControlType('BypassWhenOAFlowGreaterThanMinimum')
    oa_system = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_controller)
    oa_system.setName("#{air_loop.name} OA System")
    oa_system.addToNode(air_loop.supplyInletNode)

    # set air loop availability controls and night cycle manager, after oa system added
    air_loop.setAvailabilitySchedule(hvac_op_sch)
    air_loop.setNightCycleControlType('CycleOnAny')

    # create a VAV no reheat terminal and attach the zone/terminal pair to the air loop
    diffuser = OpenStudio::Model::AirTerminalSingleDuctVAVNoReheat.new(model, model.alwaysOnDiscreteSchedule)
    diffuser.setName("#{air_loop.name} Diffuser")
    air_loop.multiAddBranchForZone(zone, diffuser.to_HVACComponent.get)
    air_loops << air_loop
  end

  return air_loops
end
model_add_ptac(model, thermal_zones, cooling_type: 'Two Speed DX AC', heating_type: 'Gas', hot_water_loop: nil, fan_type: 'Cycling', ventilation: true) click to toggle source

Creates a PTAC system for each zone and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param cooling_type [String] valid choices are Two Speed DX AC, Single Speed DX AC @param heating_type [String] valid choices are NaturalGas, Electricity, Water, nil (no heat) @param hot_water_loop [OpenStudio::Model::PlantLoop] hot water loop to connect heating coil to. Set to nil for heating types besides water @param fan_type [String] valid choices are ConstantVolume, Cycling @param ventilation [Boolean] If true, ventilation will be supplied through the unit. If false,

no ventilation will be supplied through the unit, with the expectation that it will be provided by a DOAS or separate system.

@return [Array<OpenStudio::Model::ZoneHVACPackagedTerminalAirConditioner>] an array of the resulting PTACs

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 4021
def model_add_ptac(model,
                   thermal_zones,
                   cooling_type: 'Two Speed DX AC',
                   heating_type: 'Gas',
                   hot_water_loop: nil,
                   fan_type: 'Cycling',
                   ventilation: true)

  # default design temperatures used across all air loops
  dsgn_temps = standard_design_sizing_temperatures
  unless hot_water_loop.nil?
    hw_temp_c = hot_water_loop.sizingPlant.designLoopExitTemperature
    hw_delta_t_k = hot_water_loop.sizingPlant.loopDesignTemperatureDifference
  end

  # adjusted zone design temperatures for ptac
  dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
  dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['zn_clg_dsgn_sup_air_temp_f'] = 57.0
  dsgn_temps['zn_clg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_clg_dsgn_sup_air_temp_f'], 'F', 'C').get

  # make a PTAC for each zone
  ptacs = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding PTAC for #{zone.name}.")

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneCoolingDesignSupplyAirHumidityRatio(0.008)
    sizing_zone.setZoneHeatingDesignSupplyAirHumidityRatio(0.008)

    # add fan
    if fan_type == 'ConstantVolume'
      fan = create_fan_by_name(model,
                               'PTAC_CAV_Fan',
                               fan_name: "#{zone.name} PTAC Fan")
    elsif fan_type == 'Cycling'
      fan = create_fan_by_name(model,
                               'PTAC_Cycling_Fan',
                               fan_name: "#{zone.name} PTAC Fan")
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "ptac_fan_type of #{fan_type} is not recognized.")
    end
    fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

    # add heating coil
    case heating_type
    when 'NaturalGas', 'Gas'
      htg_coil = create_coil_heating_gas(model,
                                         name: "#{zone.name} PTAC Gas Htg Coil")
    when 'Electricity', 'Electric'
      htg_coil = create_coil_heating_electric(model,
                                              name: "#{zone.name} PTAC Electric Htg Coil")
    when nil
      htg_coil = create_coil_heating_electric(model,
                                              name: "#{zone.name} PTAC No Heat",
                                              schedule: model.alwaysOffDiscreteSchedule,
                                              nominal_capacity: 0)
    when 'Water'
      if hot_water_loop.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'No hot water plant loop supplied')
        return false
      end
      htg_coil = create_coil_heating_water(model,
                                           hot_water_loop,
                                           name: "#{hot_water_loop.name} Water Htg Coil",
                                           rated_inlet_water_temperature: hw_temp_c,
                                           rated_outlet_water_temperature: (hw_temp_c - hw_delta_t_k))
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "ptac_heating_type of #{heating_type} is not recognized.")
    end

    # add cooling coil
    if cooling_type == 'Two Speed DX AC'
      clg_coil = create_coil_cooling_dx_two_speed(model,
                                                  name: "#{zone.name} PTAC 2spd DX AC Clg Coil")
    elsif cooling_type == 'Single Speed DX AC'
      clg_coil = create_coil_cooling_dx_single_speed(model,
                                                     name: "#{zone.name} PTAC 1spd DX AC Clg Coil",
                                                     type: 'PTAC')
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "ptac_cooling_type of #{cooling_type} is not recognized.")
    end

    # wrap coils in a PTAC system
    ptac_system = OpenStudio::Model::ZoneHVACPackagedTerminalAirConditioner.new(model,
                                                                                model.alwaysOnDiscreteSchedule,
                                                                                fan,
                                                                                htg_coil,
                                                                                clg_coil)
    ptac_system.setName("#{zone.name} PTAC")
    ptac_system.setFanPlacement('DrawThrough')
    if fan_type == 'ConstantVolume'
      ptac_system.setSupplyAirFanOperatingModeSchedule(model.alwaysOnDiscreteSchedule)
    else
      ptac_system.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)
    end
    unless ventilation
      ptac_system.setOutdoorAirFlowRateDuringCoolingOperation(0.0)
      ptac_system.setOutdoorAirFlowRateDuringHeatingOperation(0.0)
      ptac_system.setOutdoorAirFlowRateWhenNoCoolingorHeatingisNeeded(0.0)
    end
    ptac_system.addToThermalZone(zone)
    ptacs << ptac_system
  end

  return ptacs
end
model_add_pthp(model, thermal_zones, fan_type: 'Cycling', ventilation: true) click to toggle source

Creates a PTHP system for each zone and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param fan_type [String] valid choices are ConstantVolume, Cycling @param ventilation [Boolean] If true, ventilation will be supplied through the unit. If false,

no ventilation will be supplied through the unit, with the expectation that it will be provided by a DOAS or separate system.

@return [Array<OpenStudio::Model::ZoneHVACPackagedTerminalAirConditioner>] an array of the resulting PTACs.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 4140
def model_add_pthp(model,
                   thermal_zones,
                   fan_type: 'Cycling',
                   ventilation: true)

  # default design temperatures used across all air loops
  dsgn_temps = standard_design_sizing_temperatures

  # adjusted zone design temperatures for pthp
  dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
  dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['zn_clg_dsgn_sup_air_temp_f'] = 57.0
  dsgn_temps['zn_clg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_clg_dsgn_sup_air_temp_f'], 'F', 'C').get

  # make a PTHP for each zone
  pthps = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding PTHP for #{zone.name}.")

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneCoolingDesignSupplyAirHumidityRatio(0.008)
    sizing_zone.setZoneHeatingDesignSupplyAirHumidityRatio(0.008)

    # add fan
    if fan_type == 'ConstantVolume'
      fan = create_fan_by_name(model,
                               'PTAC_CAV_Fan',
                               fan_name: "#{zone.name} PTHP Fan")
    elsif fan_type == 'Cycling'
      fan = create_fan_by_name(model,
                               'PTAC_Cycling_Fan',
                               fan_name: "#{zone.name} PTHP Fan")
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "PTHP fan_type of #{fan_type} is not recognized.")
      return false
    end
    fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

    # add heating coil
    htg_coil = create_coil_heating_dx_single_speed(model,
                                                   name: "#{zone.name} PTHP Htg Coil")
    # add cooling coil
    clg_coil = create_coil_cooling_dx_single_speed(model,
                                                   name: "#{zone.name} PTHP Clg Coil",
                                                   type: 'Heat Pump')
    # supplemental heating coil
    supplemental_htg_coil = create_coil_heating_electric(model,
                                                         name: "#{zone.name} PTHP Supplemental Htg Coil")
    # wrap coils in a PTHP system
    pthp_system = OpenStudio::Model::ZoneHVACPackagedTerminalHeatPump.new(model,
                                                                          model.alwaysOnDiscreteSchedule,
                                                                          fan,
                                                                          htg_coil,
                                                                          clg_coil,
                                                                          supplemental_htg_coil)
    pthp_system.setName("#{zone.name} PTHP")
    pthp_system.setFanPlacement('DrawThrough')
    pthp_system.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)
    if fan_type == 'ConstantVolume'
      pthp_system.setSupplyAirFanOperatingModeSchedule(model.alwaysOnDiscreteSchedule)
    else
      pthp_system.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)
    end
    unless ventilation
      pthp_system.setOutdoorAirFlowRateDuringCoolingOperation(0.0)
      pthp_system.setOutdoorAirFlowRateDuringHeatingOperation(0.0)
      pthp_system.setOutdoorAirFlowRateWhenNoCoolingorHeatingisNeeded(0.0)
    end
    pthp_system.addToThermalZone(zone)
    pthps << pthp_system
  end

  return pthps
end
model_add_pvav(model, thermal_zones, system_name: nil, return_plenum: nil, hot_water_loop: nil, chilled_water_loop: nil, heating_type: nil, electric_reheat: false, hvac_op_sch: nil, oa_damper_sch: nil, econo_ctrl_mthd: nil) click to toggle source

Creates a packaged VAV system and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param system_name [String] the name of the system, or nil in which case it will be defaulted @param return_plenum [OpenStudio::Model::ThermalZone] the zone to attach as the supply plenum, or nil, in which case no return plenum will be used @param hot_water_loop [OpenStudio::Model::PlantLoop] hot water loop to connect heating and reheat coils to. If nil, will be electric heat and electric reheat @param chilled_water_loop [OpenStudio::Model::PlantLoop] chilled water loop to connect cooling coils to. If nil, will be DX cooling @param heating_type [String] main heating coil fuel type

valid choices are NaturalGas, Electricity, Water, or nil (defaults to NaturalGas)

@param electric_reheat [Boolean] if true electric reheat coils, if false the reheat coils served by hot_water_loop @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [String] name of the oa damper schedule or nil in which case will be defaulted to always open @param econo_ctrl_mthd [String] economizer control type @return [OpenStudio::Model::AirLoopHVAC] the resulting packaged VAV air loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 2202
def model_add_pvav(model,
                   thermal_zones,
                   system_name: nil,
                   return_plenum: nil,
                   hot_water_loop: nil,
                   chilled_water_loop: nil,
                   heating_type: nil,
                   electric_reheat: false,
                   hvac_op_sch: nil,
                   oa_damper_sch: nil,
                   econo_ctrl_mthd: nil)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding Packaged VAV for #{thermal_zones.size} zones.")

  # create air handler
  air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
  if system_name.nil?
    air_loop.setName("#{thermal_zones.size} Zone PVAV")
  else
    air_loop.setName(system_name)
  end

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # default design temperatures used across all air loops
  dsgn_temps = standard_design_sizing_temperatures
  unless hot_water_loop.nil?
    hw_temp_c = hot_water_loop.sizingPlant.designLoopExitTemperature
    hw_delta_t_k = hot_water_loop.sizingPlant.loopDesignTemperatureDifference
  end

  # adjusted zone design heating temperature for pvav unless it would cause a temperature higher than reheat water supply temperature
  unless !hot_water_loop.nil? && hw_temp_c < OpenStudio.convert(140.0, 'F', 'C').get
    dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
    dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  end

  # default design settings used across all air loops
  sizing_system = adjust_sizing_system(air_loop, dsgn_temps)

  # air handler controls
  sa_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                dsgn_temps['clg_dsgn_sup_air_temp_c'],
                                                                                name: "Supply Air Temp - #{dsgn_temps['clg_dsgn_sup_air_temp_f']}F",
                                                                                schedule_type_limit: 'Temperature')
  sa_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, sa_temp_sch)
  sa_stpt_manager.setName("#{air_loop.name} Supply Air Setpoint Manager")
  sa_stpt_manager.addToNode(air_loop.supplyOutletNode)

  # create fan
  fan = create_fan_by_name(model,
                           'VAV_default',
                           fan_name: "#{air_loop.name} Fan")
  fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  fan.addToNode(air_loop.supplyInletNode)

  # create heating coil
  if hot_water_loop.nil?
    if heating_type == 'Electricity'
      htg_coil = create_coil_heating_electric(model,
                                              air_loop_node: air_loop.supplyInletNode,
                                              name: "#{air_loop.name} Main Electric Htg Coil")
    else # default to NaturalGas
      htg_coil = create_coil_heating_gas(model,
                                         air_loop_node: air_loop.supplyInletNode,
                                         name: "#{air_loop.name} Main Gas Htg Coil")
    end
  else
    htg_coil = create_coil_heating_water(model, hot_water_loop,
                                         air_loop_node: air_loop.supplyInletNode,
                                         name: "#{air_loop.name} Main Htg Coil",
                                         rated_inlet_water_temperature: hw_temp_c,
                                         rated_outlet_water_temperature: (hw_temp_c - hw_delta_t_k),
                                         rated_inlet_air_temperature: dsgn_temps['prehtg_dsgn_sup_air_temp_c'],
                                         rated_outlet_air_temperature: dsgn_temps['htg_dsgn_sup_air_temp_c'])
  end

  # set the setpointmanager for the central/preheat coil if required
  model_set_central_preheat_coil_spm(model, thermal_zones, htg_coil)

  # create cooling coil
  if chilled_water_loop.nil?
    create_coil_cooling_dx_two_speed(model,
                                     air_loop_node: air_loop.supplyInletNode,
                                     name: "#{air_loop.name} 2spd DX Clg Coil",
                                     type: 'OS default')
  else
    create_coil_cooling_water(model,
                              chilled_water_loop,
                              air_loop_node: air_loop.supplyInletNode,
                              name: "#{air_loop.name} Clg Coil")
  end

  # outdoor air intake system
  oa_intake_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
  oa_intake_controller.setName("#{air_loop.name} OA Controller")
  oa_intake_controller.setMinimumLimitType('FixedMinimum')
  oa_intake_controller.autosizeMinimumOutdoorAirFlowRate
  oa_intake_controller.resetMaximumFractionofOutdoorAirSchedule
  oa_intake_controller.resetEconomizerMinimumLimitDryBulbTemperature
  unless econo_ctrl_mthd.nil?
    oa_intake_controller.setEconomizerControlType(econo_ctrl_mthd)
  end
  unless oa_damper_sch.nil?
    oa_intake_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
  end
  controller_mv = oa_intake_controller.controllerMechanicalVentilation
  controller_mv.setName("#{air_loop.name} Mechanical Ventilation Controller")
  controller_mv.setSystemOutdoorAirMethod('ZoneSum')
  oa_intake = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_intake_controller)
  oa_intake.setName("#{air_loop.name} OA System")
  oa_intake.addToNode(air_loop.supplyInletNode)

  # set air loop availability controls and night cycle manager, after oa system added
  air_loop.setAvailabilitySchedule(hvac_op_sch)
  air_loop.setNightCycleControlType('CycleOnAny')

  if model.version < OpenStudio::VersionString.new('3.5.0')
    avail_mgr = air_loop.availabilityManager
    if avail_mgr.is_initialized
      avail_mgr = avail_mgr.get
    else
      avail_mgr = nil
    end
  else
    avail_mgr = air_loop.availabilityManagers[0]
  end

  if !avail_mgr.nil? && avail_mgr.to_AvailabilityManagerNightCycle.is_initialized
    avail_mgr = avail_mgr.to_AvailabilityManagerNightCycle.get
    avail_mgr.setCyclingRunTime(1800)
  end

  # attach the VAV system to each zone
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "Adding PVAV terminal for #{zone.name}")

    # create reheat coil
    if electric_reheat || hot_water_loop.nil?
      rht_coil = create_coil_heating_electric(model,
                                              name: "#{zone.name} Electric Reheat Coil")
    else
      rht_coil = create_coil_heating_water(model,
                                           hot_water_loop,
                                           name: "#{zone.name} Reheat Coil",
                                           rated_inlet_water_temperature: hw_temp_c,
                                           rated_outlet_water_temperature: (hw_temp_c - hw_delta_t_k),
                                           rated_inlet_air_temperature: dsgn_temps['htg_dsgn_sup_air_temp_c'],
                                           rated_outlet_air_temperature: dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    end

    # create VAV terminal
    terminal = OpenStudio::Model::AirTerminalSingleDuctVAVReheat.new(model, model.alwaysOnDiscreteSchedule, rht_coil)
    terminal.setName("#{zone.name} VAV Terminal")
    if model.version < OpenStudio::VersionString.new('3.0.1')
      terminal.setZoneMinimumAirFlowMethod('Constant')
    else
      terminal.setZoneMinimumAirFlowInputMethod('Constant')
    end
    # default to single maximum control logic
    terminal.setDamperHeatingAction('Normal')
    terminal.setMaximumReheatAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    air_loop.multiAddBranchForZone(zone, terminal.to_HVACComponent.get)
    oa_rate = OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate_per_area(zone)
    air_terminal_single_duct_vav_reheat_apply_initial_prototype_damper_position(terminal, oa_rate)

    unless return_plenum.nil?
      zone.setReturnPlenum(return_plenum)
    end

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
  end

  return air_loop
end
model_add_pvav_pfp_boxes(model, thermal_zones, system_name: nil, chilled_water_loop: nil, hvac_op_sch: nil, oa_damper_sch: nil, fan_efficiency: 0.62, fan_motor_efficiency: 0.9, fan_pressure_rise: 4.0) click to toggle source

Creates a packaged VAV system with parallel fan powered boxes and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param system_name [String] the name of the system, or nil in which case it will be defaulted @param chilled_water_loop [OpenStudio::Model::PlantLoop] chilled water loop to connect cooling coils to. If nil, will be DX cooling @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [String] name of the oa damper schedule or nil in which case will be defaulted to always open @param fan_efficiency [Double] fan total efficiency, including motor and impeller @param fan_motor_efficiency [Double] fan motor efficiency @param fan_pressure_rise [Double] fan pressure rise, inH2O @return [OpenStudio::Model::AirLoopHVAC] the resulting VAV air loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 2404
def model_add_pvav_pfp_boxes(model,
                             thermal_zones,
                             system_name: nil,
                             chilled_water_loop: nil,
                             hvac_op_sch: nil,
                             oa_damper_sch: nil,
                             fan_efficiency: 0.62,
                             fan_motor_efficiency: 0.9,
                             fan_pressure_rise: 4.0)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding PVAV with PFP Boxes and Reheat system for #{thermal_zones.size} zones.")

  # create air handler
  air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
  if system_name.nil?
    air_loop.setName("#{thermal_zones.size} Zone PVAV with PFP Boxes and Reheat")
  else
    air_loop.setName(system_name)
  end

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # default design temperatures and settings used across all air loops
  dsgn_temps = standard_design_sizing_temperatures
  sizing_system = adjust_sizing_system(air_loop, dsgn_temps)

  # air handler controls
  sa_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                dsgn_temps['clg_dsgn_sup_air_temp_c'],
                                                                                name: "Supply Air Temp - #{dsgn_temps['clg_dsgn_sup_air_temp_f']}F",
                                                                                schedule_type_limit: 'Temperature')
  sa_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, sa_temp_sch)
  sa_stpt_manager.setName("#{air_loop.name} Supply Air Setpoint Manager")
  sa_stpt_manager.addToNode(air_loop.supplyOutletNode)

  # create fan
  # @type [OpenStudio::Model::FanVariableVolume] fan
  fan = create_fan_by_name(model,
                           'VAV_System_Fan',
                           fan_name: "#{air_loop.name} Fan",
                           fan_efficiency: fan_efficiency,
                           pressure_rise: fan_pressure_rise,
                           motor_efficiency: fan_motor_efficiency,
                           end_use_subcategory: 'VAV System Fans')
  fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  fan.addToNode(air_loop.supplyInletNode)

  # create heating coil
  htg_coil = create_coil_heating_electric(model,
                                          air_loop_node: air_loop.supplyInletNode,
                                          name: "#{air_loop.name} Main Htg Coil")

  # set the setpointmanager for the central/preheat coil if required
  model_set_central_preheat_coil_spm(model, thermal_zones, htg_coil)

  # create cooling coil
  if chilled_water_loop.nil?
    create_coil_cooling_dx_two_speed(model,
                                     air_loop_node: air_loop.supplyInletNode,
                                     name: "#{air_loop.name} 2spd DX Clg Coil", type: 'OS default')
  else
    create_coil_cooling_water(model,
                              chilled_water_loop,
                              air_loop_node: air_loop.supplyInletNode,
                              name: "#{air_loop.name} Clg Coil")
  end

  # create outdoor air intake system
  oa_intake_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
  oa_intake_controller.setName("#{air_loop.name} OA Controller")
  oa_intake_controller.setMinimumLimitType('FixedMinimum')
  oa_intake_controller.autosizeMinimumOutdoorAirFlowRate
  oa_intake_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
  oa_intake_controller.resetEconomizerMinimumLimitDryBulbTemperature
  controller_mv = oa_intake_controller.controllerMechanicalVentilation
  controller_mv.setName("#{air_loop.name} Vent Controller")
  controller_mv.setSystemOutdoorAirMethod('ZoneSum')

  oa_intake = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_intake_controller)
  oa_intake.setName("#{air_loop.name} OA System")
  oa_intake.addToNode(air_loop.supplyInletNode)

  # set air loop availability controls and night cycle manager, after oa system added
  air_loop.setAvailabilitySchedule(hvac_op_sch)
  air_loop.setNightCycleControlType('CycleOnAny')

  # attach the VAV system to each zone
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "Adding PVAV PFP Box to zone #{zone.name}")

    # create electric reheat coil
    rht_coil = create_coil_heating_electric(model,
                                            name: "#{zone.name} Electric Reheat Coil")

    # create terminal fan
    # @type [OpenStudio::Model::FanConstantVolume] pfp_fan
    pfp_fan = create_fan_by_name(model,
                                 'PFP_Fan',
                                 fan_name: "#{zone.name} PFP Term Fan")
    pfp_fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

    # parallel fan powered terminal
    pfp_terminal = OpenStudio::Model::AirTerminalSingleDuctParallelPIUReheat.new(model,
                                                                                 model.alwaysOnDiscreteSchedule,
                                                                                 pfp_fan,
                                                                                 rht_coil)
    pfp_terminal.setName("#{zone.name} PFP Term")
    air_loop.multiAddBranchForZone(zone, pfp_terminal.to_HVACComponent.get)

    # adjust zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setCoolingDesignAirFlowMethod('DesignDay')
    sizing_zone.setHeatingDesignAirFlowMethod('DesignDay')
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
  end

  return air_loop
end
model_add_radiant_basic_controls(model, zone, radiant_loop, radiant_temperature_control_type: 'SurfaceFaceTemperature', slab_setpoint_oa_control: false, switch_over_time: 24.0, slab_sp_at_oat_low: 73, slab_oat_low: 65, slab_sp_at_oat_high: 68, slab_oat_high: 80) click to toggle source

Native EnergyPlus objects implement a control for a single thermal zone with a radiant system. @param zone [OpenStudio::Model::ThermalZone>] zone to add radiant controls @param radiant_loop [OpenStudio::Model::ZoneHVACLowTempRadiantVarFlow>] radiant loop in thermal zone @param radiant_temperature_control_type [String] determines the controlled temperature for the radiant system

options are 'SurfaceFaceTemperature', 'SurfaceInteriorTemperature'

@param slab_setpoint_oa_control [Bool] True if slab setpoint is to be varied based on outdoor air temperature @param switch_over_time [Double] Time limitation for when the system can switch between heating and cooling @param slab_sp_at_oat_low [Double] radiant slab temperature setpoint, in F, at the outdoor high temperature. @param slab_oat_low [Double] outdoor drybulb air temperature, in F, for low radiant slab setpoint. @param slab_sp_at_oat_high [Double] radiant slab temperature setpoint, in F, at the outdoor low temperature. @param slab_oat_high [Double] outdoor drybulb air temperature, in F, for high radiant slab setpoint.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.radiant_system_controls.rb, line 465
def model_add_radiant_basic_controls(model, zone, radiant_loop,
                                     radiant_temperature_control_type: 'SurfaceFaceTemperature',
                                     slab_setpoint_oa_control: false,
                                     switch_over_time: 24.0,
                                     slab_sp_at_oat_low: 73,
                                     slab_oat_low: 65,
                                     slab_sp_at_oat_high: 68,
                                     slab_oat_high: 80)

  zone_name = zone.name.to_s.gsub(/[ +-.]/, '_')

  if model.version < OpenStudio::VersionString.new('3.1.1')
    coil_cooling_radiant = radiant_loop.coolingCoil.to_CoilCoolingLowTempRadiantVarFlow.get
    coil_heating_radiant = radiant_loop.heatingCoil.to_CoilHeatingLowTempRadiantVarFlow.get
  else
    coil_cooling_radiant = radiant_loop.coolingCoil.get.to_CoilCoolingLowTempRadiantVarFlow.get
    coil_heating_radiant = radiant_loop.heatingCoil.get.to_CoilHeatingLowTempRadiantVarFlow.get
  end

  #####
  # Define radiant system parameters
  ####
  # set radiant system temperature and setpoint control type
  unless ['surfacefacetemperature', 'surfaceinteriortemperature'].include? radiant_temperature_control_type.downcase
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model',
                       "Control sequences not compatible with '#{radiant_temperature_control_type}' radiant system control. Defaulting to 'SurfaceFaceTemperature'.")
    radiant_temperature_control_type = 'SurfaceFaceTemperature'
  end

  radiant_loop.setTemperatureControlType(radiant_temperature_control_type)

  # get existing switchover time schedule or create one if needed
  sch_radiant_switchover = model.getScheduleRulesetByName('Radiant System Switchover')
  if sch_radiant_switchover.is_initialized
    sch_radiant_switchover = sch_radiant_switchover.get
  else
    sch_radiant_switchover = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                             switch_over_time,
                                                                                             name: 'Radiant System Switchover',
                                                                                             schedule_type_limit: 'Dimensionless')
  end

  # set radiant system switchover schedule
  radiant_loop.setChangeoverDelayTimePeriodSchedule(sch_radiant_switchover.to_Schedule.get)

  if slab_setpoint_oa_control
    # get weather file from model
    weather_file = model.getWeatherFile
    if weather_file.initialized
      # get annual outdoor dry bulb temperature
      annual_oat = weather_file.file.get.data.collect { |dat| dat.dryBulbTemperature.get }

      # calculate a nhrs rolling average from annual outdoor dry bulb temperature
      nhrs = 24
      last_nhrs_oat_in_year = annual_oat.last(nhrs - 1)
      combined_oat = last_nhrs_oat_in_year + annual_oat
      oat_rolling_average = combined_oat.each_cons(nhrs).map { |e| e.reduce(&:+).fdiv(nhrs).round(2) }

      # use rolling average to calculate slab setpoint temperature

      # convert temperature from IP to SI units
      slab_sp_at_oat_low_si = OpenStudio.convert(slab_sp_at_oat_low, 'F', 'C').get
      slab_oat_low_si = OpenStudio.convert(slab_oat_low, 'F', 'C').get
      slab_sp_at_oat_high_si = OpenStudio.convert(slab_sp_at_oat_high, 'F', 'C').get
      slab_oat_high_si = OpenStudio.convert(slab_oat_high, 'F', 'C').get

      # calculate relationship between slab setpoint and slope
      slope_num = slab_sp_at_oat_high_si - slab_sp_at_oat_low_si
      slope_den = slab_oat_high_si - slab_oat_low_si
      sp_and_oat_slope = slope_num.fdiv(slope_den).round(4)

      slab_setpoint = oat_rolling_average.map { |e| (slab_sp_at_oat_low_si + ((e - slab_oat_low_si) * sp_and_oat_slope)).round(1) }

      # input upper limits on slab setpoint
      slab_sp_upper_limit = [slab_sp_at_oat_high_si, slab_sp_at_oat_low_si].max
      slab_sp_lower_limit = [slab_sp_at_oat_high_si, slab_sp_at_oat_low_si].min
      slab_setpoint.map! { |e| e > slab_sp_upper_limit ? slab_sp_upper_limit.round(1) : e }

      # input lower limits on slab setpoint
      slab_setpoint.map! { |e| e < slab_sp_lower_limit ? slab_sp_lower_limit.round(1) : e }

      # convert to timeseries
      yd = model.getYearDescription
      start_date = yd.makeDate(1, 1)
      interval = OpenStudio::Time.new(1.0 / 24.0)
      time_series = OpenStudio::TimeSeries.new(start_date, interval, OpenStudio.createVector(slab_setpoint), 'C')

      # check for pre-existing schedule in model
      schedule_interval = model.getScheduleByName('Sch_Radiant_SlabSetP_Based_On_Rolling_Mean_OAT')
      if schedule_interval.is_initialized && schedule_interval.get.to_ScheduleFixedInterval.is_initialized
        schedule_interval = schedule_interval.get.to_ScheduleFixedInterval.get
        schedule_interval.setTimeSeries(time_series)
      else
        # create fixed interval schedule for slab setpoint
        schedule_interval = OpenStudio::Model::ScheduleFixedInterval.new(model)
        schedule_interval.setName('Sch_Radiant_SlabSetP_Based_On_Rolling_Mean_OAT')
        schedule_interval.setTimeSeries(time_series)
        sch_type_limits_obj = OpenstudioStandards::Schedules.create_schedule_type_limits(model, standard_schedule_type_limit: 'Temperature')
        schedule_interval.setScheduleTypeLimits(sch_type_limits_obj)
      end

      # assign slab setpoint schedule
      coil_heating_radiant.setHeatingControlTemperatureSchedule(sch_radiant_slab_setp)
      coil_cooling_radiant.setCoolingControlTemperatureSchedule(sch_radiant_slab_setp)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model',
                         'Model does not have a weather file associated with it. Define to implement slab setpoint based on outdoor weather.')
    end
  else
    # radiant system cooling control setpoint
    slab_setpoint = 22
    sch_radiant_clgsetp = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                          slab_setpoint + 0.1,
                                                                                          name: "#{zone_name}_Sch_Radiant_ClgSetP",
                                                                                          schedule_type_limit: 'Temperature')
    coil_cooling_radiant.setCoolingControlTemperatureSchedule(sch_radiant_clgsetp)

    # radiant system heating control setpoint
    sch_radiant_htgsetp = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                          slab_setpoint,
                                                                                          name: "#{zone_name}_Sch_Radiant_HtgSetP",
                                                                                          schedule_type_limit: 'Temperature')
    coil_heating_radiant.setHeatingControlTemperatureSchedule(sch_radiant_htgsetp)
  end
end
model_add_radiant_proportional_controls(model, zone, radiant_loop, radiant_temperature_control_type: 'SurfaceFaceTemperature', use_zone_occupancy_for_control: true, occupied_percentage_threshold: 0.10, model_occ_hr_start: 6.0, model_occ_hr_end: 18.0, proportional_gain: 0.3, switch_over_time: 24.0) click to toggle source

These EnergyPlus objects implement a proportional control for a single thermal zone with a radiant system. @ref [References::CBERadiantSystems] @param zone [OpenStudio::Model::ThermalZone>] zone to add radiant controls @param radiant_loop [OpenStudio::Model::ZoneHVACLowTempRadiantVarFlow>] radiant loop in thermal zone @param radiant_temperature_control_type [String] determines the controlled temperature for the radiant system

options are 'SurfaceFaceTemperature', 'SurfaceInteriorTemperature'

@param use_zone_occupancy_for_control [Boolean] Set to true if radiant system is to use specific zone occupancy objects

for CBE control strategy. If false, then it will use values in model_occ_hr_start and model_occ_hr_end
for all radiant zones. default to true.

@param occupied_percentage_threshold [Double] the minimum fraction (0 to 1) that counts as occupied

if this parameter is set, the returned ScheduleRuleset will be 0 = unoccupied, 1 = occupied
otherwise the ScheduleRuleset will be the weighted fractional occupancy schedule

@param model_occ_hr_start [Double] Starting decimal hour of whole building occupancy @param model_occ_hr_end [Double] Ending decimal hour of whole building occupancy @todo model_occ_hr_start and model_occ_hr_end from zone occupancy schedules @param proportional_gain [Double] Proportional gain constant (recommended 0.3 or less). @param switch_over_time [Double] Time limitation for when the system can switch between heating and cooling

# File lib/openstudio-standards/prototypes/common/objects/Prototype.radiant_system_controls.rb, line 19
  def model_add_radiant_proportional_controls(model, zone, radiant_loop,
                                              radiant_temperature_control_type: 'SurfaceFaceTemperature',
                                              use_zone_occupancy_for_control: true,
                                              occupied_percentage_threshold: 0.10,
                                              model_occ_hr_start: 6.0,
                                              model_occ_hr_end: 18.0,
                                              proportional_gain: 0.3,
                                              switch_over_time: 24.0)

    zone_name = ems_friendly_name(zone.name)
    zone_timestep = model.getTimestep.numberOfTimestepsPerHour

    if model.version < OpenStudio::VersionString.new('3.1.1')
      coil_cooling_radiant = radiant_loop.coolingCoil.to_CoilCoolingLowTempRadiantVarFlow.get
      coil_heating_radiant = radiant_loop.heatingCoil.to_CoilHeatingLowTempRadiantVarFlow.get
    else
      coil_cooling_radiant = radiant_loop.coolingCoil.get.to_CoilCoolingLowTempRadiantVarFlow.get
      coil_heating_radiant = radiant_loop.heatingCoil.get.to_CoilHeatingLowTempRadiantVarFlow.get
    end

    #####
    # Define radiant system parameters
    ####
    # set radiant system temperature and setpoint control type
    unless ['surfacefacetemperature', 'surfaceinteriortemperature'].include? radiant_temperature_control_type.downcase
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model',
                         "Control sequences not compatible with '#{radiant_temperature_control_type}' radiant system control. Defaulting to 'SurfaceFaceTemperature'.")
      radiant_temperature_control_type = 'SurfaceFaceTemperature'
    end

    radiant_loop.setTemperatureControlType(radiant_temperature_control_type)

    #####
    # List of schedule objects used to hold calculation results
    ####

    # get existing switchover time schedule or create one if needed
    sch_radiant_switchover = model.getScheduleRulesetByName('Radiant System Switchover')
    if sch_radiant_switchover.is_initialized
      sch_radiant_switchover = sch_radiant_switchover.get
    else
      sch_radiant_switchover = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                               switch_over_time,
                                                                                               name: 'Radiant System Switchover',
                                                                                               schedule_type_limit: 'Dimensionless')
    end

    # set radiant system switchover schedule
    radiant_loop.setChangeoverDelayTimePeriodSchedule(sch_radiant_switchover.to_Schedule.get)

    # Calculated active slab heating and cooling temperature setpoint.
    # radiant system cooling control actuator
    sch_radiant_clgsetp = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                          26.0,
                                                                                          name: "#{zone_name}_Sch_Radiant_ClgSetP",
                                                                                          schedule_type_limit: 'Temperature')
    coil_cooling_radiant.setCoolingControlTemperatureSchedule(sch_radiant_clgsetp)
    cmd_cold_water_ctrl = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_radiant_clgsetp,
                                                                                'Schedule:Year',
                                                                                'Schedule Value')
    cmd_cold_water_ctrl.setName("#{zone_name}_cmd_cold_water_ctrl")

    # radiant system heating control actuator
    sch_radiant_htgsetp = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                          20.0,
                                                                                          name: "#{zone_name}_Sch_Radiant_HtgSetP",
                                                                                          schedule_type_limit: 'Temperature')
    coil_heating_radiant.setHeatingControlTemperatureSchedule(sch_radiant_htgsetp)
    cmd_hot_water_ctrl = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_radiant_htgsetp,
                                                                               'Schedule:Year',
                                                                               'Schedule Value')
    cmd_hot_water_ctrl.setName("#{zone_name}_cmd_hot_water_ctrl")

    # Calculated cooling setpoint error. Calculated from upper comfort limit minus setpoint offset and 'measured' controlled zone temperature.
    sch_csp_error = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                    0.0,
                                                                                    name: "#{zone_name}_Sch_CSP_Error",
                                                                                    schedule_type_limit: 'Temperature')
    cmd_csp_error = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_csp_error,
                                                                          'Schedule:Year',
                                                                          'Schedule Value')
    cmd_csp_error.setName("#{zone_name}_cmd_csp_error")

    # Calculated heating setpoint error. Calculated from lower comfort limit plus setpoint offset and 'measured' controlled zone temperature.
    sch_hsp_error = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                    0.0,
                                                                                    name: "#{zone_name}_Sch_HSP_Error",
                                                                                    schedule_type_limit: 'Temperature')
    cmd_hsp_error = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_hsp_error,
                                                                          'Schedule:Year',
                                                                          'Schedule Value')
    cmd_hsp_error.setName("#{zone_name}_cmd_hsp_error")

    #####
    # List of global variables used in EMS scripts
    ####

    # Proportional  gain constant (recommended 0.3 or less).
    prp_k = model.getEnergyManagementSystemGlobalVariableByName('prp_k')
    if prp_k.is_initialized
      prp_k = prp_k.get
    else
      prp_k = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'prp_k')
    end

    # Upper slab temperature setpoint limit (recommended no higher than 29C (84F))
    upper_slab_sp_lim = model.getEnergyManagementSystemGlobalVariableByName('upper_slab_sp_lim')
    if upper_slab_sp_lim.is_initialized
      upper_slab_sp_lim = upper_slab_sp_lim.get
    else
      upper_slab_sp_lim = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'upper_slab_sp_lim')
    end

    # Lower slab temperature setpoint limit (recommended no lower than 19C (66F))
    lower_slab_sp_lim = model.getEnergyManagementSystemGlobalVariableByName('lower_slab_sp_lim')
    if lower_slab_sp_lim.is_initialized
      lower_slab_sp_lim = lower_slab_sp_lim.get
    else
      lower_slab_sp_lim = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'lower_slab_sp_lim')
    end

    # Temperature offset used as a safety factor for thermal control (recommend 0.5C (1F)).
    ctrl_temp_offset = model.getEnergyManagementSystemGlobalVariableByName('ctrl_temp_offset')
    if ctrl_temp_offset.is_initialized
      ctrl_temp_offset = ctrl_temp_offset.get
    else
      ctrl_temp_offset = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'ctrl_temp_offset')
    end

    # Hour where slab setpoint is to be changed
    hour_of_slab_sp_change = model.getEnergyManagementSystemGlobalVariableByName('hour_of_slab_sp_change')
    if hour_of_slab_sp_change.is_initialized
      hour_of_slab_sp_change = hour_of_slab_sp_change.get
    else
      hour_of_slab_sp_change = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'hour_of_slab_sp_change')
    end

    #####
    # List of zone specific variables used in EMS scripts
    ####

    # Maximum 'measured' temperature in zone during occupied times. Default setup uses mean air temperature.
    # Other possible choices are operative and mean radiant temperature.
    zone_max_ctrl_temp = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, "#{zone_name}_max_ctrl_temp")

    # Minimum 'measured' temperature in zone during occupied times. Default setup uses mean air temperature.
    # Other possible choices are operative and mean radiant temperature.
    zone_min_ctrl_temp = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, "#{zone_name}_min_ctrl_temp")

    #####
    # List of 'sensors' used in the EMS programs
    ####

    # Controlled zone temperature for the zone.
    zone_ctrl_temperature = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Zone Air Temperature')
    zone_ctrl_temperature.setName("#{zone_name}_ctrl_temperature")
    zone_ctrl_temperature.setKeyName(zone.name.get)

    # check for zone thermostat and replace heat/cool schedules for radiant system control
    # if there is no zone thermostat, then create one
    zone_thermostat = zone.thermostatSetpointDualSetpoint

    if zone_thermostat.is_initialized
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Replacing thermostat schedules in zone #{zone.name} for radiant system control.")
      zone_thermostat = zone.thermostatSetpointDualSetpoint.get
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Zone #{zone.name} does not have a thermostat. Creating a thermostat for radiant system control.")
      zone_thermostat = OpenStudio::Model::ThermostatSetpointDualSetpoint.new(model)
      zone_thermostat.setName("#{zone_name}_Thermostat_DualSetpoint")
    end

    # create new heating and cooling schedules to be used with all radiant systems
    zone_htg_thermostat = model.getScheduleRulesetByName('Radiant System Heating Setpoint')
    if zone_htg_thermostat.is_initialized
      zone_htg_thermostat = zone_htg_thermostat.get
    else
      zone_htg_thermostat = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                            20.0,
                                                                                            name: 'Radiant System Heating Setpoint',
                                                                                            schedule_type_limit: 'Temperature')
    end

    zone_clg_thermostat = model.getScheduleRulesetByName('Radiant System Cooling Setpoint')
    if zone_clg_thermostat.is_initialized
      zone_clg_thermostat = zone_clg_thermostat.get
    else
      zone_clg_thermostat = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                            26.0,
                                                                                            name: 'Radiant System Cooling Setpoint',
                                                                                            schedule_type_limit: 'Temperature')
    end

    # implement new heating and cooling schedules
    zone_thermostat.setHeatingSetpointTemperatureSchedule(zone_htg_thermostat)
    zone_thermostat.setCoolingSetpointTemperatureSchedule(zone_clg_thermostat)

    # Upper comfort limit for the zone. Taken from existing thermostat schedules in the zone.
    zone_upper_comfort_limit = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')
    zone_upper_comfort_limit.setName("#{zone_name}_upper_comfort_limit")
    zone_upper_comfort_limit.setKeyName(zone_clg_thermostat.name.get)

    # Lower comfort limit for the zone. Taken from existing thermostat schedules in the zone.
    zone_lower_comfort_limit = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')
    zone_lower_comfort_limit.setName("#{zone_name}_lower_comfort_limit")
    zone_lower_comfort_limit.setKeyName(zone_htg_thermostat.name.get)

    # Radiant system water flow rate used to determine if there is active hydronic cooling in the radiant system.
    zone_rad_cool_operation = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'System Node Mass Flow Rate')
    zone_rad_cool_operation.setName("#{zone_name}_rad_cool_operation")
    zone_rad_cool_operation.setKeyName(coil_cooling_radiant.to_StraightComponent.get.inletModelObject.get.name.get)

    # Radiant system water flow rate used to determine if there is active hydronic heating in the radiant system.
    zone_rad_heat_operation = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'System Node Mass Flow Rate')
    zone_rad_heat_operation.setName("#{zone_name}_rad_heat_operation")
    zone_rad_heat_operation.setKeyName(coil_heating_radiant.to_StraightComponent.get.inletModelObject.get.name.get)

    # Radiant system switchover delay time period schedule
    # used to determine if there is active hydronic cooling/heating in the radiant system.
    zone_rad_switch_over = model.getEnergyManagementSystemSensorByName('radiant_switch_over_time')

    unless zone_rad_switch_over.is_initialized
      zone_rad_switch_over = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')
      zone_rad_switch_over.setName('radiant_switch_over_time')
      zone_rad_switch_over.setKeyName(sch_radiant_switchover.name.get)
    end

    # Last 24 hours trend for radiant system in cooling mode.
    zone_rad_cool_operation_trend = OpenStudio::Model::EnergyManagementSystemTrendVariable.new(model, zone_rad_cool_operation)
    zone_rad_cool_operation_trend.setName("#{zone_name}_rad_cool_operation_trend")
    zone_rad_cool_operation_trend.setNumberOfTimestepsToBeLogged(zone_timestep * 48)

    # Last 24 hours trend for radiant system in heating mode.
    zone_rad_heat_operation_trend = OpenStudio::Model::EnergyManagementSystemTrendVariable.new(model, zone_rad_heat_operation)
    zone_rad_heat_operation_trend.setName("#{zone_name}_rad_heat_operation_trend")
    zone_rad_heat_operation_trend.setNumberOfTimestepsToBeLogged(zone_timestep * 48)

    # use zone occupancy objects for radiant system control if selected
    if use_zone_occupancy_for_control

      # get annual occupancy schedule for zone
      occ_schedule_ruleset = OpenstudioStandards::ThermalZone.thermal_zone_get_occupancy_schedule(zone,
                                                                                                  sch_name: "#{zone.name} Radiant System Occupied Schedule",
                                                                                                  occupied_percentage_threshold: occupied_percentage_threshold)
    else

      occ_schedule_ruleset = model.getScheduleRulesetByName('Whole Building Radiant System Occupied Schedule')
      if occ_schedule_ruleset.is_initialized
        occ_schedule_ruleset = occ_schedule_ruleset.get
      else
        # create occupancy schedules
        occ_schedule_ruleset = OpenStudio::Model::ScheduleRuleset.new(model)
        occ_schedule_ruleset.setName('Whole Building Radiant System Occupied Schedule')

        start_hour = model_occ_hr_end.to_i
        start_minute = ((model_occ_hr_end % 1) * 60).to_i
        end_hour = model_occ_hr_start.to_i
        end_minute = ((model_occ_hr_start % 1) * 60).to_i

        if end_hour > start_hour
          occ_schedule_ruleset.defaultDaySchedule.addValue(OpenStudio::Time.new(0, start_hour, start_minute, 0), 1.0)
          occ_schedule_ruleset.defaultDaySchedule.addValue(OpenStudio::Time.new(0, end_hour, end_minute, 0), 0.0)
          occ_schedule_ruleset.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 1.0) if end_hour < 24
        elsif start_hour > end_hour
          occ_schedule_ruleset.defaultDaySchedule.addValue(OpenStudio::Time.new(0, end_hour, end_minute, 0), 0.0)
          occ_schedule_ruleset.defaultDaySchedule.addValue(OpenStudio::Time.new(0, start_hour, start_minute, 0), 1.0)
          occ_schedule_ruleset.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0.0) if start_hour < 24
        else
          occ_schedule_ruleset.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 1.0)
        end
      end
    end

    # create ems sensor for zone occupied status
    zone_occupied_status = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')
    zone_occupied_status.setName("#{zone_name}_occupied_status")
    zone_occupied_status.setKeyName(occ_schedule_ruleset.name.get)

    # Last 24 hours trend for zone occupied status
    zone_occupied_status_trend = OpenStudio::Model::EnergyManagementSystemTrendVariable.new(model, zone_occupied_status)
    zone_occupied_status_trend.setName("#{zone_name}_occupied_status_trend")
    zone_occupied_status_trend.setNumberOfTimestepsToBeLogged(zone_timestep * 48)

    #####
    # List of EMS programs to implement the proportional control for the radiant system.
    ####

    # Initialize global constant values used in EMS programs.
    set_constant_values_prg_body = <<-EMS
      SET prp_k              = #{proportional_gain},
      SET ctrl_temp_offset   = 0.5,
      SET upper_slab_sp_lim  = 29,
      SET lower_slab_sp_lim  = 19,
      SET hour_of_slab_sp_change = 18
    EMS

    set_constant_values_prg = model.getEnergyManagementSystemProgramByName('Set_Constant_Values')
    if set_constant_values_prg.is_initialized
      set_constant_values_prg = set_constant_values_prg.get
    else
      set_constant_values_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
      set_constant_values_prg.setName('Set_Constant_Values')
      set_constant_values_prg.setBody(set_constant_values_prg_body)
    end

    # Initialize zone specific constant values used in EMS programs.
    set_constant_zone_values_prg_body = <<-EMS
      SET #{zone_name}_max_ctrl_temp      = #{zone_name}_lower_comfort_limit,
      SET #{zone_name}_min_ctrl_temp      = #{zone_name}_upper_comfort_limit,
      SET #{zone_name}_cmd_csp_error      = 0,
      SET #{zone_name}_cmd_hsp_error      = 0,
      SET #{zone_name}_cmd_cold_water_ctrl = #{zone_name}_upper_comfort_limit,
      SET #{zone_name}_cmd_hot_water_ctrl  = #{zone_name}_lower_comfort_limit
    EMS

    set_constant_zone_values_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
    set_constant_zone_values_prg.setName("#{zone_name}_Set_Constant_Values")
    set_constant_zone_values_prg.setBody(set_constant_zone_values_prg_body)

    # Calculate maximum and minimum 'measured' controlled temperature in the zone
    calculate_minmax_ctrl_temp_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
    calculate_minmax_ctrl_temp_prg.setName("#{zone_name}_Calculate_Extremes_In_Zone")
    calculate_minmax_ctrl_temp_prg_body = <<-EMS
      IF (#{zone_name}_occupied_status == 1),
          IF #{zone_name}_ctrl_temperature > #{zone_name}_max_ctrl_temp,
              SET #{zone_name}_max_ctrl_temp = #{zone_name}_ctrl_temperature,
          ENDIF,
          IF #{zone_name}_ctrl_temperature < #{zone_name}_min_ctrl_temp,
              SET #{zone_name}_min_ctrl_temp = #{zone_name}_ctrl_temperature,
          ENDIF,
      ELSE,
        SET #{zone_name}_max_ctrl_temp = #{zone_name}_lower_comfort_limit,
        SET #{zone_name}_min_ctrl_temp = #{zone_name}_upper_comfort_limit,
      ENDIF
    EMS
    calculate_minmax_ctrl_temp_prg.setBody(calculate_minmax_ctrl_temp_prg_body)

    # Calculate errors from comfort zone limits and 'measured' controlled temperature in the zone.
    calculate_errors_from_comfort_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
    calculate_errors_from_comfort_prg.setName("#{zone_name}_Calculate_Errors_From_Comfort")
    calculate_errors_from_comfort_prg_body = <<-EMS
      IF (CurrentTime == (hour_of_slab_sp_change - ZoneTimeStep)),
          SET #{zone_name}_cmd_csp_error = (#{zone_name}_upper_comfort_limit - ctrl_temp_offset) - #{zone_name}_max_ctrl_temp,
          SET #{zone_name}_cmd_hsp_error = (#{zone_name}_lower_comfort_limit + ctrl_temp_offset) - #{zone_name}_min_ctrl_temp,
      ENDIF
    EMS
    calculate_errors_from_comfort_prg.setBody(calculate_errors_from_comfort_prg_body)

    # Calculate the new active slab temperature setpoint for heating and cooling
    calculate_slab_ctrl_setpoint_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
    calculate_slab_ctrl_setpoint_prg.setName("#{zone_name}_Calculate_Slab_Ctrl_Setpoint")
    calculate_slab_ctrl_setpoint_prg_body = <<-EMS
      SET #{zone_name}_cont_cool_oper = @TrendSum #{zone_name}_rad_cool_operation_trend radiant_switch_over_time/ZoneTimeStep,
      SET #{zone_name}_cont_heat_oper = @TrendSum #{zone_name}_rad_heat_operation_trend radiant_switch_over_time/ZoneTimeStep,
      SET #{zone_name}_occupied_hours = @TrendSum #{zone_name}_occupied_status_trend 24/ZoneTimeStep,
      IF (#{zone_name}_cont_cool_oper > 0) && (#{zone_name}_occupied_hours > 0) && (CurrentTime == hour_of_slab_sp_change),
        SET #{zone_name}_cmd_hot_water_ctrl = #{zone_name}_cmd_hot_water_ctrl + (#{zone_name}_cmd_csp_error*prp_k),
      ELSEIF (#{zone_name}_cont_heat_oper > 0) && (#{zone_name}_occupied_hours > 0) && (CurrentTime == hour_of_slab_sp_change),
        SET #{zone_name}_cmd_hot_water_ctrl = #{zone_name}_cmd_hot_water_ctrl + (#{zone_name}_cmd_hsp_error*prp_k),
      ELSE,
        SET #{zone_name}_cmd_hot_water_ctrl = #{zone_name}_cmd_hot_water_ctrl,
      ENDIF,
      IF (#{zone_name}_cmd_hot_water_ctrl < lower_slab_sp_lim),
        SET #{zone_name}_cmd_hot_water_ctrl = lower_slab_sp_lim,
      ELSEIF (#{zone_name}_cmd_hot_water_ctrl > upper_slab_sp_lim),
        SET #{zone_name}_cmd_hot_water_ctrl = upper_slab_sp_lim,
      ENDIF,
      SET #{zone_name}_cmd_cold_water_ctrl = #{zone_name}_cmd_hot_water_ctrl + 0.01
    EMS
    calculate_slab_ctrl_setpoint_prg.setBody(calculate_slab_ctrl_setpoint_prg_body)

    #####
    # List of EMS program manager objects
    ####

    initialize_constant_parameters = model.getEnergyManagementSystemProgramCallingManagerByName('Initialize_Constant_Parameters')
    if initialize_constant_parameters.is_initialized
      initialize_constant_parameters = initialize_constant_parameters.get
      # add program if it does not exist in manager
      existing_program_names = initialize_constant_parameters.programs.collect { |prg| prg.name.get.downcase }
      unless existing_program_names.include? set_constant_values_prg.name.get.downcase
        initialize_constant_parameters.addProgram(set_constant_values_prg)
      end
    else
      initialize_constant_parameters = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
      initialize_constant_parameters.setName('Initialize_Constant_Parameters')
      initialize_constant_parameters.setCallingPoint('BeginNewEnvironment')
      initialize_constant_parameters.addProgram(set_constant_values_prg)
    end

    initialize_constant_parameters_after_warmup = model.getEnergyManagementSystemProgramCallingManagerByName('Initialize_Constant_Parameters_After_Warmup')
    if initialize_constant_parameters_after_warmup.is_initialized
      initialize_constant_parameters_after_warmup = initialize_constant_parameters_after_warmup.get
      # add program if it does not exist in manager
      existing_program_names = initialize_constant_parameters_after_warmup.programs.collect { |prg| prg.name.get.downcase }
      unless existing_program_names.include? set_constant_values_prg.name.get.downcase
        initialize_constant_parameters_after_warmup.addProgram(set_constant_values_prg)
      end
    else
      initialize_constant_parameters_after_warmup = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
      initialize_constant_parameters_after_warmup.setName('Initialize_Constant_Parameters_After_Warmup')
      initialize_constant_parameters_after_warmup.setCallingPoint('AfterNewEnvironmentWarmUpIsComplete')
      initialize_constant_parameters_after_warmup.addProgram(set_constant_values_prg)
    end

    zone_initialize_constant_parameters = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
    zone_initialize_constant_parameters.setName("#{zone_name}_Initialize_Constant_Parameters")
    zone_initialize_constant_parameters.setCallingPoint('BeginNewEnvironment')
    zone_initialize_constant_parameters.addProgram(set_constant_zone_values_prg)

    zone_initialize_constant_parameters_after_warmup = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
    zone_initialize_constant_parameters_after_warmup.setName("#{zone_name}_Initialize_Constant_Parameters_After_Warmup")
    zone_initialize_constant_parameters_after_warmup.setCallingPoint('AfterNewEnvironmentWarmUpIsComplete')
    zone_initialize_constant_parameters_after_warmup.addProgram(set_constant_zone_values_prg)

    average_building_temperature = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
    average_building_temperature.setName("#{zone_name}_Average_Building_Temperature")
    average_building_temperature.setCallingPoint('EndOfZoneTimestepAfterZoneReporting')
    average_building_temperature.addProgram(calculate_minmax_ctrl_temp_prg)
    average_building_temperature.addProgram(calculate_errors_from_comfort_prg)

    programs_at_beginning_of_timestep = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
    programs_at_beginning_of_timestep.setName("#{zone_name}_Programs_At_Beginning_Of_Timestep")
    programs_at_beginning_of_timestep.setCallingPoint('BeginTimestepBeforePredictor')
    programs_at_beginning_of_timestep.addProgram(calculate_slab_ctrl_setpoint_prg)

    #####
    # List of variables for output.
    ####

    zone_max_ctrl_temp_output = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, zone_max_ctrl_temp)
    zone_max_ctrl_temp_output.setName("#{zone_name} Maximum occupied temperature in zone")
    zone_min_ctrl_temp_output = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, zone_min_ctrl_temp)
    zone_min_ctrl_temp_output.setName("#{zone_name} Minimum occupied temperature in zone")
  end
model_add_refrigeration_case(model, thermal_zone, case_type, size_category) click to toggle source

Adds a refrigerated case to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zone [OpenStudio::Model::ThermalZone] the thermal zone where the case is located,

and which will be impacted by the case's thermal load.

@param case_type [String] the case type/name. For valid choices

refer to the ""Refrigerated Cases" tab on the OpenStudio_Standards spreadsheet.
This parameter is used also by the "Refrigeration System Lineup" tab.

@param size_category [String] size category of the building area. Valid choices are:

"<35k ft2", "35k - 50k ft2", ">50k ft2"

@return [OpenStudio::Model::RefrigerationCase] the refrigeration case

# File lib/openstudio-standards/prototypes/common/objects/Prototype.refrigeration.rb, line 15
def model_add_refrigeration_case(model, thermal_zone, case_type, size_category)
  # Get the case properties
  #

  search_criteria = {
    'template' => template,
    'case_type' => case_type,
    'size_category' => size_category
  }

  props = model_find_object(standards_data['refrigerated_cases'], search_criteria)
  if props.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Could not find refrigerated case properties for: #{search_criteria}.")
    return nil
  end

  # Capacity, defrost, anti-sweat
  case_length = OpenStudio.convert(props['case_length'], 'ft', 'm').get
  case_temp = OpenStudio.convert(props['case_temp'], 'F', 'C').get
  cooling_capacity_per_length = OpenStudio.convert(props['cooling_capacity_per_length'], 'Btu/hr*ft', 'W/m').get
  evap_fan_power_per_length = OpenStudio.convert(props['evap_fan_power_per_length'], 'W/ft', 'W/m').get
  if props['evap_temp']
    evap_temp_c = OpenStudio.convert(props['evap_temp'], 'F', 'C').get
  end
  lighting_w_per_m = OpenStudio.convert(props['lighting_per_ft'], 'W/ft', 'W/m').get
  if props['lighting_schedule']
    case_lighting_schedule = model_add_schedule(model, props['lighting_schedule'])
  else
    case_lighting_schedule = model.alwaysOnDiscreteSchedule
  end
  fraction_of_lighting_energy_to_case = props['fraction_of_lighting_energy_to_case']
  if props['latent_case_credit_curve_name']
    latent_case_credit_curve = model_add_curve(model, props['latent_case_credit_curve_name'])
  end
  defrost_power_per_length = OpenStudio.convert(props['defrost_power_per_length'], 'W/ft', 'W/m').get
  defrost_type = props['defrost_type']
  if props['defrost_correction_type']
    defrost_correction_type = props['defrost_correction_type']
  end
  if props['defrost_correction_curve_name']
    defrost_correction_curve_name = model_add_curve(model, props['defrost_correction_curve_name'])
  end
  if props['anti_sweat_power']
    anti_sweat_power = OpenStudio.convert(props['anti_sweat_power'], 'W/ft', 'W/m').get
  end
  if props['minimum_anti_sweat_heater_power_per_unit_length']
    minimum_anti_sweat_heater_power_per_unit_length = OpenStudio.convert(props['minimum_anti_sweat_heater_power_per_unit_length'], 'W/ft', 'W/m').get
  end
  if props['anti_sweat_heater_control']
    if props['anti_sweat_heater_control'] == 'RelativeHumidity'
      anti_sweat_heater_control = 'Linear'
    else
      anti_sweat_heater_control = props['anti_sweat_heater_control']
    end
  end
  if props['fractionofantisweatheaterenergytocase']
    fractionofantisweatheaterenergytocase = props['fractionofantisweatheaterenergytocase']
  end

  # Case
  ref_case = OpenStudio::Model::RefrigerationCase.new(model, model.alwaysOnDiscreteSchedule)
  ref_case.setName(case_type)
  ref_case.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  ref_case.setThermalZone(thermal_zone)
  ref_case.setRatedAmbientTemperature(OpenStudio.convert(75, 'F', 'C').get)
  ref_case.setRatedLatentHeatRatio(props['latent_heat_ratio']) if props['latent_heat_ratio']
  ref_case.setRatedRuntimeFraction(props['rated_runtime_fraction']) if props['rated_runtime_fraction']
  ref_case.setCaseLength(case_length)
  ref_case.setCaseOperatingTemperature(case_temp)
  ref_case.setRatedTotalCoolingCapacityperUnitLength(cooling_capacity_per_length)
  cooling_capacity_w = ref_case.caseLength * ref_case.ratedTotalCoolingCapacityperUnitLength
  cooling_capacity_btu_per_hr = OpenStudio.convert(cooling_capacity_w, 'W', 'Btu/hr').get
  ref_case.setStandardCaseFanPowerperUnitLength(evap_fan_power_per_length)
  ref_case.setOperatingCaseFanPowerperUnitLength(evap_fan_power_per_length)
  if props['evap_temp']
    ref_case.setDesignEvaporatorTemperatureorBrineInletTemperature(evap_temp_c)
  end
  ref_case.setStandardCaseLightingPowerperUnitLength(lighting_w_per_m)
  ref_case.setInstalledCaseLightingPowerperUnitLength(lighting_w_per_m)
  ref_case.setCaseLightingSchedule(case_lighting_schedule)

  if props['latent_case_credit_curve_name']
    ref_case.setLatentCaseCreditCurve(latent_case_credit_curve)
  end
  ref_case.setCaseDefrostPowerperUnitLength(defrost_power_per_length)
  if props['defrost_type']
    ref_case.setCaseDefrostType(defrost_type)
  end
  ref_case.setDefrostEnergyCorrectionCurveType(defrost_correction_type)
  if props['defrost_correction_curve_name']
    ref_case.setDefrostEnergyCorrectionCurve(defrost_correction_curve_name)
  end
  if props['anti_sweat_power']
    ref_case.setCaseAntiSweatHeaterPowerperUnitLength(anti_sweat_power)
  end
  ref_case.setFractionofAntiSweatHeaterEnergytoCase(fractionofantisweatheaterenergytocase)
  if props['fraction_of_lighting_energy_to_case']
    ref_case.setFractionofLightingEnergytoCase(fraction_of_lighting_energy_to_case)
  end
  if props['minimum_anti_sweat_heater_power_per_unit_length']
    ref_case.setMinimumAntiSweatHeaterPowerperUnitLength(minimum_anti_sweat_heater_power_per_unit_length)
  end
  if props['anti_sweat_heater_control']
    ref_case.setAntiSweatHeaterControlType(anti_sweat_heater_control)
  end
  ref_case.setHumidityatZeroAntiSweatHeaterEnergy(0)
  if props['under_case_hvac_return_air_fraction']
    ref_case.setUnderCaseHVACReturnAirFraction(props['under_case_hvac_return_air_fraction'])
  else
    ref_case.setUnderCaseHVACReturnAirFraction(0)
  end
  if props['restocking_schedule']
    if props['restocking_schedule'].downcase == 'always off'
      # restocking_sch = model.alwaysOffDiscreteSchedule
      ref_case.resetRefrigeratedCaseRestockingSchedule
    else
      restocking_sch = model_add_schedule(model, props['restocking_schedule'])
      ref_case.setRefrigeratedCaseRestockingSchedule(restocking_sch)
    end
  else
    ref_case.resetRefrigeratedCaseRestockingSchedule
  end

  if props['case_category']
    ref_case_addprops = ref_case.additionalProperties
    ref_case_addprops.setFeature('case_category', props['case_category'])
  end

  length_ft = OpenStudio.convert(case_length, 'm', 'ft').get
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Added #{length_ft.round} ft display case called #{case_type} with a cooling capacity of #{cooling_capacity_btu_per_hr.round} Btu/hr to #{thermal_zone.name}.")

  return ref_case
end
model_add_refrigeration_compressor(model, compressor_name) click to toggle source

Adds a refrigeration compressor to the model

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::RefrigerationCompressor] the refrigeration compressor

# File lib/openstudio-standards/prototypes/common/objects/Prototype.refrigeration.rb, line 357
def model_add_refrigeration_compressor(model, compressor_name)
  # Get the compressor properties
  search_criteria = {
    'template' => template,
    'compressor_name' => compressor_name
  }

  props = model_find_object(standards_data['refrigeration_compressors'], search_criteria)
  if props.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Could not find refrigeration compressor properties for: #{search_criteria}.")
    return nil
  end

  # Performance curves
  pwr_curve_name = props['power_curve']
  cap_curve_name = props['capacity_curve']

  # Make the compressor
  compressor = OpenStudio::Model::RefrigerationCompressor.new(model)
  compressor.setRefrigerationCompressorPowerCurve(model_add_curve(model, pwr_curve_name))
  compressor.setRefrigerationCompressorCapacityCurve(model_add_curve(model, cap_curve_name))

  return compressor
end
model_add_refrigeration_system(model, compressor_type, system_name, cases, walkins, thermal_zone) click to toggle source

Adds a full commercial refrigeration rack to the model, as would be found in a supermarket @todo Move refrigeration compressors to spreadsheet

@param model [OpenStudio::Model::Model] OpenStudio model object @param compressor_type [String] the system temperature range

valid choices are Low Temp, Med Temp

@param system_name [String] the name of the refrigeration system @param cases [Array<Hash>] an array of cases with keys: case_type and space_names @param walkins [Array<Hashs>] an array of walkins with keys:

walkin_type, space_names, and number_of_walkins

@param thermal_zone [OpenStudio::Model::ThermalZone] the thermal zone where the refrigeration piping is located @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.refrigeration.rb, line 860
def model_add_refrigeration_system(model,
                                   compressor_type,
                                   system_name,
                                   cases,
                                   walkins,
                                   thermal_zone)

  # Refrigeration system
  ref_sys = OpenStudio::Model::RefrigerationSystem.new(model)
  ref_sys.setName(system_name.to_s)
  ref_sys.setSuctionPipingZone(thermal_zone)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model',
                     "Adding #{compressor_type} refrigeration system called #{system_name} with #{cases.size} cases and #{walkins.size} walkins.")

  # Compressors (20 for each system)
  for i in 0...20
    compressor = model_add_refrigeration_compressor(model, compressor_type)
    ref_sys.addCompressor(compressor)
  end

  size_category = 'Any'
  # Cases
  cooling_cap = 0
  i = 0
  cases.each do |case_|
    zone = model_get_zones_from_spaces_on_system(model, case_)[0]
    ref_case = model_add_refrigeration_case(model, zone, case_['case_type'], size_category)
    return false if ref_case.nil?

    ########################################
    # Defrost schedule
    defrost_sch = OpenStudio::Model::ScheduleRuleset.new(model)
    defrost_sch.setName('Refrigeration Defrost Schedule')
    defrost_sch.defaultDaySchedule.setName('Refrigeration Defrost Schedule Default')
    defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i, 0, 0), 0)
    defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i, 59, 0), 0)
    defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0)
    # Dripdown schedule
    dripdown_sch = OpenStudio::Model::ScheduleRuleset.new(model)
    dripdown_sch.setName('Refrigeration Defrost Schedule')
    dripdown_sch.defaultDaySchedule.setName('Refrigeration Defrost Schedule Default')
    dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i, 0, 0), 0)
    dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i, 59, 0), 0)
    dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0)
    # Case Credit Schedule
    case_credit_sch = OpenStudio::Model::ScheduleRuleset.new(model)
    case_credit_sch.setName('Refrigeration Case Credit Schedule')
    case_credit_sch.defaultDaySchedule.setName('Refrigeration Case Credit Schedule Default')
    case_credit_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 7, 0, 0), 0.2)
    case_credit_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 21, 0, 0), 0.4)
    case_credit_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0.2)
    ref_case.setCaseDefrostSchedule(defrost_sch)
    ref_case.setCaseDefrostDripDownSchedule(dripdown_sch)
    ref_case.setCaseCreditFractionSchedule(case_credit_sch)
    ########################################
    ref_sys.addCase(ref_case)
    i += 1
  end

  # Walkins
  walkins.each do |walkin|
    for i in 0...walkin['number_of_walkins']

      zone = model_get_zones_from_spaces_on_system(model, walkin)[0]
      ref_walkin = model_add_refrigeration_walkin(model, zone, size_category, walkin['walkin_type'])
      return false if ref_walkin.nil?

      ########################################
      # Defrost schedule
      defrost_sch = OpenStudio::Model::ScheduleRuleset.new(model)
      defrost_sch.setName('Refrigeration Defrost Schedule')
      defrost_sch.defaultDaySchedule.setName('Refrigeration Defrost Schedule Default')
      defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i, 0, 0), 0)
      defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i, 59, 0), 1)
      defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i + 10, 0, 0), 0)
      defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i + 10, 59, 0), 1)
      defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0)
      # Dripdown schedule
      dripdown_sch = OpenStudio::Model::ScheduleRuleset.new(model)
      dripdown_sch.setName('Refrigeration Defrost Schedule')
      dripdown_sch.defaultDaySchedule.setName('Refrigeration Defrost Schedule Default')
      dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i, 0, 0), 0)
      dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i, 59, 0), 1)
      dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i + 10, 0, 0), 0)
      dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, i + 10, 59, 0), 1)
      dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0)
      ref_walkin.setDefrostSchedule(defrost_sch)
      ref_walkin.setDefrostDripDownSchedule(dripdown_sch)
      ref_sys.addWalkin(ref_walkin)
      ########################################
      cooling_cap += ref_walkin.ratedCoilCoolingCapacity # calculate total cooling capacity of the cases + walkins
    end
  end

  # Condenser capacity
  # The heat rejection rate from the condenser is equal to the rated capacity of all the display cases and walk-ins connected to the compressor rack
  # plus the power rating of the compressors making up the compressor rack.
  # Assuming a COP of 1.3 for low-temperature compressor racks and a COP of 2.0 for medium-temperature compressor racks,
  # the required condenser capacity is approximated as follows:
  # Note the factor 1.2 has been included to over-estimate the condenser size.  The total capacity of the display cases can be calculated
  # from their rated cooling capacity times the length of the cases.  The capacity of each of the walk-ins is specified directly.
  condensor_cap = if compressor_type == 'Low Temp'
                    1.2 * cooling_cap * (1 + 1 / 1.3)
                  else
                    1.2 * cooling_cap * (1 + 1 / 2.0)
                  end
  condenser_coefficient_2 = condensor_cap / 5.6
  condenser_curve = OpenStudio::Model::CurveLinear.new(model)
  condenser_curve.setCoefficient1Constant(0)
  condenser_curve.setCoefficient2x(condenser_coefficient_2)
  condenser_curve.setMinimumValueofx(1.4)
  condenser_curve.setMaximumValueofx(33.3)

  # Condenser fan power
  # The condenser fan power can be estimated from the heat rejection capacity of the condenser as follows:
  condenser_fan_pwr = 0.0441 * condensor_cap + 695

  # Condenser
  condenser = OpenStudio::Model::RefrigerationCondenserAirCooled.new(model)
  condenser.setRatedFanPower(condenser_fan_pwr)
  condenser.setRatedEffectiveTotalHeatRejectionRateCurve(condenser_curve)
  condenser.setCondenserFanSpeedControlType('Fixed')
  condenser.setMinimumFanAirFlowRatio(0.1)

  ref_sys.setRefrigerationCondenser(condenser)

  return true
end
model_add_refrigeration_walkin(model, thermal_zone, size_category, walkin_type) click to toggle source

Adds a refrigerated walkin unit to the model

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zone [OpenStudio::Model::ThermalZone] the thermal zone where the walkin is located,

and which will be impacted by the walkin's thermal load.

@param size_category [String] size category of the building area. Valid choices are:

"<35k ft2", "35k - 50k ft2", ">50k ft2"

@param walkin_type [String] the walkin type/name. For valid choices,

refer to the "Refrigerated Walkins" tab on the OpenStudio_Standards spreadsheet.
This parameter is used also by the "Refrigeration System Lineup" tab.

@return [OpenStudio::Model::RefrigerationWalkIn] the walk in refrigerator

# File lib/openstudio-standards/prototypes/common/objects/Prototype.refrigeration.rb, line 160
def model_add_refrigeration_walkin(model, thermal_zone, size_category, walkin_type)
  # Get the walkin properties
  search_criteria = {
    'template' => template,
    'size_category' => size_category,
    'walkin_type' => walkin_type
  }

  props = model_find_object(standards_data['refrigeration_walkins'], search_criteria)
  if props.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Could not find walkin properties for: #{search_criteria}.")
    return nil
  end

  # Capacity, defrost, lighting
  walkin_type = props['walkin_type']
  if props['rated_cooling_capacity']
    rated_cooling_capacity = OpenStudio.convert(props['rated_cooling_capacity'], 'Btu/h', 'W').get
  end
  if props['cooling_capacity_c0']
    cooling_capacity_c0 = OpenStudio.convert(OpenStudio.convert(props['cooling_capacity_c0'], 'Btu/h', 'W').get, 'W/ft', 'W/m').get
  end
  if props['cooling_capacity_c1']
    cooling_capacity_c1 = OpenStudio.convert(OpenStudio.convert(props['cooling_capacity_c1'], 'Btu/h', 'W').get, 'W/ft', 'W/m').get
  end
  if props['cooling_capacity_c2']
    cooling_capacity_c2 = OpenStudio.convert(OpenStudio.convert(props['cooling_capacity_c2'], 'Btu/h', 'W').get, 'W/ft', 'W/m').get
  end
  if props['fan_power_mult']
    fan_power_mult = props['fan_power_mult']
  end
  if props['lighting_power_mult']
    lighting_power_mult = props['lighting_power_mult']
  end
  if props['reachin_door_area_mult']
    reachin_door_area_mult = OpenStudio.convert(props['reachin_door_area_mult'], 'ft^2', 'm^2').get
  end
  operating_temp = OpenStudio.convert(props['operating_temp'], 'F', 'C').get
  if props['source_temp']
    source_temp = OpenStudio.convert(props['source_temp'], 'F', 'C').get
  end
  if props['defrost_control_type']
    defrost_control_type = props['defrost_control_type']
  end
  defrost_type = props['defrost_type']
  defrost_power_mult = props['defrost_power_mult']
  defrost_power = props['defrost_power']
  ratedtotalheatingpower = props['ratedtotalheatingpower']
  ratedcirculationfanpower = props['ratedcirculationfanpower']
  fan_power = props['fan_power']
  lighting_power = props['lighting_power']
  # lighting_power_mult = props_ref_system['lighting_power_mult']
  if props['insulated_floor_u']
    insulated_floor_u = OpenStudio.convert(props['insulated_floor_u'], 'Btu/ft^2*h*R', 'W/m^2*K').get
  end
  if props['insulated_surface_u']
    insulated_surface_u = OpenStudio.convert(props['insulated_surface_u'], 'Btu/ft^2*h*R', 'W/m^2*K').get
  end
  if props['stocking_door_u']
    insulated_door_u = OpenStudio.convert(props['stocking_door_u'], 'Btu/ft^2*h*R', 'W/m^2*K').get
  end
  if props['glass_reachin_door_u_value']
    glass_reachin_door_u_value = OpenStudio.convert(props['glass_reachin_door_u_value'], 'Btu/ft^2*h*R', 'W/m^2*K').get
  end
  if props['reachin_door_area']
    reachin_door_area = OpenStudio.convert(props['reachin_door_area'], 'ft^2', 'm^2').get
  else
    reachin_door_area = 0.0
  end
  if props['total_insulated_surface_area']
    total_insulated_surface_area = OpenStudio.convert(props['total_insulated_surface_area'], 'ft^2', 'm^2').get
  end
  if props['height_of_glass_reachin_doors']
    height_of_glass_reachin_doors = OpenStudio.convert(props['height_of_glass_reachin_doors'], 'ft', 'm').get
  end
  if props['area_of_stocking_doors']
    area_of_stocking_doors = OpenStudio.convert(props['area_of_stocking_doors'], 'ft^2', 'm^2').get
  end
  if props['floor_surface_area']
    floor_surface_area = OpenStudio.convert(props['floor_surface_area'], 'ft^2', 'm^2').get
  end
  if props['height_of_stocking_doors']
    height_of_stocking_doors = OpenStudio.convert(props['height_of_stocking_doors'], 'ft', 'm').get
  end
  lightingschedule = props['lighting_schedule']
  temperatureterminationdefrostfractiontoice = props['temperatureterminationdefrostfractiontoice']

  # Calculated properties
  if rated_cooling_capacity.nil?
    rated_cooling_capacity = cooling_capacity_c2 * (floor_surface_area ^ 2) + cooling_capacity_c1 * floor_surface_area + cooling_capacity_c0
  end
  if defrost_power.nil?
    defrost_power = defrost_power_mult * rated_cooling_capacity
  end
  if total_insulated_surface_area.nil?
    total_insulated_surface_area = 1.7226 * floor_surface_area + 28.653
  end
  if fan_power.nil?
    fan_power = fan_power_mult * rated_cooling_capacity
  end
  if lighting_power.nil?
    lighting_power = lighting_power_mult * floor_surface_area
  end

  # Walk-In
  ref_walkin = OpenStudio::Model::RefrigerationWalkIn.new(model, model.alwaysOnDiscreteSchedule)
  ref_walkin.setName(walkin_type.to_s)
  ref_walkin.setZoneBoundaryThermalZone(thermal_zone)
  ref_walkin.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  ref_walkin.setRatedCoilCoolingCapacity(rated_cooling_capacity)
  rated_cooling_capacity_btu_per_hr = OpenStudio.convert(rated_cooling_capacity, 'W', 'Btu/hr').get
  ref_walkin.setOperatingTemperature(operating_temp)
  if props['source_temp']
    ref_walkin.setRatedCoolingSourceTemperature(source_temp)
  end
  if props['defrost_control_type']
    ref_walkin.setDefrostControlType(defrost_control_type)
  end
  ref_walkin.setDefrostType(defrost_type)
  ref_walkin.setDefrostPower(defrost_power)
  if props['ratedtotalheatingpower']
    ref_walkin.setRatedTotalHeatingPower(ratedtotalheatingpower)
  end
  if props['ratedcirculationfanpower']
    ref_walkin.setRatedCirculationFanPower(ratedcirculationfanpower)
  end
  ref_walkin.setRatedCoolingCoilFanPower(fan_power)
  ref_walkin.setRatedTotalLightingPower(lighting_power)
  if props['insulated_floor_u']
    ref_walkin.setInsulatedFloorUValue(insulated_floor_u)
  end
  if props['insulated_surface_u']
    ref_walkin.setZoneBoundaryInsulatedSurfaceUValueFacingZone(insulated_surface_u)
  end
  if props['stocking_door_u']
    ref_walkin.setZoneBoundaryStockingDoorUValueFacingZone(insulated_door_u)
  end
  if props['reachin_door_area']
    ref_walkin.setZoneBoundaryAreaofGlassReachInDoorsFacingZone(reachin_door_area)
  end
  if props['total_insulated_surface_area']
    ref_walkin.setZoneBoundaryTotalInsulatedSurfaceAreaFacingZone(total_insulated_surface_area)
  end
  if props['area_of_stocking_doors']
    ref_walkin.setZoneBoundaryAreaofStockingDoorsFacingZone(area_of_stocking_doors)
  end
  if props['floor_surface_area']
    ref_walkin.setInsulatedFloorSurfaceArea(floor_surface_area)
  end
  if props['height_of_glass_reachin_doors']
    ref_walkin.setZoneBoundaryHeightofGlassReachInDoorsFacingZone(height_of_glass_reachin_doors)
  end
  if props['height_of_stocking_doors']
    ref_walkin.setZoneBoundaryHeightofStockingDoorsFacingZone(height_of_stocking_doors)
  end
  if props['glass_reachin_door_u_value']
    ref_walkin.setZoneBoundaryGlassReachInDoorUValueFacingZone(glass_reachin_door_u_value)
  end
  if props['temperatureterminationdefrostfractiontoice']
    ref_walkin.setTemperatureTerminationDefrostFractiontoIce(temperatureterminationdefrostfractiontoice)
  end

  if props['restocking_schedule']
    if props['restocking_schedule'].downcase == 'always off'
      # restocking_sch = model.alwaysOffDiscreteSchedule
      ref_walkin.resetRestockingSchedule
    else
      restocking_sch = model_add_schedule(model, props['restocking_schedule'])
      ref_walkin.setRestockingSchedule(restocking_sch)
    end
  else
    ref_walkin.resetRestockingSchedule
  end

  ref_walkin.setLightingSchedule(model_add_schedule(model, lightingschedule))
  ref_walkin.setZoneBoundaryStockingDoorOpeningScheduleFacingZone(model_add_schedule(model, 'door_wi_sched'))

  ref_walkin_addprops = ref_walkin.additionalProperties
  ref_walkin_addprops.setFeature('motor_category', props['motor_category'])

  # Add doorway protection
  if props['doorway_protection_type']
    ref_walkin.zoneBoundaries.each do |zb|
      zb.setStockingDoorOpeningProtectionTypeFacingZone(props['doorway_protection_type'])
    end
  end

  insulated_floor_area_ft2 = OpenStudio.convert(floor_surface_area, 'm^2', 'ft^2').get
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Added #{insulated_floor_area_ft2.round} ft2 walkin called #{walkin_type} with a capacity of #{rated_cooling_capacity_btu_per_hr.round} Btu/hr to #{thermal_zone.name}.")

  return ref_walkin
end
model_add_residential_erv(model, thermal_zone, min_oa_flow_m3_per_s_per_m2 = nil) click to toggle source

Add a residential ERV: standalone ERV that operates to provide OA, used in conjuction with a system that having mechanical cooling and a heating coil

@param model [OpenStudio::Model::Model] OpenStudio Model object @param thermal_zone [OpenStudio::Model::ThermalZone] OpenStudio ThermalZone object @return [OpenStudio::Model::ZoneHVACEnergyRecoveryVentilator] Standalone ERV

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 5917
def model_add_residential_erv(model,
                              thermal_zone,
                              min_oa_flow_m3_per_s_per_m2 = nil)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding standalone ERV for #{thermal_zone.name}.")

  # Determine ERR and design basis when energy recovery is required
  #
  # enthalpy_recovery_ratio = nil will trigger an ERV with no effectiveness that only provides OA
  enthalpy_recovery_ratio = nil
  climate_zone = OpenstudioStandards::Weather.model_get_climate_zone(model)
  case template
    when '90.1-2019'
      search_criteria = {
        'template' => template,
        'climate_zone' => climate_zone,
        'under_8000_hours' => false,
        'nontransient_dwelling' => true
      }
    else
      search_criteria = {
        'template' => template,
        'climate_zone' => climate_zone,
        'under_8000_hours' => false
      }
  end

  erv_enthalpy_recovery_ratio = model_find_object(standards_data['energy_recovery'], search_criteria)

  # Extract ERR from data lookup
  if !erv_enthalpy_recovery_ratio.nil?
    if erv_enthalpy_recovery_ratio['enthalpy_recovery_ratio'].nil? & erv_enthalpy_recovery_ratio['enthalpy_recovery_ratio_design_conditions'].nil?
      # If not included in the data, an enthalpy
      # recovery ratio (ERR) of 50% is used
      enthalpy_recovery_ratio = 0.5
      case climate_zone
        when 'ASHRAE 169-2006-6B',
          'ASHRAE 169-2013-6B',
          'ASHRAE 169-2006-7A',
          'ASHRAE 169-2013-7A',
          'ASHRAE 169-2006-7B',
          'ASHRAE 169-2013-7B',
          'ASHRAE 169-2006-8A',
          'ASHRAE 169-2013-8A',
          'ASHRAE 169-2006-8B',
          'ASHRAE 169-2013-8B'
          design_conditions = 'heating'
        else
          design_conditions = 'cooling'
      end
    else
      design_conditions = erv_enthalpy_recovery_ratio['enthalpy_recovery_ratio_design_conditions'].downcase
      enthalpy_recovery_ratio = erv_enthalpy_recovery_ratio['enthalpy_recovery_ratio']
    end
  end

  # # Fan power with energy recovery = 0.934 W/cfm
  supply_fan = create_fan_by_name(model,
                                  'ERV_Supply_Fan',
                                  fan_name: "#{thermal_zone.name} ERV Supply Fan")
  exhaust_fan = create_fan_by_name(model,
                                   'ERV_Supply_Fan',
                                   fan_name: "#{thermal_zone.name} ERV Exhaust Fan")
  supply_fan.setMotorEfficiency(0.48)
  exhaust_fan.setMotorEfficiency(0.48)
  supply_fan.setFanTotalEfficiency(0.303158)
  exhaust_fan.setFanTotalEfficiency(0.303158)
  supply_fan.setPressureRise(270.64755)
  exhaust_fan.setPressureRise(270.64755)


  # Create ERV Controller
  erv_controller = OpenStudio::Model::ZoneHVACEnergyRecoveryVentilatorController.new(model)
  erv_controller.setName("#{thermal_zone.name} ERV Controller")
  erv_controller.setControlHighIndoorHumidityBasedonOutdoorHumidityRatio(false)

  # Create heat exchanger
  heat_exchanger = OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent.new(model)
  heat_exchanger.setName("#{thermal_zone.name} ERV HX")
  heat_exchanger.setSupplyAirOutletTemperatureControl(false)
  heat_exchanger.setHeatExchangerType('Rotary')
  heat_exchanger.setEconomizerLockout(false)
  heat_exchanger.setFrostControlType('ExhaustOnly')
  heat_exchanger.setThresholdTemperature(-23.3)
  heat_exchanger.setInitialDefrostTimeFraction(0.167)
  heat_exchanger.setRateofDefrostTimeFractionIncrease(1.44)
  heat_exchanger.setAvailabilitySchedule(model_add_schedule(model, 'Always On - No Design Day'))
  heat_exchanger_air_to_air_sensible_and_latent_apply_prototype_efficiency_enthalpy_recovery_ratio(heat_exchanger, enthalpy_recovery_ratio, design_conditions, climate_zone)

  erv = OpenStudio::Model::ZoneHVACEnergyRecoveryVentilator.new(model, heat_exchanger, supply_fan, exhaust_fan)
  erv.setName("#{thermal_zone.name} ERV")

  erv.setController(erv_controller)
  erv.addToThermalZone(thermal_zone)

  # Set OA requirements; Assumes a default of 55 cfm
  if min_oa_flow_m3_per_s_per_m2.nil?
    erv.setSupplyAirFlowRate(OpenStudio.convert(55.0, 'cfm', 'm^3/s').get)
    erv.setExhaustAirFlowRate(OpenStudio.convert(55.0, 'cfm', 'm^3/s').get)
  else
    erv.setVentilationRateperUnitFloorArea(min_oa_flow_m3_per_s_per_m2)
  end
  erv.setVentilationRateperOccupant(0.0)

  # Ensure the ERV takes priority, so ventilation load is included when treated by other zonal systems
  # From EnergyPlus I/O reference:
  # "For situations where one or more equipment types has limited capacity or limited control capability, order the
  #  sequence so that the most controllable piece of equipment runs last. For example, with a dedicated outdoor air
  #  system (DOAS), the air terminal for the DOAS should be assigned Heating Sequence = 1 and Cooling Sequence = 1.
  #  Any other equipment should be assigned sequence 2 or higher so that it will see the net load after the DOAS air
  #  is added to the zone."
  thermal_zone.setCoolingPriority(erv.to_ModelObject.get, 1)
  thermal_zone.setHeatingPriority(erv.to_ModelObject.get, 1)

  return erv
end
model_add_residential_ventilator(model, thermal_zone, min_oa_flow_m3_per_s_per_m2 = nil) click to toggle source

Add a residential ventilation: standalone unit ventilation and zone exhaust that operates to provide OA, used in conjuction with a system that having mechanical cooling and a heating coil

@param model [OpenStudio::Model::Model] OpenStudio Model object @param thermal_zone [OpenStudio::Model::ThermalZone] OpenStudio ThermalZone object @return [OpenStudio::Model::ZoneHVACUnitVentilator] Standalone Unit Ventilator

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6040
def model_add_residential_ventilator(model,
                                     thermal_zone,
                                     min_oa_flow_m3_per_s_per_m2 = nil)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding standalone unit ventilator for #{thermal_zone.name}.")

  # Fan power with no energy recovery = 0.806 W/cfm
  supply_fan = create_fan_by_name(model,
                                  'ERV_Supply_Fan',
                                  fan_name: "#{thermal_zone.name} Ventilator Supply Fan")
  supply_fan.setMotorEfficiency(0.48)
  supply_fan.setFanTotalEfficiency(0.303158)
  supply_fan.setPressureRise(233.6875)

  unit_ventilator = OpenStudio::Model::ZoneHVACUnitVentilator.new(model, supply_fan)
  unit_ventilator.setName("#{thermal_zone.name} Unit Ventilator")
  unit_ventilator.addToThermalZone(thermal_zone)
  fan_zone_exhaust = create_fan_zone_exhaust(model,
                                             fan_name: "#{thermal_zone.name} Exhaust Fan",
                                             fan_efficiency: 0.303158,
                                             pressure_rise: 233.6875)

  # Set OA requirements; Assumes a default of 55 cfm
  if min_oa_flow_m3_per_s_per_m2.nil?
    unit_ventilator.setMaximumSupplyAirFlowRate(OpenStudio.convert(55.0, 'cfm', 'm^3/s').get)
    fan_zone_exhaust.setMaximumFlowRate(OpenStudio.convert(55.0, 'cfm', 'm^3/s').get)
  else
    unit_ventilator.setMaximumSupplyAirFlowRate(min_oa_flow_m3_per_s_per_m2)
    fan_zone_exhaust.setMaximumFlowRate(min_oa_flow_m3_per_s_per_m2)
  end

  # Ensure the unit ventilator takes priority, so ventilation load is included when treated by other zonal systems
  # From EnergyPlus I/O reference:
  # "For situations where one or more equipment types has limited capacity or limited control capability, order the
  #  sequence so that the most controllable piece of equipment runs last. For example, with a dedicated outdoor air
  #  system (DOAS), the air terminal for the DOAS should be assigned Heating Sequence = 1 and Cooling Sequence = 1.
  #  Any other equipment should be assigned sequence 2 or higher so that it will see the net load after the DOAS air
  #  is added to the zone."
  thermal_zone.setCoolingPriority(unit_ventilator.to_ModelObject.get, 1)
  thermal_zone.setHeatingPriority(unit_ventilator.to_ModelObject.get, 1)
end
model_add_schedule(model, schedule_name) click to toggle source

Create a schedule from the openstudio standards dataset and add it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param schedule_name [String} name of the schedule @return [ScheduleRuleset] the resulting schedule ruleset @todo make return an OptionalScheduleRuleset

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2754
def model_add_schedule(model, schedule_name)
  return nil if schedule_name.nil? || schedule_name == ''

  # First check model and return schedule if it already exists
  model.getSchedules.sort.each do |schedule|
    if schedule.name.get.to_s == schedule_name
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Already added schedule: #{schedule_name}")
      return schedule
    end
  end

  require 'date'

  # OpenStudio::logFree(OpenStudio::Info, 'openstudio.standards.Model', "Adding schedule: #{schedule_name}")

  # Find all the schedule rules that match the name
  rules = model_find_objects(standards_data['schedules'], 'name' => schedule_name)
  if rules.size.zero?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Cannot find data for schedule: #{schedule_name}, will not be created.")
    return model.alwaysOnDiscreteSchedule
  end

  # Make a schedule ruleset
  sch_ruleset = OpenStudio::Model::ScheduleRuleset.new(model)
  sch_ruleset.setName(schedule_name.to_s)

  # Loop through the rules, making one for each row in the spreadsheet
  rules.each do |rule|
    day_types = rule['day_types']
    start_date = DateTime.parse(rule['start_date'])
    end_date = DateTime.parse(rule['end_date'])
    sch_type = rule['type']
    values = rule['values']

    # Day Type choices: Wkdy, Wknd, Mon, Tue, Wed, Thu, Fri, Sat, Sun, WntrDsn, SmrDsn, Hol
    # Default
    if day_types.include?('Default')
      day_sch = sch_ruleset.defaultDaySchedule
      day_sch.setName("#{schedule_name} Default")
      model_add_vals_to_sch(model, day_sch, sch_type, values)
      if model.version < OpenStudio::VersionString.new('3.8.0')
        day_sch.setInterpolatetoTimestep(false)
      else
        day_sch.setInterpolatetoTimestep('No')
      end
    end

    # Winter Design Day
    if day_types.include?('WntrDsn')
      day_sch = OpenStudio::Model::ScheduleDay.new(model)
      sch_ruleset.setWinterDesignDaySchedule(day_sch)
      day_sch = sch_ruleset.winterDesignDaySchedule
      day_sch.setName("#{schedule_name} Winter Design Day")
      model_add_vals_to_sch(model, day_sch, sch_type, values)
      if model.version < OpenStudio::VersionString.new('3.8.0')
        day_sch.setInterpolatetoTimestep(false)
      else
        day_sch.setInterpolatetoTimestep('No')
      end
    end

    # Summer Design Day
    if day_types.include?('SmrDsn')
      day_sch = OpenStudio::Model::ScheduleDay.new(model)
      sch_ruleset.setSummerDesignDaySchedule(day_sch)
      day_sch = sch_ruleset.summerDesignDaySchedule
      day_sch.setName("#{schedule_name} Summer Design Day")
      model_add_vals_to_sch(model, day_sch, sch_type, values)
      if model.version < OpenStudio::VersionString.new('3.8.0')
        day_sch.setInterpolatetoTimestep(false)
      else
        day_sch.setInterpolatetoTimestep('No')
      end
    end

    # Other days (weekdays, weekends, etc)
    if day_types.include?('Wknd') ||
       day_types.include?('Wkdy') ||
       day_types.include?('Sat') ||
       day_types.include?('Sun') ||
       day_types.include?('Mon') ||
       day_types.include?('Tue') ||
       day_types.include?('Wed') ||
       day_types.include?('Thu') ||
       day_types.include?('Fri')

      # Make the Rule
      sch_rule = OpenStudio::Model::ScheduleRule.new(sch_ruleset)
      day_sch = sch_rule.daySchedule
      day_sch.setName("#{schedule_name} #{day_types} Day")
      model_add_vals_to_sch(model, day_sch, sch_type, values)
      if model.version < OpenStudio::VersionString.new('3.8.0')
        day_sch.setInterpolatetoTimestep(false)
      else
        day_sch.setInterpolatetoTimestep('No')
      end

      # Set the dates when the rule applies
      sch_rule.setStartDate(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(start_date.month.to_i), start_date.day.to_i))
      sch_rule.setEndDate(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(end_date.month.to_i), end_date.day.to_i))

      # Set the days when the rule applies
      # Weekends
      if day_types.include?('Wknd')
        sch_rule.setApplySaturday(true)
        sch_rule.setApplySunday(true)
      end
      # Weekdays
      if day_types.include?('Wkdy')
        sch_rule.setApplyMonday(true)
        sch_rule.setApplyTuesday(true)
        sch_rule.setApplyWednesday(true)
        sch_rule.setApplyThursday(true)
        sch_rule.setApplyFriday(true)
      end
      # Individual Days
      sch_rule.setApplyMonday(true) if day_types.include?('Mon')
      sch_rule.setApplyTuesday(true) if day_types.include?('Tue')
      sch_rule.setApplyWednesday(true) if day_types.include?('Wed')
      sch_rule.setApplyThursday(true) if day_types.include?('Thu')
      sch_rule.setApplyFriday(true) if day_types.include?('Fri')
      sch_rule.setApplySaturday(true) if day_types.include?('Sat')
      sch_rule.setApplySunday(true) if day_types.include?('Sun')
    end
  end
  return sch_ruleset
end
model_add_split_ac(model, thermal_zones, cooling_type: 'Two Speed DX AC', heating_type: 'Single Speed Heat Pump', supplemental_heating_type: 'Gas', fan_type: 'Cycling', hvac_op_sch: nil, oa_damper_sch: nil, econ_max_oa_frac_sch: nil) click to toggle source

Creates a split DX AC system for each zone and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param cooling_type [String] valid choices are Two Speed DX AC, Single Speed DX AC, Single Speed Heat Pump @param heating_type [String] valid choices are Gas, Single Speed Heat Pump @param supplemental_heating_type [String] valid choices are Electric, Gas @param fan_type [String] valid choices are ConstantVolume, Cycling @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [String] name of the oa damper schedule, or nil in which case will be defaulted to always open @param econ_max_oa_frac_sch [String] name of the economizer maximum outdoor air fraction schedule @return [OpenStudio::Model::AirLoopHVAC] the resulting split AC air loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 3747
def model_add_split_ac(model,
                       thermal_zones,
                       cooling_type: 'Two Speed DX AC',
                       heating_type: 'Single Speed Heat Pump',
                       supplemental_heating_type: 'Gas',
                       fan_type: 'Cycling',
                       hvac_op_sch: nil,
                       oa_damper_sch: nil,
                       econ_max_oa_frac_sch: nil)

  # create a split AC for each group of thermal zones
  air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
  thermal_zones_name = thermal_zones.map(&:name).join(' - ')
  air_loop.setName("#{thermal_zones_name} SAC")

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # default design temperatures used across all air loops
  dsgn_temps = standard_design_sizing_temperatures

  # adjusted zone design heating temperature for split_ac
  dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
  dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['htg_dsgn_sup_air_temp_f'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_f']
  dsgn_temps['htg_dsgn_sup_air_temp_c'] = dsgn_temps['zn_htg_dsgn_sup_air_temp_c']

  # default design settings used across all air loops
  sizing_system = adjust_sizing_system(air_loop, dsgn_temps, min_sys_airflow_ratio: 1.0, sizing_option: 'NonCoincident')

  # air handler controls
  # add a setpoint manager single zone reheat to control the supply air temperature
  setpoint_mgr_single_zone_reheat = OpenStudio::Model::SetpointManagerSingleZoneReheat.new(model)
  setpoint_mgr_single_zone_reheat.setName("#{air_loop.name} Setpoint Manager SZ Reheat")
  setpoint_mgr_single_zone_reheat.setControlZone(thermal_zones[0])
  setpoint_mgr_single_zone_reheat.setMinimumSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
  setpoint_mgr_single_zone_reheat.setMaximumSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
  setpoint_mgr_single_zone_reheat.addToNode(air_loop.supplyOutletNode)

  # add the components to the air loop in order from closest to zone to furthest from zone
  # create fan
  fan = nil
  if fan_type == 'ConstantVolume'
    fan = create_fan_by_name(model,
                             'Split_AC_CAV_Fan',
                             fan_name: "#{air_loop.name} Fan",
                             end_use_subcategory: 'CAV System Fans')
    fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  elsif fan_type == 'Cycling'
    fan = create_fan_by_name(model,
                             'Split_AC_Cycling_Fan',
                             fan_name: "#{air_loop.name} Fan",
                             end_use_subcategory: 'CAV System Fans')
    fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "fan_type #{fan_type} invalid for split AC system.")
  end
  fan.addToNode(air_loop.supplyInletNode) unless fan.nil?

  # create supplemental heating coil
  if supplemental_heating_type == 'Electric'
    create_coil_heating_electric(model,
                                 air_loop_node: air_loop.supplyInletNode,
                                 name: "#{air_loop.name} Electric Backup Htg Coil")
  elsif supplemental_heating_type == 'Gas'
    create_coil_heating_gas(model,
                            air_loop_node: air_loop.supplyInletNode,
                            name: "#{air_loop.name} Gas Backup Htg Coil")
  end

  # create heating coil
  if heating_type == 'Gas'
    htg_coil = create_coil_heating_gas(model,
                                       air_loop_node: air_loop.supplyInletNode,
                                       name: "#{air_loop.name} Gas Htg Coil")
    htg_part_load_fraction_correlation = OpenStudio::Model::CurveCubic.new(model)
    htg_part_load_fraction_correlation.setCoefficient1Constant(0.8)
    htg_part_load_fraction_correlation.setCoefficient2x(0.2)
    htg_part_load_fraction_correlation.setCoefficient3xPOW2(0.0)
    htg_part_load_fraction_correlation.setCoefficient4xPOW3(0.0)
    htg_part_load_fraction_correlation.setMinimumValueofx(0.0)
    htg_part_load_fraction_correlation.setMaximumValueofx(1.0)
    htg_coil.setPartLoadFractionCorrelationCurve(htg_part_load_fraction_correlation)
  elsif heating_type == 'Single Speed Heat Pump'
    create_coil_heating_dx_single_speed(model,
                                        air_loop_node: air_loop.supplyInletNode,
                                        name: "#{air_loop.name} HP Htg Coil")
  end

  # create cooling coil
  if cooling_type == 'Two Speed DX AC'
    create_coil_cooling_dx_two_speed(model,
                                     air_loop_node: air_loop.supplyInletNode,
                                     name: "#{air_loop.name} 2spd DX AC Clg Coil")
  elsif cooling_type == 'Single Speed DX AC'
    create_coil_cooling_dx_single_speed(model,
                                        air_loop_node: air_loop.supplyInletNode,
                                        name: "#{air_loop.name} 1spd DX AC Clg Coil", type: 'Split AC')
  elsif cooling_type == 'Single Speed Heat Pump'
    create_coil_cooling_dx_single_speed(model,
                                        air_loop_node: air_loop.supplyInletNode,
                                        name: "#{air_loop.name} 1spd DX HP Clg Coil", type: 'Heat Pump')
  end

  # create outdoor air controller
  oa_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
  oa_controller.setName("#{air_loop.name} OA System Controller")
  oa_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
  oa_controller.autosizeMinimumOutdoorAirFlowRate
  oa_controller.resetEconomizerMinimumLimitDryBulbTemperature
  oa_controller.setMaximumFractionofOutdoorAirSchedule(model_add_schedule(model, econ_max_oa_frac_sch)) unless econ_max_oa_frac_sch.nil?
  oa_system = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_controller)
  oa_system.setName("#{air_loop.name} OA System")
  oa_system.addToNode(air_loop.supplyInletNode)

  # set air loop availability controls after oa system added
  air_loop.setAvailabilitySchedule(hvac_op_sch)

  # create a diffuser and attach the zone/diffuser pair to the air loop
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding #{zone.name} to split DX AC system.")

    diffuser = OpenStudio::Model::AirTerminalSingleDuctUncontrolled.new(model, model.alwaysOnDiscreteSchedule)
    diffuser.setName("#{zone.name} SAC Diffuser")
    air_loop.multiAddBranchForZone(zone, diffuser.to_HVACComponent.get)

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneCoolingDesignSupplyAirHumidityRatio(0.008)
    sizing_zone.setZoneHeatingDesignSupplyAirHumidityRatio(0.008)
  end

  return air_loop
end
model_add_swh(model, building_type, prototype_input) click to toggle source

Add service water heating to the model

@param model [OpenStudio::Model::Model] OpenStudio model object @param building_type [String] building type @param prototype_input [Hash] hash of prototype inputs @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.swh.rb, line 8
def model_add_swh(model, building_type, prototype_input)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Started Adding Service Water Heating')

  # Add the main service water heating loop, if specified
  # for tall and super tall buildings, add main (multiple) and booster swh in model_custom_hvac_tweaks
  unless prototype_input['main_water_heater_volume'].nil? || (building_type == 'TallBuilding' || building_type == 'SuperTallBuilding')
    # Get the thermal zone for the water heater, if specified
    water_heater_zone = nil
    if prototype_input['main_water_heater_space_name']
      wh_space_name = prototype_input['main_water_heater_space_name']
      wh_space = model.getSpaceByName(wh_space_name)
      if wh_space.empty?
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "Cannot find a space called #{wh_space_name} in the model, water heater will not be placed in a zone.")
      else
        wh_zone = wh_space.get.thermalZone
        if wh_zone.empty?
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "Cannot find a zone that contains the space #{wh_space_name} in the model, water heater will not be placed in a zone.")
        else
          water_heater_zone = wh_zone.get
        end
      end
    end

    swh_fueltype = prototype_input['main_water_heater_fuel']
    # Add the main service water loop
    unless building_type == 'RetailStripmall' && template != 'NECB2011'
      main_swh_loop = model_add_swh_loop(model,
                                         'Main Service Water Loop',
                                         water_heater_zone,
                                         OpenStudio.convert(prototype_input['main_service_water_temperature'], 'F', 'C').get,
                                         prototype_input['main_service_water_pump_head'].to_f,
                                         prototype_input['main_service_water_pump_motor_efficiency'],
                                         OpenStudio.convert(prototype_input['main_water_heater_capacity'], 'Btu/hr', 'W').get,
                                         OpenStudio.convert(prototype_input['main_water_heater_volume'], 'gal', 'm^3').get,
                                         swh_fueltype,
                                         OpenStudio.convert(prototype_input['main_service_water_parasitic_fuel_consumption_rate'], 'Btu/hr', 'W').get)
    end

    # Attach the end uses if specified in prototype inputs
    # @todo remove special logic for large office SWH end uses
    # @todo remove special logic for stripmall SWH end uses and service water loops
    # @todo remove special logic for large hotel SWH end uses
    if building_type == 'LargeOffice' && template != 'NECB2011'

      # Only the core spaces have service water
      ['Core_bottom', 'Core_mid', 'Core_top'].sort.each do |space_name|
        # ['Mechanical_Bot_ZN_1','Mechanical_Mid_ZN_1','Mechanical_Top_ZN_1'].each do |space_name| # for new space type large office
        model_add_swh_end_uses(model,
                               'Main',
                               main_swh_loop,
                               OpenStudio.convert(prototype_input['main_service_water_peak_flowrate'], 'gal/min', 'm^3/s').get,
                               prototype_input['main_service_water_flowrate_schedule'],
                               OpenStudio.convert(prototype_input['main_water_use_temperature'], 'F', 'C').get,
                               space_name)
      end
    elsif building_type == 'LargeOfficeDetailed' && template != 'NECB2011'

      # Only mechanical rooms have service water
      ['Mechanical_Bot_ZN_1', 'Mechanical_Mid_ZN_1', 'Mechanical_Top_ZN_1'].sort.each do |space_name| # for new space type large office
        model_add_swh_end_uses(model,
                               'Main',
                               main_swh_loop,
                               OpenStudio.convert(prototype_input['main_service_water_peak_flowrate'], 'gal/min', 'm^3/s').get,
                               prototype_input['main_service_water_flowrate_schedule'],
                               OpenStudio.convert(prototype_input['main_water_use_temperature'], 'F', 'C').get,
                               space_name)
      end
    elsif building_type == 'RetailStripmall' && template != 'NECB2011'

      return true if template == 'DOE Ref Pre-1980' || template == 'DOE Ref 1980-2004'

      # Create a separate hot water loop & water heater for each space in the list
      swh_space_names = ['LGstore1', 'SMstore1', 'SMstore2', 'SMstore3', 'LGstore2', 'SMstore5', 'SMstore6']
      swh_sch_names = ['RetailStripmall Type1_SWH_SCH', 'RetailStripmall Type1_SWH_SCH', 'RetailStripmall Type2_SWH_SCH',
                       'RetailStripmall Type2_SWH_SCH', 'RetailStripmall Type3_SWH_SCH', 'RetailStripmall Type3_SWH_SCH',
                       'RetailStripmall Type3_SWH_SCH']
      rated_use_rate_gal_per_min = 0.03 # in gal/min
      rated_flow_rate_m3_per_s = OpenStudio.convert(rated_use_rate_gal_per_min, 'gal/min', 'm^3/s').get

      # Loop through all spaces
      swh_space_names.zip(swh_sch_names).sort.each do |swh_space_name, swh_sch_name|
        swh_thermal_zone = model.getSpaceByName(swh_space_name).get.thermalZone.get
        main_swh_loop = model_add_swh_loop(model,
                                           "#{swh_thermal_zone.name} Service Water Loop",
                                           swh_thermal_zone,
                                           OpenStudio.convert(prototype_input['main_service_water_temperature'], 'F', 'C').get,
                                           prototype_input['main_service_water_pump_head'].to_f,
                                           prototype_input['main_service_water_pump_motor_efficiency'],
                                           OpenStudio.convert(prototype_input['main_water_heater_capacity'], 'Btu/hr', 'W').get,
                                           OpenStudio.convert(prototype_input['main_water_heater_volume'], 'gal', 'm^3').get,
                                           prototype_input['main_water_heater_fuel'],
                                           OpenStudio.convert(prototype_input['main_service_water_parasitic_fuel_consumption_rate'], 'Btu/hr', 'W').get)

        model_add_swh_end_uses(model,
                               'Main',
                               main_swh_loop,
                               rated_flow_rate_m3_per_s,
                               swh_sch_name,
                               OpenStudio.convert(prototype_input['main_water_use_temperature'], 'F', 'C').get,
                               swh_space_name)
      end

    elsif prototype_input['main_service_water_peak_flowrate']
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.model.Model', 'Adding shw by main_service_water_peak_flowrate')

      # Attaches the end uses if specified as a lump value in the prototype_input
      model_add_swh_end_uses(model,
                             'Main',
                             main_swh_loop,
                             OpenStudio.convert(prototype_input['main_service_water_peak_flowrate'], 'gal/min', 'm^3/s').get,
                             prototype_input['main_service_water_flowrate_schedule'],
                             OpenStudio.convert(prototype_input['main_water_use_temperature'], 'F', 'C').get,
                             nil)

    else
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.model.Model', 'Adding shw by space_type_map')

      # Attaches the end uses if specified by space type
      space_type_map = @space_type_map

      if template == 'NECB2011'
        building_type = 'Space Function'
      end

      # Log how many water fixtures are added
      water_fixtures = []

      # Loop through spaces types and add service hot water if specified
      space_type_map.sort.each do |space_type_name, space_names|
        search_criteria = {
          'template' => template,
          'building_type' => model_get_lookup_name(building_type),
          'space_type' => space_type_name
        }
        data = standards_lookup_table_first(table_name: 'space_types', search_criteria: search_criteria)

        # Skip space types with no data
        next if data.nil?

        # Skip space types with no water use, unless it is a NECB archetype (these do not have peak flow rates defined)
        next unless template == 'NECB2011' || !data['service_water_heating_peak_flow_rate'].nil? || !data['service_water_heating_peak_flow_per_area'].nil?

        # Add a service water use for each space
        space_names.sort.each do |space_name|
          space = model.getSpaceByName(space_name).get
          space_multiplier = nil
          space_multiplier = case template
                               when 'NECB2011'
                                 # Added this to prevent double counting of zone multipliers.. space multipliers are never used in NECB archtypes.
                                 1
                               else
                                 space.multiplier
                             end

          water_fixture = model_add_swh_end_uses_by_space(model,
                                                          main_swh_loop,
                                                          space,
                                                          space_multiplier)
          unless water_fixture.nil?
            water_fixtures << water_fixture
          end
        end
      end

      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Added #{water_fixtures.size} water fixtures to model")
    end
  end

  # Add the booster water heater, if specified
  # for tall and super tall buildings, add main (multiple) and booster swh in model_custom_hvac_tweaks
  unless prototype_input['booster_water_heater_volume'].nil? || (building_type == 'TallBuilding' || building_type == 'SuperTallBuilding')
    # Add the booster water loop
    swh_booster_loop = model_add_swh_booster(model,
                                             main_swh_loop,
                                             OpenStudio.convert(prototype_input['booster_water_heater_capacity'], 'Btu/hr', 'W').get,
                                             OpenStudio.convert(prototype_input['booster_water_heater_volume'], 'gal', 'm^3').get,
                                             prototype_input['booster_water_heater_fuel'],
                                             OpenStudio.convert(prototype_input['booster_water_temperature'], 'F', 'C').get,
                                             0,
                                             nil)

    # Attach the end uses
    model_add_booster_swh_end_uses(model,
                                   swh_booster_loop,
                                   OpenStudio.convert(prototype_input['booster_service_water_peak_flowrate'], 'gal/min', 'm^3/s').get,
                                   prototype_input['booster_service_water_flowrate_schedule'],
                                   OpenStudio.convert(prototype_input['booster_water_use_temperature'], 'F', 'C').get)
  end

  # Add the laundry water heater, if specified
  # for tall and super tall buildings, add laundry swh in model_custom_hvac_tweaks
  unless prototype_input['laundry_water_heater_volume'].nil? || (building_type == 'TallBuilding' || building_type == 'SuperTallBuilding')
    # Add the laundry service water heating loop
    laundry_swh_loop = model_add_swh_loop(model,
                                          'Laundry Service Water Loop',
                                          nil,
                                          OpenStudio.convert(prototype_input['laundry_service_water_temperature'], 'F', 'C').get,
                                          prototype_input['laundry_service_water_pump_head'].to_f,
                                          prototype_input['laundry_service_water_pump_motor_efficiency'],
                                          OpenStudio.convert(prototype_input['laundry_water_heater_capacity'], 'Btu/hr', 'W').get,
                                          OpenStudio.convert(prototype_input['laundry_water_heater_volume'], 'gal', 'm^3').get,
                                          prototype_input['laundry_water_heater_fuel'],
                                          OpenStudio.convert(prototype_input['laundry_service_water_parasitic_fuel_consumption_rate'], 'Btu/hr', 'W').get)

    # Attach the end uses if specified in prototype inputs
    model_add_swh_end_uses(model,
                           'Laundry',
                           laundry_swh_loop,
                           OpenStudio.convert(prototype_input['laundry_service_water_peak_flowrate'], 'gal/min', 'm^3/s').get,
                           prototype_input['laundry_service_water_flowrate_schedule'],
                           OpenStudio.convert(prototype_input['laundry_water_use_temperature'], 'F', 'C').get,
                           nil)
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Finished adding Service Water Heating')

  return true
end
model_add_swh_booster(model, main_service_water_loop, water_heater_capacity, water_heater_volume, water_heater_fuel, booster_water_temperature, parasitic_fuel_consumption_rate, booster_water_heater_thermal_zone) click to toggle source

Creates a booster water heater and attaches it to the supplied service water heating loop.

@param model [OpenStudio::Model::Model] OpenStudio model object @param main_service_water_loop [OpenStudio::Model::PlantLoop] the main service water loop that this booster assists. @param water_heater_capacity [Double] water heater capacity, in W @param water_heater_volume [Double] water heater volume, in m^3 @param water_heater_fuel [Double] valid choices are Gas, Electric @param booster_water_temperature [Double] water heater temperature, in C @param parasitic_fuel_consumption_rate [Double] water heater parasitic fuel consumption rate, in W @param booster_water_heater_thermal_zone [OpenStudio::Model::ThermalZone] zones to place water heater in. If nil, will be assumed in 70F air for heat loss. @return [OpenStudio::Model::PlantLoop] the resulting booster water loop.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ServiceWaterHeating.rb, line 700
def model_add_swh_booster(model,
                          main_service_water_loop,
                          water_heater_capacity,
                          water_heater_volume,
                          water_heater_fuel,
                          booster_water_temperature,
                          parasitic_fuel_consumption_rate,
                          booster_water_heater_thermal_zone)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding booster water heater to #{main_service_water_loop.name}")

  # Booster water heating loop
  booster_service_water_loop = OpenStudio::Model::PlantLoop.new(model)
  booster_service_water_loop.setName('Service Water Loop')

  # Temperature schedule type limits
  temp_sch_type_limits = OpenstudioStandards::Schedules.create_schedule_type_limits(model,
                                                                                    name: 'Temperature Schedule Type Limits',
                                                                                    lower_limit_value: 0.0,
                                                                                    upper_limit_value: 100.0,
                                                                                    numeric_type: 'Continuous',
                                                                                    unit_type: 'Temperature')

  # Service water heating loop controls
  swh_temp_c = booster_water_temperature
  swh_temp_f = OpenStudio.convert(swh_temp_c, 'C', 'F').get
  swh_delta_t_r = 9 # 9F delta-T
  swh_delta_t_k = OpenStudio.convert(swh_delta_t_r, 'R', 'K').get
  swh_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                 swh_temp_c,
                                                                                 name: "Service Water Booster Temp - #{swh_temp_f}F",
                                                                                 schedule_type_limit: 'Temperature')
  swh_temp_sch.setScheduleTypeLimits(temp_sch_type_limits)
  swh_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, swh_temp_sch)
  swh_stpt_manager.setName('Hot water booster setpoint manager')
  swh_stpt_manager.addToNode(booster_service_water_loop.supplyOutletNode)
  sizing_plant = booster_service_water_loop.sizingPlant
  sizing_plant.setLoopType('Heating')
  sizing_plant.setDesignLoopExitTemperature(swh_temp_c)
  sizing_plant.setLoopDesignTemperatureDifference(swh_delta_t_k)

  # Booster water heating pump
  swh_pump = OpenStudio::Model::PumpVariableSpeed.new(model)
  swh_pump.setName('Booster Water Loop Pump')
  swh_pump.setRatedPumpHead(0.0) # As if there is no circulation pump
  swh_pump.setRatedPowerConsumption(0.0) # As if there is no circulation pump
  swh_pump.setMotorEfficiency(1)
  swh_pump.setPumpControlType('Continuous')
  swh_pump.setMinimumFlowRate(0.0)
  swh_pump.addToNode(booster_service_water_loop.supplyInletNode)

  # Water heater
  # @todo Standards - Change water heater methodology to follow
  # 'Model Enhancements Appendix A.'
  water_heater_capacity_btu_per_hr = OpenStudio.convert(water_heater_capacity, 'W', 'Btu/hr').get
  water_heater_capacity_kbtu_per_hr = OpenStudio.convert(water_heater_capacity_btu_per_hr, 'Btu/hr', 'kBtu/hr').get
  water_heater_vol_gal = OpenStudio.convert(water_heater_volume, 'm^3', 'gal').get

  # Water heater depends on the fuel type
  water_heater = OpenStudio::Model::WaterHeaterMixed.new(model)
  water_heater.setName("#{water_heater_vol_gal}gal #{water_heater_fuel} Booster Water Heater - #{water_heater_capacity_kbtu_per_hr.round}kBtu/hr")
  water_heater.setTankVolume(OpenStudio.convert(water_heater_vol_gal, 'gal', 'm^3').get)
  water_heater.setSetpointTemperatureSchedule(swh_temp_sch)
  water_heater.setDeadbandTemperatureDifference(2.0)
  water_heater.setEndUseSubcategory('Booster')

  if booster_water_heater_thermal_zone.nil?
    # Assume the water heater is indoors at 70F or 72F
    case template
    when '90.1-2004', '90.1-2007', '90.1-2010', '90.1-2013', '90.1-2016', '90.1-2019'
      indoor_temp = 71.6
    else
      indoor_temp = 70.0
    end
    default_water_heater_ambient_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                            OpenStudio.convert(indoor_temp, 'F', 'C').get,
                                                                                                            name: 'Water Heater Ambient Temp Schedule - ' + indoor_temp.to_s,
                                                                                                            schedule_type_limit: 'Temperature')
    default_water_heater_ambient_temp_sch.setScheduleTypeLimits(temp_sch_type_limits)
    water_heater.setAmbientTemperatureIndicator('Schedule')
    water_heater.setAmbientTemperatureSchedule(default_water_heater_ambient_temp_sch)
    water_heater.resetAmbientTemperatureThermalZone
  else
    water_heater.setAmbientTemperatureIndicator('ThermalZone')
    water_heater.setAmbientTemperatureThermalZone(booster_water_heater_thermal_zone)
    water_heater.resetAmbientTemperatureSchedule
  end

  water_heater.setMaximumTemperatureLimit(swh_temp_c)
  water_heater.setDeadbandTemperatureDifference(OpenStudio.convert(3.6, 'R', 'K').get)
  water_heater.setHeaterControlType('Cycle')
  water_heater.setHeaterMaximumCapacity(OpenStudio.convert(water_heater_capacity_btu_per_hr, 'Btu/hr', 'W').get)
  water_heater.setOffCycleParasiticHeatFractiontoTank(0.8)
  water_heater.setIndirectWaterHeatingRecoveryTime(1.5) # 1.5hrs
  if water_heater_fuel == 'Electricity'
    water_heater.setHeaterFuelType('Electricity')
    water_heater.setHeaterThermalEfficiency(1.0)
    water_heater.setOffCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOnCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOffCycleParasiticFuelType('Electricity')
    water_heater.setOnCycleParasiticFuelType('Electricity')
    water_heater.setOffCycleLossCoefficienttoAmbientTemperature(1.053)
    water_heater.setOnCycleLossCoefficienttoAmbientTemperature(1.053)
  elsif water_heater_fuel == 'Natural Gas' || water_heater_fuel == 'NaturalGas'
    water_heater.setHeaterFuelType('Gas')
    water_heater.setHeaterThermalEfficiency(0.8)
    water_heater.setOffCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOnCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOffCycleParasiticFuelType('Gas')
    water_heater.setOnCycleParasiticFuelType('Gas')
    water_heater.setOffCycleLossCoefficienttoAmbientTemperature(6.0)
    water_heater.setOnCycleLossCoefficienttoAmbientTemperature(6.0)
  end

  booster_service_water_loop.addSupplyBranchForComponent(water_heater)

  # Service water heating loop bypass pipes
  water_heater_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  booster_service_water_loop.addSupplyBranchForComponent(water_heater_bypass_pipe)
  coil_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  booster_service_water_loop.addDemandBranchForComponent(coil_bypass_pipe)
  supply_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_outlet_pipe.addToNode(booster_service_water_loop.supplyOutletNode)
  demand_inlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_inlet_pipe.addToNode(booster_service_water_loop.demandInletNode)
  demand_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_outlet_pipe.addToNode(booster_service_water_loop.demandOutletNode)

  # Heat exchanger to supply the booster water heater
  # with normal hot water from the main service water loop.
  hx = OpenStudio::Model::HeatExchangerFluidToFluid.new(model)
  hx.setName('HX for Booster Water Heating')
  hx.setHeatExchangeModelType('Ideal')
  hx.setControlType('UncontrolledOn')
  hx.setHeatTransferMeteringEndUseType('LoopToLoop')

  # Add the HX to the supply side of the booster loop
  hx.addToNode(booster_service_water_loop.supplyInletNode)

  # Add the HX to the demand side of
  # the main service water loop.
  main_service_water_loop.addDemandBranchForComponent(hx)

  # Add a plant component temperature source to the demand outlet
  # of the HX to represent the fact that the water used by the booster
  # would in reality be at the mains temperature.
  mains_src = OpenStudio::Model::PlantComponentTemperatureSource.new(model)
  mains_src.setName('Mains Water Makeup for SWH Booster')
  mains_src.addToNode(hx.demandOutletModelObject.get.to_Node.get)

  # Mains water temperature sensor
  mains_water_temp_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Site Mains Water Temperature')
  mains_water_temp_sen.setName('Mains_Water_Temp_Sen')
  mains_water_temp_sen.setKeyName('Environment')

  # Schedule to actuate
  water_mains_temp_sch = OpenStudio::Model::ScheduleConstant.new(model)
  water_mains_temp_sch.setName('Mains Water Temperature')
  water_mains_temp_sch.setValue(OpenStudio.convert(50, 'F', 'C').get)

  # Actuator for mains water temperature schedule
  mains_water_temp_sch_act = OpenStudio::Model::EnergyManagementSystemActuator.new(water_mains_temp_sch, 'Schedule:Constant', 'Schedule Value')
  mains_water_temp_sch_act.setName('Mains_Water_Temp_Act')

  # Program
  mains_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
  mains_prg.setName('Mains_Water_Prg')
  mains_prg_body = "SET #{mains_water_temp_sch_act.handle} = #{mains_water_temp_sen.handle}"
  mains_prg.setBody(mains_prg_body)

  # Program Calling Manager
  mains_mgr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
  mains_mgr.setName('Mains_Water_Prg_Mgr')
  mains_mgr.setCallingPoint('BeginTimestepBeforePredictor')
  mains_mgr.addProgram(mains_prg)

  # Make the plant component use the actuated schedule
  mains_src.setTemperatureSpecificationType('Scheduled')
  mains_src.setSourceTemperatureSchedule(water_mains_temp_sch)

  return booster_service_water_loop
end
model_add_swh_end_uses(model, use_name, swh_loop, peak_flowrate, flowrate_schedule, water_use_temperature, space_name, frac_sensible: 0.2, frac_latent: 0.05) click to toggle source

Creates water fixtures and attaches them to the supplied service water loop.

@param model [OpenStudio::Model::Model] OpenStudio model object @param use_name [String] The name that will be assigned to the newly created fixture. @param swh_loop [OpenStudio::Model::PlantLoop] the main service water loop to add water fixtures to. @param peak_flowrate [Double] in m^3/s @param flowrate_schedule [String] name of the flow rate schedule @param water_use_temperature [Double] mixed water use temperature, in C @param space_name [String] the name of the space to add the water fixture to, or nil, in which case it will not be assigned to any particular space. @return [OpenStudio::Model::WaterUseEquipment] the resulting water fixture.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ServiceWaterHeating.rb, line 898
def model_add_swh_end_uses(model,
                           use_name,
                           swh_loop,
                           peak_flowrate,
                           flowrate_schedule,
                           water_use_temperature,
                           space_name,
                           frac_sensible: 0.2,
                           frac_latent: 0.05)
  # Water use connection
  swh_connection = OpenStudio::Model::WaterUseConnections.new(model)

  # Water fixture definition
  water_fixture_def = OpenStudio::Model::WaterUseEquipmentDefinition.new(model)
  rated_flow_rate_m3_per_s = peak_flowrate
  rated_flow_rate_gal_per_min = OpenStudio.convert(rated_flow_rate_m3_per_s, 'm^3/s', 'gal/min').get

  water_use_sensible_frac_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                frac_sensible,
                                                                                                name: "Fraction Sensible - #{frac_sensible}",
                                                                                                schedule_type_limit: 'Fractional')
  water_use_latent_frac_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                              frac_latent,
                                                                                              name: "Fraction Latent - #{frac_latent}",
                                                                                              schedule_type_limit: 'Fractional')
  water_fixture_def.setSensibleFractionSchedule(water_use_sensible_frac_sch)
  water_fixture_def.setLatentFractionSchedule(water_use_latent_frac_sch)
  water_fixture_def.setPeakFlowRate(rated_flow_rate_m3_per_s)
  water_fixture_def.setName("#{use_name} Service Water Use Def #{rated_flow_rate_gal_per_min.round(2)}gpm")
  # Target mixed water temperature
  mixed_water_temp_f = OpenStudio.convert(water_use_temperature, 'C', 'F').get
  mixed_water_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                         OpenStudio.convert(mixed_water_temp_f, 'F', 'C').get,
                                                                                         name: "Mixed Water At Faucet Temp - #{mixed_water_temp_f.round}F",
                                                                                         schedule_type_limit: 'Temperature')
  water_fixture_def.setTargetTemperatureSchedule(mixed_water_temp_sch)

  # Water use equipment
  water_fixture = OpenStudio::Model::WaterUseEquipment.new(water_fixture_def)
  schedule = model_add_schedule(model, flowrate_schedule)
  water_fixture.setFlowRateFractionSchedule(schedule)

  if space_name.nil?
    water_fixture.setName("#{use_name} Service Water Use #{rated_flow_rate_gal_per_min.round(2)}gpm at #{mixed_water_temp_f.round}F")
    swh_connection.setName("#{use_name} WUC #{rated_flow_rate_gal_per_min.round(2)}gpm at #{mixed_water_temp_f.round}F")
  else
    water_fixture.setName("#{space_name} Service Water Use #{rated_flow_rate_gal_per_min.round(2)}gpm at #{mixed_water_temp_f.round}F")
    swh_connection.setName("#{space_name} WUC #{rated_flow_rate_gal_per_min.round(2)}gpm at #{mixed_water_temp_f.round}F")
  end

  unless space_name.nil?
    space = model.getSpaceByName(space_name)
    space = space.get
    water_fixture.setSpace(space)
  end

  swh_connection.addWaterUseEquipment(water_fixture)

  # Connect the water use connection to the SWH loop
  unless swh_loop.nil?
    swh_loop.addDemandBranchForComponent(swh_connection)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding water fixture to #{swh_loop.name}.")
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Added #{water_fixture.name}.")

  return water_fixture
end
model_add_swh_end_uses_by_space(model, swh_loop, space, space_multiplier = 1.0, is_flow_per_area = true) click to toggle source

This method will add a swh water fixture to the model for the space. It will return a water fixture object, or NIL if there is no water load at all.

Adds a WaterUseEquipment object representing the SWH loads of the supplied Space. Attaches this WaterUseEquipment to the supplied PlantLoop via a new WaterUseConnections object.

@param model [OpenStudio::Model::Model] OpenStudio model object @param swh_loop [OpenStudio::Model::PlantLoop] the SWH loop to connect the WaterUseEquipment to @param space [OpenStudio::Model::Space] the Space to add a WaterUseEquipment for @param space_multiplier [Double] the multiplier to use if the supplied Space actually represents

more area than is shown in the model.

@param is_flow_per_area [Boolean] if true, use the value in the ‘service_water_heating_peak_flow_per_area’

field of the space_types JSON.  If false, use the value in the 'service_water_heating_peak_flow_rate' field.

@return [OpenStudio::Model::WaterUseEquipment] the WaterUseEquipment for the

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ServiceWaterHeating.rb, line 981
def model_add_swh_end_uses_by_space(model,
                                    swh_loop,
                                    space,
                                    space_multiplier = 1.0,
                                    is_flow_per_area = true)
  # SpaceType
  if space.spaceType.empty?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "Space #{space.name} does not have a Space Type assigned, cannot add SWH end uses.")
    return nil
  end
  space_type = space.spaceType.get

  # Standards Building Type
  if space_type.standardsBuildingType.empty?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "Space #{space.name}'s Space Type does not have a Standards Building Type assigned, cannot add SWH end uses.")
    return nil
  end
  stds_bldg_type = space_type.standardsBuildingType.get
  building_type = model_get_lookup_name(stds_bldg_type)

  # Standards Space Type
  if space_type.standardsSpaceType.empty?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "Space #{space.name}'s Space Type does not have a Standards Space Type assigned, cannot add SWH end uses.")
    return nil
  end
  stds_spc_type = space_type.standardsSpaceType.get

  # find the specific space_type properties from standard.json
  search_criteria = {
    'template' => template,
    'building_type' => building_type,
    'space_type' => stds_spc_type
  }
  data = standards_lookup_table_first(table_name: 'space_types', search_criteria: search_criteria)
  if data.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Could not find space type for: #{search_criteria}.")
    return nil
  end
  space_area = OpenStudio.convert(space.floorArea, 'm^2', 'ft^2').get # ft2

  # If there is no service hot water load.. Don't bother adding anything.
  if data['service_water_heating_peak_flow_per_area'].to_f == 0.0 &&
     data['service_water_heating_peak_flow_rate'].to_f == 0.0
    return nil
  end

  # Water use connection
  swh_connection = OpenStudio::Model::WaterUseConnections.new(model)

  # Water fixture definition
  water_fixture_def = OpenStudio::Model::WaterUseEquipmentDefinition.new(model)
  rated_flow_rate_per_area = data['service_water_heating_peak_flow_per_area'].to_f # gal/h.ft2
  rated_flow_rate_gal_per_hour = if is_flow_per_area
                                   rated_flow_rate_per_area * space_area * space_multiplier # gal/h
                                 else
                                   data['service_water_heating_peak_flow_rate'].to_f
                                 end
  rated_flow_rate_gal_per_min = rated_flow_rate_gal_per_hour / 60 # gal/h to gal/min
  rated_flow_rate_m3_per_s = OpenStudio.convert(rated_flow_rate_gal_per_min, 'gal/min', 'm^3/s').get
  water_use_sensible_frac_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                0.2,
                                                                                                name: 'Fraction Sensible - 0.2',
                                                                                                schedule_type_limit: 'Fractional')
  water_use_latent_frac_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                              0.05,
                                                                                              name: 'Fraction Latent - 0.05',
                                                                                              schedule_type_limit: 'Fractional')
  water_fixture_def.setSensibleFractionSchedule(water_use_sensible_frac_sch)
  water_fixture_def.setLatentFractionSchedule(water_use_latent_frac_sch)
  water_fixture_def.setPeakFlowRate(rated_flow_rate_m3_per_s)
  water_fixture_def.setName("#{space.name.get} Service Water Use Def #{rated_flow_rate_gal_per_min.round(2)}gpm")
  # Target mixed water temperature
  mixed_water_temp_f = data['service_water_heating_target_temperature']
  mixed_water_temp_c = OpenStudio.convert(mixed_water_temp_f, 'F', 'C').get
  mixed_water_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                         mixed_water_temp_c,
                                                                                         name: "Mixed Water At Faucet Temp - #{mixed_water_temp_f.round}F",
                                                                                         schedule_type_limit: 'Temperature')
  water_fixture_def.setTargetTemperatureSchedule(mixed_water_temp_sch)

  # Water use equipment
  water_fixture = OpenStudio::Model::WaterUseEquipment.new(water_fixture_def)
  schedule = model_add_schedule(model, data['service_water_heating_schedule'])
  water_fixture.setFlowRateFractionSchedule(schedule)
  water_fixture.setName("#{space.name.get} Service Water Use #{rated_flow_rate_gal_per_min.round(2)}gpm")
  swh_connection.addWaterUseEquipment(water_fixture)
  # Assign water fixture to a space
  water_fixture.setSpace(space) if model_attach_water_fixtures_to_spaces?(model)

  # Connect the water use connection to the SWH loop
  swh_loop.addDemandBranchForComponent(swh_connection)
  return water_fixture
end
model_add_swh_loop(model, system_name, water_heater_thermal_zone, service_water_temperature, service_water_pump_head, service_water_pump_motor_efficiency, water_heater_capacity, water_heater_volume, water_heater_fuel, parasitic_fuel_consumption_rate, add_pipe_losses = false, floor_area_served = 465, number_of_stories = 1, pipe_insulation_thickness = 0.0127, number_water_heaters = 1) click to toggle source

Creates a service water heating loop.

@param model [OpenStudio::Model::Model] OpenStudio model object @param system_name [String] the name of the system, or nil in which case it will be defaulted @param water_heater_thermal_zone [OpenStudio::Model::ThermalZone]

zones to place water heater in.  If nil, will be assumed in 70F air for heat loss.

@param service_water_temperature [Double] service water temperature, in C @param service_water_pump_head [Double] service water pump head, in Pa @param service_water_pump_motor_efficiency [Double] service water pump motor efficiency, as decimal. @param water_heater_capacity [Double] water heater heating capacity, in W @param water_heater_volume [Double] water heater volume, in m^3 @param water_heater_fuel [String] water heater fuel. Valid choices are NaturalGas, Electricity @param parasitic_fuel_consumption_rate [Double] the parasitic fuel consumption rate of the water heater, in W @param add_pipe_losses [Boolean] if true, add piping and associated heat losses to system. If false, add no pipe heat losses @param floor_area_served [Double] area served by the SWH loop, in m^2. Used for pipe loss piping length estimation @param number_of_stories [Integer] number of stories served by the SWH loop. Used for pipe loss piping length estimation @param pipe_insulation_thickness [Double] thickness of the fiberglass batt pipe insulation, in m. Use 0 for uninsulated pipes @param number_water_heaters [Double] the number of water heaters represented by the capacity and volume inputs. Used to modify efficiencies for water heaters based on individual component size while avoiding having to model lots of individual water heaters (for runtime sake). @return [OpenStudio::Model::PlantLoop] the resulting service water loop.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ServiceWaterHeating.rb, line 26
def model_add_swh_loop(model,
                       system_name,
                       water_heater_thermal_zone,
                       service_water_temperature,
                       service_water_pump_head,
                       service_water_pump_motor_efficiency,
                       water_heater_capacity,
                       water_heater_volume,
                       water_heater_fuel,
                       parasitic_fuel_consumption_rate,
                       add_pipe_losses = false,
                       floor_area_served = 465,
                       number_of_stories = 1,
                       pipe_insulation_thickness = 0.0127, # 1/2in
                       number_water_heaters = 1)
  # Service water heating loop
  service_water_loop = OpenStudio::Model::PlantLoop.new(model)
  service_water_loop.setMinimumLoopTemperature(10.0)
  service_water_loop.setMaximumLoopTemperature(60.0)

  if system_name.nil?
    service_water_loop.setName('Service Water Loop')
  else
    service_water_loop.setName(system_name)
  end

  # Temperature schedule type limits
  temp_sch_type_limits = OpenstudioStandards::Schedules.create_schedule_type_limits(model,
                                                                                    name: 'Temperature Schedule Type Limits',
                                                                                    lower_limit_value: 0.0,
                                                                                    upper_limit_value: 100.0,
                                                                                    numeric_type: 'Continuous',
                                                                                    unit_type: 'Temperature')

  # Service water heating loop controls
  swh_temp_c = service_water_temperature
  swh_temp_f = OpenStudio.convert(swh_temp_c, 'C', 'F').get
  swh_delta_t_r = 9.0 # 9F delta-T
  swh_delta_t_k = OpenStudio.convert(swh_delta_t_r, 'R', 'K').get
  swh_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                 swh_temp_c,
                                                                                 name: "Service Water Loop Temp - #{swh_temp_f.round}F",
                                                                                 schedule_type_limit: 'Temperature')
  swh_temp_sch.setScheduleTypeLimits(temp_sch_type_limits)
  swh_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, swh_temp_sch)
  swh_stpt_manager.setName('Service hot water setpoint manager')
  swh_stpt_manager.addToNode(service_water_loop.supplyOutletNode)
  sizing_plant = service_water_loop.sizingPlant
  sizing_plant.setLoopType('Heating')
  sizing_plant.setDesignLoopExitTemperature(swh_temp_c)
  sizing_plant.setLoopDesignTemperatureDifference(swh_delta_t_k)

  # Determine if circulating or non-circulating based on supplied head pressure
  swh_pump_head_press_pa = service_water_pump_head
  circulating = true
  if swh_pump_head_press_pa.nil? || swh_pump_head_press_pa <= 1
    # As if there is no circulation pump
    swh_pump_head_press_pa = 0.001
    service_water_pump_motor_efficiency = 1
    circulating = false
  end

  # Service water heating pump
  if circulating
    swh_pump = OpenStudio::Model::PumpConstantSpeed.new(model)
    swh_pump.setName("#{service_water_loop.name} Circulator Pump")
    swh_pump.setPumpControlType('Intermittent')
  else
    swh_pump = OpenStudio::Model::PumpVariableSpeed.new(model)
    swh_pump.setName("#{service_water_loop.name} Water Mains Pressure Driven")
    swh_pump.setPumpControlType('Continuous')
  end
  swh_pump.setRatedPumpHead(swh_pump_head_press_pa.to_f)
  swh_pump.setMotorEfficiency(service_water_pump_motor_efficiency)
  swh_pump.addToNode(service_water_loop.supplyInletNode)

  water_heater = model_add_water_heater(model,
                                        water_heater_capacity,
                                        water_heater_volume,
                                        water_heater_fuel,
                                        service_water_temperature,
                                        parasitic_fuel_consumption_rate,
                                        swh_temp_sch,
                                        false,
                                        0.0,
                                        nil,
                                        water_heater_thermal_zone,
                                        number_water_heaters)

  service_water_loop.addSupplyBranchForComponent(water_heater)

  # Pipe losses
  if add_pipe_losses
    model_add_piping_losses_to_swh_system(model,
                                          service_water_loop,
                                          circulating,
                                          pipe_insulation_thickness: pipe_insulation_thickness,
                                          floor_area_served: floor_area_served,
                                          number_of_stories: number_of_stories)
  end

  # Service water heating loop bypass pipes
  water_heater_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  service_water_loop.addSupplyBranchForComponent(water_heater_bypass_pipe)
  coil_bypass_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  service_water_loop.addDemandBranchForComponent(coil_bypass_pipe)
  supply_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  supply_outlet_pipe.addToNode(service_water_loop.supplyOutletNode)
  demand_outlet_pipe = OpenStudio::Model::PipeAdiabatic.new(model)
  demand_outlet_pipe.addToNode(service_water_loop.demandOutletNode)

  if circulating
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Added circulating SWH loop called #{service_water_loop.name}")
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Added non-circulating SWH loop called #{service_water_loop.name}")
  end

  return service_water_loop
end
model_add_transformer(model, wired_lighting_frac: nil, transformer_size: nil, transformer_efficiency: nil, excluded_interiorequip_key: '', excluded_interiorequip_meter: nil) click to toggle source

Add transformers for some prototypes

@param model [OpenStudio::Model::Model] OpenStudio model object @param wired_lighting_frac [Double] the wired lighting fraction, 0-1 @param transformer_size [Double] the transformer size in VA @param transformer_efficiency [Double] the transformer efficiency, 0-1 @param excluded_interiorequip_key [String] key to exclude @param excluded_interiorequip_meter [String] meter to exclude @return [OpenStudio::Model::ElectricLoadCenterTransformer] the transformer object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.transformers.rb, line 11
  def model_add_transformer(model,
                            wired_lighting_frac: nil,
                            transformer_size: nil,
                            transformer_efficiency: nil,
                            excluded_interiorequip_key: '',
                            excluded_interiorequip_meter: nil)
    # throw an error if transformer properties are missing
    if wired_lighting_frac.nil? || transformer_size.nil? || transformer_efficiency.nil?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.transformers', "Either 'wired_lighting_frac', 'transformer_size', or 'transformer_efficiency' is unspecified.  Cannot add transformer.")
      return false
    end

    # @todo default values are for testing only
    # ems sensor for interior lighting
    facility_int_ltg = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'InteriorLights:Electricity')
    facility_int_ltg.setName('Facility_Int_LTG')

    # declaire ems variable for transformer wired lighting portion
    wired_ltg_var = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'Wired_LTG')

    # ems program for transformer load
    transformer_load_prog = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
    transformer_load_prog.setName('Transformer_Load_Prog')
    transformer_load_prog_body = <<-EMS
    SET Wired_LTG = Facility_Int_LTG*#{wired_lighting_frac}
    EMS
    transformer_load_prog.setBody(transformer_load_prog_body)

    # ems program calling manager
    transformer_load_prog_manager = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
    transformer_load_prog_manager.setName('Transformer_Load_Prog_Manager')
    transformer_load_prog_manager.setCallingPoint('AfterPredictorAfterHVACManagers')
    transformer_load_prog_manager.addProgram(transformer_load_prog)

    # ems output variable
    wired_ltg_emsout = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, wired_ltg_var)
    wired_ltg_emsout.setName('Wired_LTG')
    wired_ltg_emsout.setTypeOfDataInVariable('Summed')
    wired_ltg_emsout.setUpdateFrequency('ZoneTimeStep')
    wired_ltg_emsout.setUnits('J')

    # meter for ems output
    wired_ltg_meter = OpenStudio::Model::MeterCustom.new(model)
    wired_ltg_meter.setName('Wired_LTG_Electricity')
    wired_ltg_meter.setFuelType('Electricity')
    wired_ltg_meter.addKeyVarGroup('', 'Wired_LTG')

    # meter for wired int equip
    unless excluded_interiorequip_meter.nil?
      wired_int_equip_meter = OpenStudio::Model::MeterCustomDecrement.new(model, 'InteriorEquipment:Electricity')
      wired_int_equip_meter.setName('Wired_Int_EQUIP')
      wired_int_equip_meter.setFuelType('Electricity')
      wired_int_equip_meter.addKeyVarGroup(excluded_interiorequip_key, excluded_interiorequip_meter)
    end

    # add transformer
    transformer = OpenStudio::Model::ElectricLoadCenterTransformer.new(model)
    transformer.setName('Transformer_1')
    transformer.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
    transformer.setTransformerUsage('PowerInFromGrid')
    transformer.setRatedCapacity(transformer_size)
    transformer.setPhase('3')
    transformer.setConductorMaterial('Aluminum')
    transformer.setFullLoadTemperatureRise(150)
    transformer.setFractionofEddyCurrentLosses(0.1)
    transformer.setPerformanceInputMethod('NominalEfficiency')
    transformer.setNameplateEfficiency(transformer_efficiency)
    transformer.setPerUnitLoadforNameplateEfficiency(0.35)
    transformer.setReferenceTemperatureforNameplateEfficiency(75)
    transformer.setConsiderTransformerLossforUtilityCost(true)
    transformer.addMeter('Wired_LTG_Electricity')
    if excluded_interiorequip_meter.nil?
      transformer.addMeter('InteriorEquipment:Electricity') # by default, add this as the second meter
    else
      transformer.addMeter('Wired_Int_EQUIP')
    end

    return transformer
  end
model_add_typical_exterior_lights(model, exterior_lighting_zone_number, onsite_parking_fraction = 1.0, add_base_site_allowance = false, use_model_for_entries_and_canopies = false) click to toggle source

Add exterior lighting to the model

@param model [OpenStudio::Model::Model] OpenStudio model object @param exterior_lighting_zone_number [Integer] exterior lighting zone number, 0-4 @param onsite_parking_fraction [Double] onsite parking fraction, 0-1 @param add_base_site_allowance [Boolean] whether to include the base site allowance @param use_model_for_entries_and_canopies [Boolean] use building geometry for number of entries and canopy size @return [Hash] a hash of OpenStudio::Model::ExteriorLights objects @todo would be nice to add argument for some building types (SmallHotel, MidriseApartment, PrimarySchool, SecondarySchool, RetailStripmall) if it has interior or exterior circulation.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.exterior_lights.rb, line 11
def model_add_typical_exterior_lights(model, exterior_lighting_zone_number, onsite_parking_fraction = 1.0, add_base_site_allowance = false, use_model_for_entries_and_canopies = false)
  exterior_lights = {}
  installed_power = 0.0

  # populate search hash
  search_criteria = {
    'template' => template,
    'exterior_lighting_zone_number' => exterior_lighting_zone_number
  }

  # load exterior_lighting_properties
  exterior_lighting_properties = standards_lookup_table_first(table_name: 'exterior_lighting', search_criteria: search_criteria)

  # make sure lighting properties were found
  if exterior_lighting_properties.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.exterior_lights', "Exterior lighting properties not found for #{template}, ext lighting zone #{exterior_lighting_zone_number}, none will be added to model.")
    return exterior_lights
  end

  # get building types and ratio (needed to get correct schedules, parking area, entries, canopies, and drive throughs)
  space_type_hash = model_create_space_type_hash(model)

  # get model specific values to map to exterior_lighting_properties
  area_length_count_hash = model_create_exterior_lighting_area_length_count_hash(model, space_type_hash, use_model_for_entries_and_canopies)

  # using midnight to 6am setback or shutdown
  start_setback_shutoff = { hr: 24, min: 0 }
  end_setback_shutoff = { hr: 6, min: 0 }
  shuttoff = false
  setback = false
  if exterior_lighting_properties['building_facade_and_landscape_automatic_shut_off'] == 1
    ext_lights_sch_facade_and_landscape = OpenStudio::Model::ScheduleRuleset.new(model)
    default_day = ext_lights_sch_facade_and_landscape.defaultDaySchedule
    default_day.addValue(OpenStudio::Time.new(0, end_setback_shutoff[:hr], end_setback_shutoff[:min], 0), 0.0)
    default_day.addValue(OpenStudio::Time.new(0, start_setback_shutoff[:hr], start_setback_shutoff[:min], 0), 1.0)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Facade and Landscape exterior lights shut off from #{start_setback_shutoff} to #{end_setback_shutoff}")
  else
    ext_lights_sch_facade_and_landscape = model.alwaysOnDiscreteSchedule
  end
  if !exterior_lighting_properties['occupancy_setback_reduction'].nil? && (exterior_lighting_properties['occupancy_setback_reduction'] > 0.0)
    ext_lights_sch_other = OpenStudio::Model::ScheduleRuleset.new(model)
    setback_value = 1.0 - exterior_lighting_properties['occupancy_setback_reduction']
    default_day = ext_lights_sch_other.defaultDaySchedule
    default_day.addValue(OpenStudio::Time.new(0, end_setback_shutoff[:hr], end_setback_shutoff[:min], 0), setback_value)
    default_day.addValue(OpenStudio::Time.new(0, start_setback_shutoff[:hr], start_setback_shutoff[:min], 0), 1.0)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Non Facade and Landscape lights reduce by #{exterior_lighting_properties['occupancy_setback_reduction'] * 100} % from #{start_setback_shutoff} to #{end_setback_shutoff}")
  else
    ext_lights_sch_other = model.alwaysOnDiscreteSchedule
  end

  # add exterior lights for parking area
  if !area_length_count_hash[:parking_area_and_drives_area].nil? && area_length_count_hash[:parking_area_and_drives_area] > 0

    # lighting values
    multiplier = area_length_count_hash[:parking_area_and_drives_area] * onsite_parking_fraction
    power = exterior_lighting_properties['parking_areas_and_drives']
    name_prefix = 'Parking Areas and Drives'

    # create ext light def
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Added #{power.round(2)} W/ft^2 of lighting for #{multiplier} ft^2 of parking area.")
    ext_lights_def = OpenStudio::Model::ExteriorLightsDefinition.new(model)
    ext_lights_def.setName("#{name_prefix} Def (W/ft^2)")
    ext_lights_def.setDesignLevel(power)

    # create ext light inst
    # creating exterior lights object
    ext_lights = OpenStudio::Model::ExteriorLights.new(ext_lights_def, ext_lights_sch_other)
    ext_lights.setMultiplier(multiplier)
    ext_lights.setName(name_prefix)
    ext_lights.setControlOption(exterior_lighting_properties['control_option'])
    ext_lights.setEndUseSubcategory(name_prefix)
    exterior_lights[name_prefix] = ext_lights

    # update installed power
    installed_power += power * multiplier
  end

  # add exterior lights for facades
  if !area_length_count_hash[:building_facades].nil? && area_length_count_hash[:building_facades] > 0

    # lighting values
    multiplier = area_length_count_hash[:building_facades]
    power = exterior_lighting_properties['building_facades']
    name_prefix = 'Building Facades'

    # create ext light def
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Added #{power.round(2)} W/ft^2 of lighting for #{multiplier} ft^2 of building facade area.")
    ext_lights_def = OpenStudio::Model::ExteriorLightsDefinition.new(model)
    ext_lights_def.setName("#{name_prefix} Def (W/ft^2)")
    ext_lights_def.setDesignLevel(power)

    # create ext light inst
    # creating exterior lights object
    ext_lights = OpenStudio::Model::ExteriorLights.new(ext_lights_def, ext_lights_sch_facade_and_landscape)
    ext_lights.setMultiplier(multiplier)
    ext_lights.setName(name_prefix)
    ext_lights.setControlOption(exterior_lighting_properties['control_option'])
    ext_lights.setEndUseSubcategory(name_prefix)
    exterior_lights[name_prefix] = ext_lights

    # update installed power
    installed_power += power * multiplier
  end

  # add exterior lights for main entries
  if !area_length_count_hash[:main_entries].nil? && area_length_count_hash[:main_entries] > 0

    # lighting values
    multiplier = area_length_count_hash[:main_entries]
    power = exterior_lighting_properties['main_entries']
    name_prefix = 'Main Entries'

    # create ext light def
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Added #{power.round(2)} W/ft of lighting for #{multiplier} ft of main entry length.")
    ext_lights_def = OpenStudio::Model::ExteriorLightsDefinition.new(model)
    ext_lights_def.setName("#{name_prefix} Def (W/ft)")
    ext_lights_def.setDesignLevel(power)

    # create ext light inst
    # creating exterior lights object
    ext_lights = OpenStudio::Model::ExteriorLights.new(ext_lights_def, ext_lights_sch_other)
    ext_lights.setMultiplier(multiplier)
    ext_lights.setName(name_prefix)
    ext_lights.setControlOption(exterior_lighting_properties['control_option'])
    ext_lights.setEndUseSubcategory(name_prefix)
    exterior_lights[name_prefix] = ext_lights

    # update installed power
    installed_power += power * multiplier
  end

  # add exterior lights for other doors
  if !area_length_count_hash[:other_doors].nil? && area_length_count_hash[:other_doors] > 0

    # lighting values
    multiplier = area_length_count_hash[:other_doors]
    power = exterior_lighting_properties['other_doors']
    name_prefix = 'Other Doors'

    # create ext light def
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Added #{power.round(2)} W/ft of lighting for #{multiplier} ft of other doors.")
    ext_lights_def = OpenStudio::Model::ExteriorLightsDefinition.new(model)
    ext_lights_def.setName("#{name_prefix} Def (W/ft)")
    ext_lights_def.setDesignLevel(power)

    # create ext light inst
    # creating exterior lights object
    ext_lights = OpenStudio::Model::ExteriorLights.new(ext_lights_def, ext_lights_sch_other)
    ext_lights.setMultiplier(multiplier)
    ext_lights.setName(name_prefix)
    ext_lights.setControlOption(exterior_lighting_properties['control_option'])
    ext_lights.setEndUseSubcategory(name_prefix)
    exterior_lights[name_prefix] = ext_lights

    # update installed power
    installed_power += power * multiplier
  end

  # add exterior lights for entry canopies
  if !area_length_count_hash[:canopy_entry_area].nil? && area_length_count_hash[:canopy_entry_area] > 0

    # lighting values
    multiplier = area_length_count_hash[:canopy_entry_area]
    power = exterior_lighting_properties['entry_canopies']
    name_prefix = 'Entry Canopies'

    # create ext light def
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Added #{power} W/ft^2 of lighting for #{multiplier} ft^2 of building entry canopies.")
    ext_lights_def = OpenStudio::Model::ExteriorLightsDefinition.new(model)
    ext_lights_def.setName("#{name_prefix} Def (W/ft^2)")
    ext_lights_def.setDesignLevel(power)

    # create ext light inst
    # creating exterior lights object
    ext_lights = OpenStudio::Model::ExteriorLights.new(ext_lights_def, ext_lights_sch_other)
    ext_lights.setMultiplier(multiplier)
    ext_lights.setName(name_prefix)
    ext_lights.setControlOption(exterior_lighting_properties['control_option'])
    ext_lights.setEndUseSubcategory(name_prefix)
    exterior_lights[name_prefix] = ext_lights

    # update installed power
    installed_power += power * multiplier
  end

  # add exterior lights for emergency canopies
  if !area_length_count_hash[:canopy_emergency_area].nil? && area_length_count_hash[:canopy_emergency_area] > 0

    # lighting values
    multiplier = area_length_count_hash[:canopy_emergency_area]
    power = exterior_lighting_properties['loading_areas_for_emergency_vehicles']
    name_prefix = 'Emergency Canopies'

    # create ext light def
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Added #{power} W/ft^2 of lighting for #{multiplier} ft^2 of building emergency canopies.")
    ext_lights_def = OpenStudio::Model::ExteriorLightsDefinition.new(model)
    ext_lights_def.setName("#{name_prefix} Def (W/ft^2)")
    ext_lights_def.setDesignLevel(power)

    # create ext light inst
    # creating exterior lights object
    ext_lights = OpenStudio::Model::ExteriorLights.new(ext_lights_def, ext_lights_sch_other)
    ext_lights.setMultiplier(multiplier)
    ext_lights.setName(name_prefix)
    ext_lights.setControlOption(exterior_lighting_properties['control_option'])
    ext_lights.setEndUseSubcategory(name_prefix)
    exterior_lights[name_prefix] = ext_lights

    # update installed power
    installed_power += power * multiplier
  end

  # add exterior lights for drive through windows
  if !area_length_count_hash[:drive_through_windows].nil? && area_length_count_hash[:drive_through_windows] > 0

    # lighting values
    multiplier = area_length_count_hash[:drive_through_windows]
    power = exterior_lighting_properties['drive_through_windows_and_doors']
    name_prefix = 'Drive Through Windows'

    # create ext light def
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Added #{power} W/drive through window of lighting for #{multiplier} drive through windows.")
    ext_lights_def = OpenStudio::Model::ExteriorLightsDefinition.new(model)
    ext_lights_def.setName("#{name_prefix} Def (W/ft^2)")
    ext_lights_def.setDesignLevel(power)

    # create ext light inst
    # creating exterior lights object
    ext_lights = OpenStudio::Model::ExteriorLights.new(ext_lights_def, ext_lights_sch_other)
    ext_lights.setMultiplier(multiplier)
    ext_lights.setName(name_prefix)
    ext_lights.setControlOption(exterior_lighting_properties['control_option'])
    ext_lights.setEndUseSubcategory(name_prefix)
    exterior_lights[name_prefix] = ext_lights

    # update installed power
    installed_power += power * multiplier
  end

  # @todo - add_base_site_lighting_allowance (non landscaping tradable lighting)
  # add exterior lights for drive through windows
  if add_base_site_allowance

    # lighting values
    if !exterior_lighting_properties['base_site_allowance_power'].nil?
      power = exterior_lighting_properties['base_site_allowance_power']
    elsif !exterior_lighting_properties['base_site_allowance_fraction'].nil?
      power = exterior_lighting_properties['base_site_allowance_fraction'] * installed_power # shold be of allowed vs. installed, but hard to calculate
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', 'Cannot determine target base site allowance power, will set to 0 W.')
      power = 0.0
    end
    name_prefix = 'Base Site Allowance'

    # create ext light def
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Added #{power} W of non landscape tradable exterior lighting. Will follow occupancy setback reduction.")
    ext_lights_def = OpenStudio::Model::ExteriorLightsDefinition.new(model)
    ext_lights_def.setName("#{name_prefix} Def (W)")
    ext_lights_def.setDesignLevel(power)

    # create ext light inst
    # creating exterior lights object
    ext_lights = OpenStudio::Model::ExteriorLights.new(ext_lights_def, ext_lights_sch_other)
    ext_lights.setName(name_prefix)
    ext_lights.setControlOption(exterior_lighting_properties['control_option'])
    ext_lights.setEndUseSubcategory(name_prefix)
    exterior_lights[name_prefix] = ext_lights

    # don't need to update installed power for this
  end

  return exterior_lights
end
model_add_typical_refrigeration(model, building_type) click to toggle source

Add a typical refrigeration system to the model, including cases, walkins, compressors, and condensors. For small stores, each case and walkin is served by one compressor and one condenser. For larger stores, all medium temp cases and walkins are served by one multi-compressor rack, and all low temp cases and walkins another.

@param model [OpenStudio::Model::Model] OpenStudio model object @param building_type [String] building type @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.refrigeration.rb, line 525
def model_add_typical_refrigeration(model, building_type)
  # Define system category and scaling factor
  floor_area_ft2 = OpenStudio.convert(model.getBuilding.floorArea, 'm^2', 'ft^2').get
  case building_type
  when 'SuperMarket', 'Gro'
    if floor_area_ft2 < 35_000 # this is in m2
      size_category = '<35k ft2'
      floor_area_scaling_factor = floor_area_ft2 / 35_000
    elsif floor_area_ft2 < 50_000
      size_category = '35k - 50k ft2'
      floor_area_scaling_factor = floor_area_ft2 / 50_000
    else
      size_category = '>50k ft2'
      floor_area_scaling_factor = floor_area_ft2 / 50_000
    end
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Refrigeration size category is #{size_category}, with a scaling factor of #{floor_area_scaling_factor} because the floor area is #{floor_area_ft2.round} ft2.  All cases and walkins added later will subsequently be scaled by this factor.")
  else
    size_category = 'Kitchen'
    floor_area_scaling_factor = 1 # Do not scale kitchen systems
  end

  # Add a low and medium temperature system
  ['Medium Temperature', 'Low Temperature'].each do |system_type|
    # Find refrigeration system lineup
    search_criteria = {
      'template' => template,
      'building_type' => building_type,
      'size_category' => size_category,
      'system_type' => system_type
    }
    props_lineup = model_find_object(standards_data['refrigeration_system_lineup'], search_criteria)
    if props_lineup.nil?
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "No refrigeration system lineup found for #{search_criteria}, no system will be added.")
      next
    end
    number_of_display_cases = props_lineup['number_of_display_cases']
    number_of_walkins = props_lineup['number_of_walkins']
    compressor_name = props_lineup['compressor_name']
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Refrigeration system lineup found for #{search_criteria}: #{number_of_display_cases} display cases and #{number_of_walkins} walkins, with compressor '#{compressor_name}'.")

    # Find the thermal zones most suited for holding the display cases
    thermal_zone_case = nil
    if number_of_display_cases > 0
      thermal_zone_case = model_typical_display_case_zone(model)
      if thermal_zone_case.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Attempted to add #{number_of_display_cases} display cases to the model, but could find no thermal zone to put them into.")
        return false
      end
    end

    # Add display cases
    display_cases = []
    (1..number_of_display_cases).each_with_index do |display_case_number, def_start_hr_iterator|
      case_type = props_lineup["case_type_#{display_case_number}"]

      # Add the basic case
      ref_case = model_add_refrigeration_case(model, thermal_zone_case, case_type, size_category)
      return false if ref_case.nil?

      # Scale based on floor area
      ref_case.setCaseLength(ref_case.caseLength * floor_area_scaling_factor)

      # Find defrost and dripdown properties
      search_criteria = {
        'template' => template,
        'case_type' => case_type,
        'size_category' => size_category
      }
      props_case = model_find_object(standards_data['refrigerated_cases'], search_criteria)
      if props_case.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Could not find refrigerated case properties for: #{search_criteria}.")
        next
      end
      numb_defrosts_per_day = props_case['defrost_per_day']
      minutes_defrost = props_case['minutes_defrost']
      minutes_dripdown = props_case['minutes_dripdown']
      minutes_defrost = 59 if minutes_defrost > 59 # Just to make sure to remain in the same hour
      minutes_dripdown = 59 if minutes_dripdown > 59 # Just to make sure to remain in the same hour

      # Add defrost and dripdown schedules
      defrost_sch = OpenStudio::Model::ScheduleRuleset.new(model)
      defrost_sch.setName('Refrigeration Defrost Schedule')
      defrost_sch.defaultDaySchedule.setName("Refrigeration Defrost Schedule Default - #{case_type}")
      dripdown_sch = OpenStudio::Model::ScheduleRuleset.new(model)
      dripdown_sch.setName('Refrigeration Dripdown Schedule')
      dripdown_sch.defaultDaySchedule.setName("Refrigeration Dripdown Schedule Default - #{case_type}")

      # Stagger the defrosts for cases by 1 hr
      interval_defrost = (24 / numb_defrosts_per_day).floor # Hour interval between each defrost period
      if (def_start_hr_iterator + interval_defrost * numb_defrosts_per_day) > 23
        first_def_start_hr = 0 # Start over again at midnight when time reaches 23hrs
      else
        first_def_start_hr = def_start_hr_iterator
      end

      # Add the specified number of defrost periods to the daily schedule
      (1..numb_defrosts_per_day).each do |defrost_of_day|
        def_start_hr = first_def_start_hr + ((1 - defrost_of_day) * interval_defrost)
        defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, def_start_hr, 0, 0), 0)
        defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, def_start_hr, minutes_defrost.to_int, 0), 0)
        dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, def_start_hr, 0, 0), 0) # Dripdown is synced with defrost
        dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, def_start_hr, minutes_dripdown.to_int, 0), 0)
      end
      defrost_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0)
      dripdown_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0)

      # Assign the defrost and dripdown schedules
      ref_case.setCaseDefrostSchedule(defrost_sch)
      ref_case.setCaseDefrostDripDownSchedule(dripdown_sch)

      display_cases << ref_case
    end

    # Find the thermal zones most suited for holding the walkins
    thermal_zone_walkin = nil
    if number_of_walkins > 0
      thermal_zone_walkin = model_typical_walkin_zone(model)
      if thermal_zone_walkin.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Attempted to add #{number_of_walkins} walkins to the model, but could find no thermal zone to put them into.")
        return false
      end
    end

    # Add walkin cases
    walkins = []
    (1..number_of_walkins).each_with_index do |walkin_number, def_start_hr_iterator|
      walkin_type = props_lineup["walkin_type_#{walkin_number}"]

      # Add the basic walkin
      ref_walkin = model_add_refrigeration_walkin(model, thermal_zone_walkin, size_category, walkin_type)
      return false if ref_walkin.nil?

      # Scale based on floor area
      ref_walkin.setRatedTotalLightingPower(ref_walkin.ratedTotalLightingPower * floor_area_scaling_factor)
      ref_walkin.setRatedCoolingCoilFanPower(ref_walkin.ratedCoolingCoilFanPower * floor_area_scaling_factor)
      ref_walkin.setDefrostPower(ref_walkin.defrostPower.get * floor_area_scaling_factor)
      ref_walkin.setRatedCoilCoolingCapacity(ref_walkin.ratedCoilCoolingCapacity * floor_area_scaling_factor)
      ref_walkin.setZoneBoundaryTotalInsulatedSurfaceAreaFacingZone(ref_walkin.zoneBoundaryTotalInsulatedSurfaceAreaFacingZone.get * floor_area_scaling_factor)
      ref_walkin.setInsulatedFloorSurfaceArea(ref_walkin.insulatedFloorSurfaceArea * floor_area_scaling_factor)

      # Check that walkin physically fits inside the thermal zone.
      # If not, remove the walkin and warn.
      walkin_floor_area_ft2 = OpenStudio.convert(ref_walkin.insulatedFloorSurfaceArea, 'm^2', 'ft^2').get.round
      walkin_zone_floor_area_ft2 = OpenStudio.convert(thermal_zone_walkin.floorArea, 'm^2', 'ft^2').get.round
      if walkin_floor_area_ft2 > walkin_zone_floor_area_ft2
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "Walkin #{ref_walkin.name} has an area of #{walkin_floor_area_ft2} ft^2, which is larger than the #{walkin_zone_floor_area_ft2} ft^2 zone.  Walkin will be kept in the model, but considered re-sizing the zone '#{thermal_zone_walkin.name}'.")
      end

      # Find defrost and dripdown properties
      search_criteria = {
        'template' => template,
        'walkin_type' => walkin_type,
        'size_category' => size_category
      }
      props_walkin = model_find_object(standards_data['refrigeration_walkins'], search_criteria)
      if props_walkin.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Could not find walkin properties for: #{search_criteria}.")
        next
      end
      numb_defrosts_per_day = props_walkin['defrost_per_day']
      minutes_defrost = props_walkin['minutes_defrost']
      minutes_dripdown = props_walkin['minutes_dripdown']
      minutes_defrost = 59 if minutes_defrost > 59 # Just to make sure to remain in the same hour
      minutes_dripdown = 59 if minutes_dripdown > 59 # Just to make sure to remain in the same hour

      # Add defrost and dripdown schedules
      defrost_sch_walkin = OpenStudio::Model::ScheduleRuleset.new(model)
      defrost_sch_walkin.setName('Refrigeration Defrost Schedule')
      defrost_sch_walkin.defaultDaySchedule.setName("Refrigeration Defrost Schedule Default - #{walkin_type}")
      dripdown_sch_walkin = OpenStudio::Model::ScheduleRuleset.new(model)
      dripdown_sch_walkin.setName('Refrigeration Dripdown Schedule')
      dripdown_sch_walkin.defaultDaySchedule.setName("Refrigeration Dripdown Schedule Default - #{walkin_type}")

      # Stagger the defrosts for cases by 1 hr
      interval_defrost = (24 / numb_defrosts_per_day).floor # Hour interval between each defrost period
      if (def_start_hr_iterator + interval_defrost * numb_defrosts_per_day) > 23
        first_def_start_hr = 0 # Start over again at midnight when time reaches 23hrs
      else
        first_def_start_hr = def_start_hr_iterator
      end

      # Add the specified number of defrost periods to the daily schedule
      (1..numb_defrosts_per_day).each do |defrost_of_day|
        def_start_hr = first_def_start_hr + ((1 - defrost_of_day) * interval_defrost)
        defrost_sch_walkin.defaultDaySchedule.addValue(OpenStudio::Time.new(0, def_start_hr, 0, 0), 0)
        defrost_sch_walkin.defaultDaySchedule.addValue(OpenStudio::Time.new(0, def_start_hr, minutes_defrost.to_int, 0), 0)
        dripdown_sch_walkin.defaultDaySchedule.addValue(OpenStudio::Time.new(0, def_start_hr, 0, 0), 0) # Dripdown is synced with defrost
        dripdown_sch_walkin.defaultDaySchedule.addValue(OpenStudio::Time.new(0, def_start_hr, minutes_dripdown.to_int, 0), 0)
      end
      defrost_sch_walkin.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0)
      dripdown_sch_walkin.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0)

      # Assign the defrost and dripdown schedules
      ref_walkin.setDefrostSchedule(defrost_sch_walkin)
      ref_walkin.setDefrostDripDownSchedule(dripdown_sch_walkin)

      walkins << ref_walkin
    end

    # Divide cases and walkins into one or more refrigeration systems depending on store type
    # For small stores and kitchens one system with one compressor and one condenser per case is employed.
    # For larger stores, multiple cases and walkins are served by a rack with multiple compressors.
    ref_system_lineups = []
    case system_type
    when '<35k ft2', 'Kitchen'
      # Put each case on its own system
      display_cases.each do |ref_case|
        ref_system_lineups << { 'ref_cases' => [ref_case], 'walkins' => [] }
      end
      # Put each walkin on its own system
      walkins.each do |walkin|
        ref_system_lineups << { 'ref_cases' => [], 'walkins' => [walkin] }
      end
    else
      # Put all cases and walkins on one system
      ref_system_lineups << { 'ref_cases' => display_cases, 'walkins' => walkins }
    end

    # Find refrigeration system properties
    search_criteria = {
      'template' => template,
      'building_type' => building_type,
      'size_category' => size_category,
      'system_type' => system_type
    }
    props_ref_system = model_find_object(standards_data['refrigeration_system'], search_criteria)
    if props_ref_system.nil?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Could not find refrigeration system properties for: #{search_criteria}.")
      next
    end

    # Add refrigeration systems
    ref_system_lineups.each do |ref_system_lineup|
      # Skip if no cases or walkins are attached to the system
      next if ref_system_lineup['ref_cases'].empty? && ref_system_lineup['walkins'].empty?

      # Add refrigeration system
      ref_system = OpenStudio::Model::RefrigerationSystem.new(model)
      ref_system.setName(system_type)
      ref_system.setRefrigerationSystemWorkingFluidType(props_ref_system['refrigerant'])
      ref_system.setSuctionTemperatureControlType(props_ref_system['refrigerant'])

      # Sum the capacity required by all cases and walkins
      # and attach the cases and walkins to the system.
      rated_case_capacity_w = 0
      ref_system_lineup['ref_cases'].each do |ref_case|
        rated_case_capacity_w += ref_case.ratedTotalCoolingCapacityperUnitLength * ref_case.caseLength
        ref_system.addCase(ref_case)
      end
      ref_system_lineup['walkins'].each do |walkin|
        rated_case_capacity_w += walkin.ratedCoilCoolingCapacity
        ref_system.addWalkin(walkin)
      end

      # Find the compressor properties
      search_criteria = {
        'template' => template,
        'compressor_name' => compressor_name
      }
      props_compressor = model_find_object(standards_data['refrigeration_compressors'], search_criteria)
      if props_compressor.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Could not find refrigeration compressor properties for: #{search_criteria}.")
        next
      end

      # Calculate the number of compressors required to meet the
      # combined rated capacity of all the cases
      # and add them to the system
      rated_compressor_capacity_btu_per_hr = props_compressor['rated_capacity']
      number_of_compressors = (rated_case_capacity_w / OpenStudio.convert(rated_compressor_capacity_btu_per_hr, 'Btu/h', 'W').get).ceil
      (1..number_of_compressors).each do |compressor_number|
        compressor = model_add_refrigeration_compressor(model, compressor_name)
        ref_system.addCompressor(compressor)
      end
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Added #{number_of_compressors} compressors, each with a capacity of #{rated_compressor_capacity_btu_per_hr.round} Btu/hr to serve #{OpenStudio.convert(rated_case_capacity_w, 'W', 'Btu/hr').get.round} Btu/hr of case and walkin load.")

      # Find the condenser properties
      search_criteria = {
        'template' => template,
        'building_type' => building_type,
        'system_type' => system_type,
        'size_category' => size_category
      }
      props_condenser = model_find_object(standards_data['refrigeration_condenser'], search_criteria)
      if props_condenser.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Could not find refrigeration condenser properties for: #{search_criteria}.")
        next
      end

      # Heat rejection as a function of temperature
      heat_rejection_curve = OpenStudio::Model::CurveLinear.new(model)
      heat_rejection_curve.setName('Condenser Heat Rejection Function of Temperature')
      heat_rejection_curve.setCoefficient1Constant(0)
      heat_rejection_curve.setCoefficient2x(props_condenser['heatrejectioncurve_c1'])
      heat_rejection_curve.setMinimumValueofx(-50)
      heat_rejection_curve.setMaximumValueofx(50)

      # Add condenser
      condenser = OpenStudio::Model::RefrigerationCondenserAirCooled.new(model)
      condenser.setRatedEffectiveTotalHeatRejectionRateCurve(heat_rejection_curve)
      condenser.setRatedSubcoolingTemperatureDifference(OpenStudio.convert(props_condenser['subcool_t'], 'F', 'C').get)
      condenser.setMinimumFanAirFlowRatio(props_condenser['min_airflow'])
      condenser.setRatedFanPower(props_condenser['fan_power_per_q_rejected'].to_f * rated_case_capacity_w)
      condenser.setCondenserFanSpeedControlType(props_condenser['fan_speed_control'])
      ref_system.setRefrigerationCondenser(condenser)

      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Added #{system_type} refrigeration system")
    end
  end

  return true
end
model_add_typical_swh(model, water_heater_fuel: nil, pipe_insul_in: nil, circulating: nil) click to toggle source

add typical swh demand and supply to model

@param model [OpenStudio::Model::Model] OpenStudio model object @param water_heater_fuel [String] water heater fuel. Valid choices are NaturalGas, Electricity, and HeatPump.

If not supplied, a smart default will be determined based on building type.

@param pipe_insul_in [Double] thickness of the pipe insulation, in inches. @param circulating [String] whether the (circulating, noncirculating, nil) nil is smart @return [Array<OpenStudio::Model::PlantLoop>] hot water loops @todo - add in losses from tank and pipe insulation, etc.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.swh.rb, line 236
def model_add_typical_swh(model,
                          water_heater_fuel: nil,
                          pipe_insul_in: nil,
                          circulating: nil)
  # array of hot water loops
  swh_systems = []

  # hash of general water use equipment awaiting loop
  water_use_equipment_hash = {} # key is standards building type value is array of water use equipment

  # create space type hash (need num_units for MidriseApartment and RetailStripmall)
  space_type_hash = model_create_space_type_hash(model, trust_effective_num_spaces = false)

  # loop through space types adding demand side of swh
  model.getSpaceTypes.sort.each do |space_type|
    next unless space_type.standardsBuildingType.is_initialized
    next unless space_type_hash.key?(space_type) # this is used for space types without any floor area

    stds_bldg_type = space_type.standardsBuildingType.get

    # lookup space_type_properties
    space_type_properties = space_type_get_standards_data(space_type)
    peak_flow_rate_gal_per_hr_per_ft2 = space_type_properties['service_water_heating_peak_flow_per_area'].to_f
    peak_flow_rate_gal_per_hr = space_type_properties['service_water_heating_peak_flow_rate'].to_f
    swh_system_type = space_type_properties['service_water_heating_system_type']
    flow_rate_fraction_schedule = model_add_schedule(model, space_type_properties['service_water_heating_schedule'])
    service_water_temperature_f = space_type_properties['service_water_heating_target_temperature'].to_f
    service_water_temperature_c = OpenStudio.convert(service_water_temperature_f, 'F', 'C').get
    booster_water_temperature_f = space_type_properties['booster_water_heating_target_temperature'].to_f
    booster_water_temperature_c = OpenStudio.convert(booster_water_temperature_f, 'F', 'C').get
    booster_water_heater_fraction = space_type_properties['booster_water_heater_fraction'].to_f
    service_water_fraction_sensible = space_type_properties['service_water_heating_fraction_sensible']
    service_water_fraction_latent = space_type_properties['service_water_heating_fraction_latent']
    floor_area_m2 = space_type_hash[space_type][:floor_area]
    floor_area_ft2 = OpenStudio.convert(floor_area_m2, 'm^2', 'ft^2').get

    # next if no service water heating demand
    next unless peak_flow_rate_gal_per_hr_per_ft2 > 0.0 || peak_flow_rate_gal_per_hr > 0.0

    # If there is no SWH schedule specified, assume
    # that there should be no SWH consumption for this space type.
    unless flow_rate_fraction_schedule
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "No service water heating schedule was specified for #{space_type.name}, an always off schedule will be used and no water will be used.")
      flow_rate_fraction_schedule = model.alwaysOffDiscreteSchedule
    end

    # Determine flow rate
    case swh_system_type
    when 'One Per Unit'
      water_heater_fuel = 'Electricity' if water_heater_fuel.nil?
      num_units = space_type_hash[space_type][:num_units].round # First try number of units
      num_units = space_type_hash[space_type][:effective_num_spaces].round if num_units.zero? # Fall back on number of spaces
      peak_flow_rate_gal_per_hr = num_units * peak_flow_rate_gal_per_hr
      peak_flow_rate_m3_per_s = OpenStudio.convert(peak_flow_rate_gal_per_hr, 'gal/hr', 'm^3/s').get
      use_name = "#{space_type.name} #{num_units} units"
    else
      # @todo add building type or sice specific logic or just assume Gas?
      #   (SmallOffice and Warehouse are only non unit prototypes with Electric heating)
      water_heater_fuel = 'NaturalGas' if water_heater_fuel.nil?
      num_units = 1
      peak_flow_rate_gal_per_hr = peak_flow_rate_gal_per_hr_per_ft2 * floor_area_ft2
      peak_flow_rate_m3_per_s = OpenStudio.convert(peak_flow_rate_gal_per_hr, 'gal/hr', 'm^3/s').get
      use_name = space_type.name.to_s
    end

    # Split flow rate between main and booster uses if specified
    booster_water_use_equip = nil
    if booster_water_heater_fraction > 0.0
      booster_peak_flow_rate_m3_per_s = peak_flow_rate_m3_per_s * booster_water_heater_fraction
      peak_flow_rate_m3_per_s -= booster_peak_flow_rate_m3_per_s

      # Add booster water heater equipment and connections
      booster_water_use_equip = model_add_swh_end_uses(model,
                                                       "Booster #{use_name}",
                                                       loop = nil,
                                                       booster_peak_flow_rate_m3_per_s,
                                                       flow_rate_fraction_schedule.name.get,
                                                       booster_water_temperature_c,
                                                       space_name = nil,
                                                       frac_sensible: service_water_fraction_sensible,
                                                       frac_latent: service_water_fraction_latent)
    end

    # Add water use equipment and connections
    water_use_equip = model_add_swh_end_uses(model,
                                             use_name,
                                             swh_loop = nil,
                                             peak_flow_rate_m3_per_s,
                                             flow_rate_fraction_schedule.name.get,
                                             service_water_temperature_c,
                                             space_name = nil,
                                             frac_sensible: service_water_fraction_sensible,
                                             frac_latent: service_water_fraction_latent)

    # Water heater sizing
    case swh_system_type
    when 'One Per Unit'
      water_heater_capacity_w = num_units * OpenStudio.convert(20.0, 'kBtu/hr', 'W').get
      water_heater_volume_m3 = num_units * OpenStudio.convert(50.0, 'gal', 'm^3').get
      num_water_heaters = num_units
    else
      water_use_equips = [water_use_equip]
      water_use_equips << booster_water_use_equip unless booster_water_use_equip.nil? # Include booster in sizing since flows will be preheated by main water heater
      water_heater_sizing = model_find_water_heater_capacity_volume_and_parasitic(model, water_use_equips)
      water_heater_capacity_w = water_heater_sizing[:water_heater_capacity]
      water_heater_volume_m3 = water_heater_sizing[:water_heater_volume]
      num_water_heaters = 1
    end

    # Add either a dedicated SWH loop or save to add to shared SWH loop
    case swh_system_type
    when 'Shared'

      # Store water use equip by building type to add to shared building hot water loop
      if water_use_equipment_hash.key?(stds_bldg_type)
        water_use_equipment_hash[stds_bldg_type] << water_use_equip
      else
        water_use_equipment_hash[stds_bldg_type] = [water_use_equip]
      end

    when 'One Per Unit', 'Dedicated'
      pipe_insul_in = 0.0 if pipe_insul_in.nil?

      # Add service water loop with water heater
      swh_loop = model_add_swh_loop(model,
                                    system_name = "#{space_type.name} Service Water Loop",
                                    water_heater_thermal_zone = nil,
                                    service_water_temperature_c,
                                    service_water_pump_head = 0.01,
                                    service_water_pump_motor_efficiency = 1.0,
                                    water_heater_capacity_w,
                                    water_heater_volume_m3,
                                    water_heater_fuel,
                                    parasitic_fuel_consumption_rate_w = 0,
                                    add_pipe_losses = true,
                                    floor_area_served = OpenStudio.convert(950, 'ft^2', 'm^2').get,
                                    number_of_stories = 1,
                                    pipe_insulation_thickness = OpenStudio.convert(pipe_insul_in, 'in', 'm').get,
                                    num_water_heaters)
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "In model_add_typical, num_water_heaters = #{num_water_heaters}")
      # Add loop to list
      swh_systems << swh_loop

      # Attach water use equipment to the loop
      swh_connection = water_use_equip.waterUseConnections
      swh_loop.addDemandBranchForComponent(swh_connection.get) if swh_connection.is_initialized

      # If a booster fraction is specified, some percentage of the water
      # is assumed to be heated beyond the normal temperature by a separate
      # booster water heater.  This booster water heater is fed by the
      # main water heater, so the booster is responsible for a smaller delta-T.
      if booster_water_heater_fraction > 0
        # find_water_heater_capacity_volume_and_parasitic
        booster_water_heater_sizing = model_find_water_heater_capacity_volume_and_parasitic(model,
                                                                                            [booster_water_use_equip],
                                                                                            htg_eff: 1.0,
                                                                                            inlet_temp_f: service_water_temperature_f,
                                                                                            target_temp_f: booster_water_temperature_f)

        # Add service water booster loop with water heater
        # Note that booster water heaters are always assumed to be electric resistance
        swh_booster_loop = model_add_swh_booster(model,
                                                 swh_loop,
                                                 booster_water_heater_sizing[:water_heater_capacity],
                                                 water_heater_volume_m3 = OpenStudio.convert(6, 'gal', 'm^3').get,
                                                 water_heater_fuel = 'Electricity',
                                                 booster_water_temperature_c,
                                                 parasitic_fuel_consumption_rate_w = 0.0,
                                                 booster_water_heater_thermal_zone = nil)

        # Rename the service water booster loop
        swh_booster_loop.setName("#{space_type.name} Service Water Booster Loop")

        # Attach booster water use equipment to the booster loop
        booster_swh_connection = booster_water_use_equip.waterUseConnections
        swh_booster_loop.addDemandBranchForComponent(booster_swh_connection.get) if booster_swh_connection.is_initialized
      end

    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "'#{swh_system_type}' is not a valid Service Water Heating System Type, cannot add SWH to #{space_type.name}.  Valid choices are One Per Unit, Dedicated, and Shared.")
    end
  end

  # get building floor area and effective number of stories
  bldg_floor_area_m2 = model.getBuilding.floorArea
  bldg_effective_num_stories_hash = model_effective_num_stories(model)
  bldg_effective_num_stories = bldg_effective_num_stories_hash[:below_grade] + bldg_effective_num_stories_hash[:above_grade]

  # add non-dedicated system(s) here. Separate systems for water use equipment from different building types
  water_use_equipment_hash.sort.each do |stds_bldg_type, water_use_equipment_array|
    # @todo find the water use equipment with the highest temperature
    water_heater_temp_f = 140.0
    water_heater_temp_c = OpenStudio.convert(water_heater_temp_f, 'F', 'C').get

    # find pump values
    # Table A.2 in PrototypeModelEnhancements_2014_0.pdf shows 10ft on everything except SecondarySchool which has 11.4ft
    # @todo Remove hard-coded building-type-based lookups for circulating vs. non-circulating SWH systems
    circulating_bldg_types = [
      # DOE building types
      'Office',
      'PrimarySchool',
      'Outpatient',
      'Hospital',
      'SmallHotel',
      'LargeHotel',
      'FullServiceRestaurant',
      'HighriseApartment',
      # DEER building types
      'Asm', # 'Assembly'
      'ECC', # 'Education - Community College'
      'EPr', # 'Education - Primary School'
      'ERC', # 'Education - Relocatable Classroom'
      'ESe', # 'Education - Secondary School'
      'EUn', # 'Education - University'
      'Gro', # 'Grocery'
      'Hsp', # 'Health/Medical - Hospital'
      'Htl', # 'Lodging - Hotel'
      'MBT', # 'Manufacturing Biotech'
      'MFm', # 'Residential Multi-family'
      'Mtl', # 'Lodging - Motel'
      'Nrs', # 'Health/Medical - Nursing Home'
      'OfL', # 'Office - Large'
      # 'RFF', # 'Restaurant - Fast-Food'
      'RSD' # 'Restaurant - Sit-Down'
    ]
    if circulating_bldg_types.include?(stds_bldg_type)
      service_water_pump_head_pa = OpenStudio.convert(10.0, 'ftH_{2}O', 'Pa').get
      service_water_pump_motor_efficiency = 0.3
      circulating = true if circulating.nil?
      pipe_insul_in = 0.5 if pipe_insul_in.nil?
    else # values for non-circulating pump
      service_water_pump_head_pa = 0.01
      service_water_pump_motor_efficiency = 1.0
      circulating = false if circulating.nil?
      pipe_insul_in = 0.0 if pipe_insul_in.nil?
    end

    bldg_type_floor_area_m2 = 0.0
    space_type_hash.sort.each do |space_type, space_type_props|
      bldg_type_floor_area_m2 += space_type_props[:floor_area] if space_type_props[:stds_bldg_type] == stds_bldg_type
    end

    # Calculate the number of stories covered by this building type
    num_stories = bldg_effective_num_stories * (bldg_type_floor_area_m2 / bldg_floor_area_m2)

    # Water heater sizing
    water_heater_sizing = model_find_water_heater_capacity_volume_and_parasitic(model, water_use_equipment_array)
    water_heater_capacity_w = water_heater_sizing[:water_heater_capacity]
    water_heater_volume_m3 = water_heater_sizing[:water_heater_volume]

    # Add a shared service water heating loop with water heater
    shared_swh_loop = model_add_swh_loop(model,
                                         "#{stds_bldg_type} Shared Service Water Loop",
                                         water_heater_thermal_zone = nil,
                                         water_heater_temp_c,
                                         service_water_pump_head_pa,
                                         service_water_pump_motor_efficiency,
                                         water_heater_capacity_w,
                                         water_heater_volume_m3,
                                         water_heater_fuel,
                                         parasitic_fuel_consumption_rate_w = 0,
                                         add_pipe_losses = true,
                                         floor_area_served = bldg_type_floor_area_m2,
                                         number_of_stories = num_stories,
                                         pipe_insulation_thickness = OpenStudio.convert(pipe_insul_in, 'in', 'm').get)

    # Attach all water use equipment to the shared loop
    water_use_equipment_array.sort.each do |water_use_equip|
      swh_connection = water_use_equip.waterUseConnections
      shared_swh_loop.addDemandBranchForComponent(swh_connection.get) if swh_connection.is_initialized
    end

    # add to list of systems
    swh_systems << shared_swh_loop

    OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Adding shared water heating loop for #{stds_bldg_type}.")
  end

  return swh_systems
end
model_add_unitheater(model, thermal_zones, hvac_op_sch: nil, fan_control_type: 'ConstantVolume', fan_pressure_rise: 0.2, heating_type: nil, hot_water_loop: nil, rated_inlet_water_temperature: 180.0, rated_outlet_water_temperature: 160.0, rated_inlet_air_temperature: 60.0, rated_outlet_air_temperature: 104.0) click to toggle source

Creates a unit heater for each zone and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param fan_control_type [String] valid choices are OnOff, ConstantVolume, VariableVolume @param fan_pressure_rise [Double] fan pressure rise, inH2O @param heating_type [String] valid choices are NaturalGas, Gas, Electricity, Electric, DistrictHeating, DistrictHeatingWater, DistrictHeatingSteam @param hot_water_loop [OpenStudio::Model::PlantLoop] hot water loop to connect to the heating coil @param rated_inlet_water_temperature [Double] rated inlet water temperature in degrees Fahrenheit, default is 180F @param rated_outlet_water_temperature [Double] rated outlet water temperature in degrees Fahrenheit, default is 160F @param rated_inlet_air_temperature [Double] rated inlet air temperature in degrees Fahrenheit, default is 60F @param rated_outlet_air_temperature [Double] rated outlet air temperature in degrees Fahrenheit, default is 100F @return [Array<OpenStudio::Model::ZoneHVACUnitHeater>] an array of the resulting unit heaters.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 4232
def model_add_unitheater(model,
                         thermal_zones,
                         hvac_op_sch: nil,
                         fan_control_type: 'ConstantVolume',
                         fan_pressure_rise: 0.2,
                         heating_type: nil,
                         hot_water_loop: nil,
                         rated_inlet_water_temperature: 180.0,
                         rated_outlet_water_temperature: 160.0,
                         rated_inlet_air_temperature: 60.0,
                         rated_outlet_air_temperature: 104.0)

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # set defaults if nil
  fan_control_type = 'ConstantVolume' if fan_control_type.nil?
  fan_pressure_rise = 0.2 if fan_pressure_rise.nil?

  # default design temperatures used across all air loops
  dsgn_temps = standard_design_sizing_temperatures

  # adjusted zone design heating temperature for unit heater
  dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 122.0
  dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get

  # make a unit heater for each zone
  unit_heaters = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding unit heater for #{zone.name}.")

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])

    # add fan
    fan = create_fan_by_name(model,
                             'Unit_Heater_Fan',
                             fan_name: "#{zone.name} UnitHeater Fan",
                             pressure_rise: fan_pressure_rise)
    fan.setAvailabilitySchedule(hvac_op_sch)

    # add heating coil
    if heating_type == 'NaturalGas' || heating_type == 'Gas'
      htg_coil = create_coil_heating_gas(model,
                                         name: "#{zone.name} UnitHeater Gas Htg Coil",
                                         schedule: hvac_op_sch)
    elsif heating_type == 'Electricity' || heating_type == 'Electric'
      htg_coil = create_coil_heating_electric(model,
                                              name: "#{zone.name} UnitHeater Electric Htg Coil",
                                              schedule: hvac_op_sch)
    elsif heating_type.include?('DistrictHeating') && !hot_water_loop.nil?
      # control temperature for hot water loop
      if rated_inlet_water_temperature.nil?
        rated_inlet_water_temperature_c = OpenStudio.convert(180.0, 'F', 'C').get
      else
        rated_inlet_water_temperature_c = OpenStudio.convert(rated_inlet_water_temperature, 'F', 'C').get
      end
      if rated_outlet_water_temperature.nil?
        rated_outlet_water_temperature_c = OpenStudio.convert(160.0, 'F', 'C').get
      else
        rated_outlet_water_temperature_c = OpenStudio.convert(rated_outlet_water_temperature, 'F', 'C').get
      end
      if rated_inlet_air_temperature.nil?
        rated_inlet_air_temperature_c = OpenStudio.convert(60.0, 'F', 'C').get
      else
        rated_inlet_air_temperature_c = OpenStudio.convert(rated_inlet_air_temperature, 'F', 'C').get
      end
      if rated_outlet_air_temperature.nil?
        rated_outlet_air_temperature_c = OpenStudio.convert(104.0, 'F', 'C').get
      else
        rated_outlet_air_temperature_c = OpenStudio.convert(rated_outlet_air_temperature, 'F', 'C').get
      end
      htg_coil = create_coil_heating_water(model,
                                           hot_water_loop,
                                           name: "#{zone.name} UnitHeater Water Htg Coil",
                                           rated_inlet_water_temperature: rated_inlet_water_temperature_c,
                                           rated_outlet_water_temperature: rated_outlet_water_temperature_c,
                                           rated_inlet_air_temperature: rated_inlet_air_temperature_c,
                                           rated_outlet_air_temperature: rated_outlet_air_temperature_c)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'No heating type was found when adding unit heater; no unit heater will be created.')
      return false
    end

    # create unit heater
    unit_heater = OpenStudio::Model::ZoneHVACUnitHeater.new(model,
                                                            hvac_op_sch,
                                                            fan,
                                                            htg_coil)
    unit_heater.setName("#{zone.name} Unit Heater")
    unit_heater.setFanControlType(fan_control_type)
    unit_heater.addToThermalZone(zone)
    unit_heaters << unit_heater
  end

  return unit_heaters
end
model_add_vav_pfp_boxes(model, thermal_zones, system_name: nil, chilled_water_loop: nil, hvac_op_sch: nil, oa_damper_sch: nil, fan_efficiency: 0.62, fan_motor_efficiency: 0.9, fan_pressure_rise: 4.0) click to toggle source

Creates a VAV system with parallel fan powered boxes and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param system_name [String] the name of the system, or nil in which case it will be defaulted @param chilled_water_loop [OpenStudio::Model::PlantLoop] chilled water loop to connect to the cooling coil @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [String] name of the oa damper schedule or nil in which case will be defaulted to always open @param fan_efficiency [Double] fan total efficiency, including motor and impeller @param fan_motor_efficiency [Double] fan motor efficiency @param fan_pressure_rise [Double] fan pressure rise, inH2O @return [OpenStudio::Model::AirLoopHVAC] the resulting VAV air loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 2063
def model_add_vav_pfp_boxes(model,
                            thermal_zones,
                            system_name: nil,
                            chilled_water_loop: nil,
                            hvac_op_sch: nil,
                            oa_damper_sch: nil,
                            fan_efficiency: 0.62,
                            fan_motor_efficiency: 0.9,
                            fan_pressure_rise: 4.0)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding VAV with PFP Boxes and Reheat system for #{thermal_zones.size} zones.")

  # create air handler
  air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
  if system_name.nil?
    air_loop.setName("#{thermal_zones.size} Zone VAV with PFP Boxes and Reheat")
  else
    air_loop.setName(system_name)
  end

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  if oa_damper_sch.nil?
    oa_damper_sch = model.alwaysOnDiscreteSchedule
  else
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # default design temperatures and settings used across all air loops
  dsgn_temps = standard_design_sizing_temperatures
  sizing_system = adjust_sizing_system(air_loop, dsgn_temps)

  # air handler controls
  sa_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                dsgn_temps['clg_dsgn_sup_air_temp_c'],
                                                                                name: "Supply Air Temp - #{dsgn_temps['clg_dsgn_sup_air_temp_f']}F",
                                                                                schedule_type_limit: 'Temperature')
  sa_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, sa_temp_sch)
  sa_stpt_manager.setName("#{air_loop.name} Supply Air Setpoint Manager")
  sa_stpt_manager.addToNode(air_loop.supplyOutletNode)

  # create fan
  # @type [OpenStudio::Model::FanVariableVolume] fan
  fan = create_fan_by_name(model,
                           'VAV_System_Fan',
                           fan_name: "#{air_loop.name} Fan",
                           fan_efficiency: fan_efficiency,
                           pressure_rise: fan_pressure_rise,
                           motor_efficiency: fan_motor_efficiency,
                           end_use_subcategory: 'VAV System Fans')
  fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  fan.addToNode(air_loop.supplyInletNode)

  # create heating coil
  htg_coil = create_coil_heating_electric(model,
                                          air_loop_node: air_loop.supplyInletNode,
                                          name: "#{air_loop.name} Htg Coil")

  # set the setpointmanager for the central/preheat coil if required
  model_set_central_preheat_coil_spm(model, thermal_zones, htg_coil)

  # create cooling coil
  create_coil_cooling_water(model,
                            chilled_water_loop,
                            air_loop_node: air_loop.supplyInletNode,
                            name: "#{air_loop.name} Clg Coil")

  # create outdoor air intake system
  oa_intake_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
  oa_intake_controller.setName("#{air_loop.name} OA Controller")
  oa_intake_controller.setMinimumLimitType('FixedMinimum')
  oa_intake_controller.autosizeMinimumOutdoorAirFlowRate
  oa_intake_controller.resetEconomizerMinimumLimitDryBulbTemperature
  # oa_intake_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
  controller_mv = oa_intake_controller.controllerMechanicalVentilation
  controller_mv.setName("#{air_loop.name} Vent Controller")
  controller_mv.setSystemOutdoorAirMethod('ZoneSum')
  oa_intake = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_intake_controller)
  oa_intake.setName("#{air_loop.name} OA System")
  oa_intake.addToNode(air_loop.supplyInletNode)

  # set air loop availability controls and night cycle manager, after oa system added
  air_loop.setAvailabilitySchedule(hvac_op_sch)
  air_loop.setNightCycleControlType('CycleOnAny')

  # attach the VAV system to each zone
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding VAV with PFP Boxes and Reheat system terminal for #{zone.name}.")

    # create reheat coil
    rht_coil = create_coil_heating_electric(model,
                                            name: "#{zone.name} Electric Reheat Coil")

    # create terminal fan
    # @type [OpenStudio::Model::FanConstantVolume] pfp_fan
    pfp_fan = create_fan_by_name(model,
                                 'PFP_Fan',
                                 fan_name: "#{zone.name} PFP Term Fan")
    pfp_fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

    # create parallel fan powered terminal
    pfp_terminal = OpenStudio::Model::AirTerminalSingleDuctParallelPIUReheat.new(model,
                                                                                 model.alwaysOnDiscreteSchedule,
                                                                                 pfp_fan,
                                                                                 rht_coil)
    pfp_terminal.setName("#{zone.name} PFP Term")
    air_loop.multiAddBranchForZone(zone, pfp_terminal.to_HVACComponent.get)

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setCoolingDesignAirFlowMethod('DesignDay')
    sizing_zone.setHeatingDesignAirFlowMethod('DesignDay')
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
  end

  return air_loop
end
model_add_vav_reheat(model, thermal_zones, system_name: nil, return_plenum: nil, heating_type: nil, reheat_type: nil, hot_water_loop: nil, chilled_water_loop: nil, hvac_op_sch: nil, oa_damper_sch: nil, fan_efficiency: 0.62, fan_motor_efficiency: 0.9, fan_pressure_rise: 4.0, min_sys_airflow_ratio: 0.3, vav_sizing_option: 'Coincident', econo_ctrl_mthd: nil) click to toggle source

Creates a VAV system and adds it to the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to connect to this system @param system_name [String] the name of the system, or nil in which case it will be defaulted @param return_plenum [OpenStudio::Model::ThermalZone] the zone to attach as the supply plenum, or nil, in which case no return plenum will be used @param heating_type [String] main heating coil fuel type

valid choices are NaturalGas, Gas, Electricity, HeatPump, DistrictHeating, DistrictHeatingWater, DistrictHeatingSteam, or nil (defaults to NaturalGas)

@param reheat_type [String] valid options are NaturalGas, Gas, Electricity, Water, nil (no heat) @param hot_water_loop [OpenStudio::Model::PlantLoop] hot water loop to connect heating and reheat coils to @param chilled_water_loop [OpenStudio::Model::PlantLoop] chilled water loop to connect cooling coil to @param hvac_op_sch [String] name of the HVAC operation schedule or nil in which case will be defaulted to always on @param oa_damper_sch [String] name of the oa damper schedule, or nil in which case will be defaulted to always open @param fan_efficiency [Double] fan total efficiency, including motor and impeller @param fan_motor_efficiency [Double] fan motor efficiency @param fan_pressure_rise [Double] fan pressure rise, inH2O @param min_sys_airflow_ratio [Double] minimum system airflow ratio @param vav_sizing_option [String] air system sizing option, Coincident or NonCoincident @param econo_ctrl_mthd [String] economizer control type @return [OpenStudio::Model::AirLoopHVAC] the resulting VAV air loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 1821
def model_add_vav_reheat(model,
                         thermal_zones,
                         system_name: nil,
                         return_plenum: nil,
                         heating_type: nil,
                         reheat_type: nil,
                         hot_water_loop: nil,
                         chilled_water_loop: nil,
                         hvac_op_sch: nil,
                         oa_damper_sch: nil,
                         fan_efficiency: 0.62,
                         fan_motor_efficiency: 0.9,
                         fan_pressure_rise: 4.0,
                         min_sys_airflow_ratio: 0.3,
                         vav_sizing_option: 'Coincident',
                         econo_ctrl_mthd: nil)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding VAV system for #{thermal_zones.size} zones.")

  # create air handler
  air_loop = OpenStudio::Model::AirLoopHVAC.new(model)
  if system_name.nil?
    air_loop.setName("#{thermal_zones.size} Zone VAV")
  else
    air_loop.setName(system_name)
  end

  # hvac operation schedule
  if hvac_op_sch.nil?
    hvac_op_sch = model.alwaysOnDiscreteSchedule
  else
    hvac_op_sch = model_add_schedule(model, hvac_op_sch)
  end

  # oa damper schedule
  unless oa_damper_sch.nil?
    oa_damper_sch = model_add_schedule(model, oa_damper_sch)
  end

  # default design temperatures and settings used across all air loops
  dsgn_temps = standard_design_sizing_temperatures
  sizing_system = adjust_sizing_system(air_loop, dsgn_temps)
  if !min_sys_airflow_ratio.nil?
    if model.version < OpenStudio::VersionString.new('2.7.0')
      sizing_system.setMinimumSystemAirFlowRatio(min_sys_airflow_ratio)
    else
      sizing_system.setCentralHeatingMaximumSystemAirFlowRatio(min_sys_airflow_ratio)
    end
  end
  sizing_system.setSizingOption(vav_sizing_option) unless vav_sizing_option.nil?
  unless hot_water_loop.nil?
    hw_temp_c = hot_water_loop.sizingPlant.designLoopExitTemperature
    hw_delta_t_k = hot_water_loop.sizingPlant.loopDesignTemperatureDifference
  end

  # air handler controls
  sa_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                dsgn_temps['clg_dsgn_sup_air_temp_c'],
                                                                                name: "Supply Air Temp - #{dsgn_temps['clg_dsgn_sup_air_temp_f']}F",
                                                                                schedule_type_limit: 'Temperature')
  sa_stpt_manager = OpenStudio::Model::SetpointManagerScheduled.new(model, sa_temp_sch)
  sa_stpt_manager.setName("#{air_loop.name} Supply Air Setpoint Manager")
  sa_stpt_manager.addToNode(air_loop.supplyOutletNode)

  # create fan
  # @type [OpenStudio::Model::FanVariableVolume] fan
  fan = create_fan_by_name(model,
                           'VAV_System_Fan',
                           fan_name: "#{air_loop.name} Fan",
                           fan_efficiency: fan_efficiency,
                           pressure_rise: fan_pressure_rise,
                           motor_efficiency: fan_motor_efficiency,
                           end_use_subcategory: 'VAV System Fans')
  fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)
  fan.addToNode(air_loop.supplyInletNode)

  # create heating coil
  if hot_water_loop.nil?
    if heating_type == 'Electricity'
      htg_coil = create_coil_heating_electric(model,
                                              air_loop_node: air_loop.supplyInletNode,
                                              name: "#{air_loop.name} Main Electric Htg Coil")
    else # default to NaturalGas
      htg_coil = create_coil_heating_gas(model,
                                         air_loop_node: air_loop.supplyInletNode,
                                         name: "#{air_loop.name} Main Gas Htg Coil")
    end
  else
    htg_coil = create_coil_heating_water(model,
                                         hot_water_loop,
                                         air_loop_node: air_loop.supplyInletNode,
                                         name: "#{air_loop.name} Main Htg Coil",
                                         rated_inlet_water_temperature: hw_temp_c,
                                         rated_outlet_water_temperature: (hw_temp_c - hw_delta_t_k),
                                         rated_inlet_air_temperature: dsgn_temps['prehtg_dsgn_sup_air_temp_c'],
                                         rated_outlet_air_temperature: dsgn_temps['htg_dsgn_sup_air_temp_c'])
  end

  # set the setpointmanager for the central/preheat coil if required
  model_set_central_preheat_coil_spm(model, thermal_zones, htg_coil)

  # create cooling coil
  if chilled_water_loop.nil?
    create_coil_cooling_dx_two_speed(model,
                                     air_loop_node: air_loop.supplyInletNode,
                                     name: "#{air_loop.name} 2spd DX Clg Coil",
                                     type: 'OS default')
  else
    create_coil_cooling_water(model,
                              chilled_water_loop,
                              air_loop_node: air_loop.supplyInletNode,
                              name: "#{air_loop.name} Clg Coil")
  end

  # outdoor air intake system
  oa_intake_controller = OpenStudio::Model::ControllerOutdoorAir.new(model)
  oa_intake_controller.setName("#{air_loop.name} OA Controller")
  oa_intake_controller.setMinimumLimitType('FixedMinimum')
  oa_intake_controller.autosizeMinimumOutdoorAirFlowRate
  oa_intake_controller.resetMaximumFractionofOutdoorAirSchedule
  oa_intake_controller.resetEconomizerMinimumLimitDryBulbTemperature
  unless econo_ctrl_mthd.nil?
    oa_intake_controller.setEconomizerControlType(econo_ctrl_mthd)
  end
  unless oa_damper_sch.nil?
    oa_intake_controller.setMinimumOutdoorAirSchedule(oa_damper_sch)
  end
  controller_mv = oa_intake_controller.controllerMechanicalVentilation
  controller_mv.setName("#{air_loop.name} Vent Controller")
  controller_mv.setSystemOutdoorAirMethod('ZoneSum')
  oa_intake = OpenStudio::Model::AirLoopHVACOutdoorAirSystem.new(model, oa_intake_controller)
  oa_intake.setName("#{air_loop.name} OA System")
  oa_intake.addToNode(air_loop.supplyInletNode)

  # set air loop availability controls and night cycle manager, after oa system added
  air_loop.setAvailabilitySchedule(hvac_op_sch)
  air_loop.setNightCycleControlType('CycleOnAny')

  if model.version < OpenStudio::VersionString.new('3.5.0')
    avail_mgr = air_loop.availabilityManager
    if avail_mgr.is_initialized
      avail_mgr = avail_mgr.get
    else
      avail_mgr = nil
    end
  else
    avail_mgr = air_loop.availabilityManagers[0]
  end

  if !avail_mgr.nil? && avail_mgr.to_AvailabilityManagerNightCycle.is_initialized
    avail_mgr = avail_mgr.to_AvailabilityManagerNightCycle.get
    avail_mgr.setCyclingRunTime(1800)
  end

  # hook the VAV system to each zone
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "Adding VAV system terminal for #{zone.name}")

    # create reheat coil
    case reheat_type
    when 'NaturalGas', 'Gas'
      rht_coil = create_coil_heating_gas(model,
                                         name: "#{zone.name} Gas Reheat Coil")
    when 'Electricity'
      rht_coil = create_coil_heating_electric(model,
                                              name: "#{zone.name} Electric Reheat Coil")
    when 'Water'
      rht_coil = create_coil_heating_water(model,
                                           hot_water_loop,
                                           name: "#{zone.name} Reheat Coil",
                                           rated_inlet_water_temperature: hw_temp_c,
                                           rated_outlet_water_temperature: (hw_temp_c - hw_delta_t_k),
                                           rated_inlet_air_temperature: dsgn_temps['htg_dsgn_sup_air_temp_c'],
                                           rated_outlet_air_temperature: dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    else
      # no reheat
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Model.Model', "No reheat coil for terminal in #{zone.name}")
    end

    # set zone reheat temperatures depending on reheat
    case reheat_type
    when 'NaturalGas', 'Gas', 'Electricity', 'Water'
      # create vav terminal
      terminal = OpenStudio::Model::AirTerminalSingleDuctVAVReheat.new(model, model.alwaysOnDiscreteSchedule, rht_coil)
      terminal.setName("#{zone.name} VAV Terminal")
      if model.version < OpenStudio::VersionString.new('3.0.1')
        terminal.setZoneMinimumAirFlowMethod('Constant')
      else
        terminal.setZoneMinimumAirFlowInputMethod('Constant')
      end
      # default to single maximum control logic
      terminal.setDamperHeatingAction('Normal')
      terminal.setMaximumReheatAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
      air_loop.multiAddBranchForZone(zone, terminal.to_HVACComponent.get)
      oa_rate = OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate_per_area(zone)
      air_terminal_single_duct_vav_reheat_apply_initial_prototype_damper_position(terminal, oa_rate)

      # zone sizing
      sizing_zone = zone.sizingZone
      sizing_zone.setCoolingDesignAirFlowMethod('DesignDayWithLimit')
      sizing_zone.setHeatingDesignAirFlowMethod('DesignDay')
      sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
      sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])
    else
      # no reheat
      # create vav terminal
      terminal = OpenStudio::Model::AirTerminalSingleDuctVAVNoReheat.new(model, model.alwaysOnDiscreteSchedule)
      terminal.setName("#{zone.name} VAV Terminal")
      if model.version < OpenStudio::VersionString.new('3.0.1')
        terminal.setZoneMinimumAirFlowMethod('Constant')
      else
        terminal.setZoneMinimumAirFlowInputMethod('Constant')
      end
      air_loop.multiAddBranchForZone(zone, terminal.to_HVACComponent.get)
      oa_rate = OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate_per_area(zone)
      air_terminal_single_duct_vav_reheat_apply_initial_prototype_damper_position(terminal, oa_rate)

      # zone sizing
      sizing_zone = zone.sizingZone
      sizing_zone.setCoolingDesignAirFlowMethod('DesignDayWithLimit')
      sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    end

    unless return_plenum.nil?
      zone.setReturnPlenum(return_plenum)
    end
  end

  return air_loop
end
model_add_vrf(model, thermal_zones, ventilation: false) click to toggle source

Adds Variable Refrigerant Flow system and terminal units for each zone

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to add fan coil units @param ventilation [Boolean] If true, ventilation will be supplied through the unit. If false,

no ventilation will be supplied through the unit, with the expectation that it will be provided by a DOAS or separate system.

@return [Array<OpenStudio::Model::ZoneHVACTerminalUnitVariableRefrigerantFlow>] array of vrf units.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 4597
def model_add_vrf(model,
                  thermal_zones,
                  ventilation: false)

  # create vrf outdoor unit
  master_zone = thermal_zones[0]
  vrf_outdoor_unit = create_air_conditioner_variable_refrigerant_flow(model,
                                                                      name: "#{thermal_zones.size} Zone VRF System",
                                                                      master_zone: master_zone)

  # default design temperatures used across all air loops
  dsgn_temps = standard_design_sizing_temperatures

  vrfs = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding vrf unit for #{zone.name}.")

    # zone sizing
    sizing_zone = zone.sizingZone
    sizing_zone.setZoneCoolingDesignSupplyAirTemperature(dsgn_temps['zn_clg_dsgn_sup_air_temp_c'])
    sizing_zone.setZoneHeatingDesignSupplyAirTemperature(dsgn_temps['zn_htg_dsgn_sup_air_temp_c'])

    # add vrf terminal unit
    vrf_terminal_unit = OpenStudio::Model::ZoneHVACTerminalUnitVariableRefrigerantFlow.new(model)
    vrf_terminal_unit.setName("#{zone.name} VRF Terminal Unit")
    vrf_terminal_unit.addToThermalZone(zone)
    vrf_terminal_unit.setTerminalUnitAvailabilityschedule(model.alwaysOnDiscreteSchedule)

    unless ventilation
      vrf_terminal_unit.setOutdoorAirFlowRateDuringCoolingOperation(0.0)
      vrf_terminal_unit.setOutdoorAirFlowRateDuringHeatingOperation(0.0)
      vrf_terminal_unit.setOutdoorAirFlowRateWhenNoCoolingorHeatingisNeeded(0.0)
    end

    # set fan variables
    # always off denotes cycling fan
    vrf_terminal_unit.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)
    vrf_fan = vrf_terminal_unit.supplyAirFan.to_FanOnOff.get
    vrf_fan.setPressureRise(300.0)
    vrf_fan.setMotorEfficiency(0.8)
    vrf_fan.setFanEfficiency(0.6)
    vrf_fan.setName("#{zone.name} VRF Unit Cycling Fan")

    # add to main condensing unit
    vrf_outdoor_unit.addTerminal(vrf_terminal_unit)
  end

  return vrfs
end
model_add_water_heater(model, water_heater_capacity, water_heater_volume, water_heater_fuel, service_water_temperature, parasitic_fuel_consumption_rate, swh_temp_sch, set_peak_use_flowrate, peak_flowrate, flowrate_schedule, water_heater_thermal_zone, number_water_heaters) click to toggle source

Creates a water heater and attaches it to the supplied service water heating loop.

@param model [OpenStudio::Model::Model] OpenStudio model object @param water_heater_capacity [Double] water heater capacity, in W @param water_heater_volume [Double] water heater volume, in m^3 @param water_heater_fuel [Double] valid choices are NaturalGas, Electricity @param service_water_temperature [Double] water heater temperature, in C @param parasitic_fuel_consumption_rate [Double] water heater parasitic fuel consumption rate, in W @param swh_temp_sch [OpenStudio::Model::Schedule] the service water heating schedule. If nil, will be defaulted. @param set_peak_use_flowrate [Boolean] if true, the peak flow rate and flow rate schedule will be set. @param peak_flowrate [Double] in m^3/s @param flowrate_schedule [String] name of the flow rate schedule @param water_heater_thermal_zone [OpenStudio::Model::ThermalZone] zone to place water heater in.

If nil, will be assumed in 70F air for heat loss.

@param number_water_heaters [Double] the number of water heaters represented by the capacity and volume inputs. Used to modify efficiencies for water heaters based on individual component size while avoiding having to model lots of individual water heaters (for runtime sake). @return [OpenStudio::Model::WaterHeaterMixed] the resulting water heater

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ServiceWaterHeating.rb, line 164
def model_add_water_heater(model,
                           water_heater_capacity,
                           water_heater_volume,
                           water_heater_fuel,
                           service_water_temperature,
                           parasitic_fuel_consumption_rate,
                           swh_temp_sch,
                           set_peak_use_flowrate,
                           peak_flowrate,
                           flowrate_schedule,
                           water_heater_thermal_zone,
                           number_water_heaters)
  # Water heater
  # @todo Standards - Change water heater methodology to follow
  # 'Model Enhancements Appendix A.'
  water_heater_capacity_btu_per_hr = OpenStudio.convert(water_heater_capacity, 'W', 'Btu/hr').get
  water_heater_capacity_kbtu_per_hr = OpenStudio.convert(water_heater_capacity_btu_per_hr, 'Btu/hr', 'kBtu/hr').get
  water_heater_vol_gal = OpenStudio.convert(water_heater_volume, 'm^3', 'gal').get

  # Temperature schedule type limits
  temp_sch_type_limits = OpenstudioStandards::Schedules.create_schedule_type_limits(model,
                                                                                    name: 'Temperature Schedule Type Limits',
                                                                                    lower_limit_value: 0.0,
                                                                                    upper_limit_value: 100.0,
                                                                                    numeric_type: 'Continuous',
                                                                                    unit_type: 'Temperature')

  if swh_temp_sch.nil?
    # Service water heating loop controls
    swh_temp_c = service_water_temperature
    swh_temp_f = OpenStudio.convert(swh_temp_c, 'C', 'F').get
    swh_delta_t_r = 9 # 9F delta-T
    swh_temp_c = OpenStudio.convert(swh_temp_f, 'F', 'C').get
    swh_delta_t_k = OpenStudio.convert(swh_delta_t_r, 'R', 'K').get
    swh_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                   swh_temp_c,
                                                                                   name: "Service Water Loop Temp - #{swh_temp_f.round}F",
                                                                                   schedule_type_limit: 'Temperature')
    swh_temp_sch.setScheduleTypeLimits(temp_sch_type_limits)
  end

  # Water heater depends on the fuel type
  water_heater = OpenStudio::Model::WaterHeaterMixed.new(model)

  # Assign a quantity to the water heater if it represents multiple water heaters
  if number_water_heaters > 1
    water_heater.setName("#{number_water_heaters}X #{(water_heater_vol_gal / number_water_heaters).round}gal #{water_heater_fuel} Water Heater - #{(water_heater_capacity_kbtu_per_hr / number_water_heaters).round}kBtu/hr")
    water_heater.additionalProperties.setFeature('component_quantity', number_water_heaters)
  else
    water_heater.setName("#{water_heater_vol_gal.round}gal #{water_heater_fuel} Water Heater - #{water_heater_capacity_kbtu_per_hr.round}kBtu/hr")
  end

  water_heater.setTankVolume(OpenStudio.convert(water_heater_vol_gal, 'gal', 'm^3').get)
  water_heater.setSetpointTemperatureSchedule(swh_temp_sch)
  water_heater.setDeadbandTemperatureDifference(2.0)

  if water_heater_thermal_zone.nil?
    # Assume the water heater is indoors at 70F or 72F
    case template
    when '90.1-2004', '90.1-2007', '90.1-2010', '90.1-2013', '90.1-2016', '90.1-2019'
      indoor_temp = 71.6
    else
      indoor_temp = 70.0
    end
    default_water_heater_ambient_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                            OpenStudio.convert(indoor_temp, 'F', 'C').get,
                                                                                                            name: 'Water Heater Ambient Temp Schedule - ' + indoor_temp.to_s + 'f',
                                                                                                            schedule_type_limit: 'Temperature')
    default_water_heater_ambient_temp_sch.setScheduleTypeLimits(temp_sch_type_limits)
    water_heater.setAmbientTemperatureIndicator('Schedule')
    water_heater.setAmbientTemperatureSchedule(default_water_heater_ambient_temp_sch)
    water_heater.resetAmbientTemperatureThermalZone
  else
    water_heater.setAmbientTemperatureIndicator('ThermalZone')
    water_heater.setAmbientTemperatureThermalZone(water_heater_thermal_zone)
    water_heater.resetAmbientTemperatureSchedule
  end

  water_heater.setMaximumTemperatureLimit(service_water_temperature)
  water_heater.setDeadbandTemperatureDifference(OpenStudio.convert(3.6, 'R', 'K').get)
  water_heater.setHeaterControlType('Cycle')
  water_heater.setHeaterMaximumCapacity(OpenStudio.convert(water_heater_capacity_btu_per_hr, 'Btu/hr', 'W').get)
  water_heater.setOffCycleParasiticHeatFractiontoTank(0.8)
  water_heater.setIndirectWaterHeatingRecoveryTime(1.5) # 1.5hrs
  if water_heater_fuel == 'Electricity'
    water_heater.setHeaterFuelType('Electricity')
    water_heater.setHeaterThermalEfficiency(1.0)
    water_heater.setOffCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOnCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOffCycleParasiticFuelType('Electricity')
    water_heater.setOnCycleParasiticFuelType('Electricity')
    water_heater.setOffCycleLossCoefficienttoAmbientTemperature(1.053)
    water_heater.setOnCycleLossCoefficienttoAmbientTemperature(1.053)
  elsif water_heater_fuel == 'Natural Gas' || water_heater_fuel == 'NaturalGas'
    water_heater.setHeaterFuelType('Gas')
    water_heater.setHeaterThermalEfficiency(0.78)
    water_heater.setOffCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOnCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOffCycleParasiticFuelType('Gas')
    water_heater.setOnCycleParasiticFuelType('Gas')
    water_heater.setOffCycleLossCoefficienttoAmbientTemperature(6.0)
    water_heater.setOnCycleLossCoefficienttoAmbientTemperature(6.0)
  elsif water_heater_fuel == 'HeatPump'
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', 'Simple workaround to represent heat pump water heaters without incurring significant runtime penalty associated with using correct objects.')
    # Make a part-load efficiency modifier curve with a value above 1, which
    # is multiplied by the nominal efficiency of 100% to represent
    # the COP of a HPWH.
    # @todo could make this workaround better by using EMS
    # to modify this curve output in realtime based on
    # the OA temperature.
    hpwh_cop = 2.8
    eff_f_of_plr = OpenStudio::Model::CurveCubic.new(model)
    eff_f_of_plr.setName("HPWH_COP_#{hpwh_cop}")
    eff_f_of_plr.setCoefficient1Constant(hpwh_cop)
    eff_f_of_plr.setCoefficient2x(0.0)
    eff_f_of_plr.setCoefficient3xPOW2(0.0)
    eff_f_of_plr.setCoefficient4xPOW3(0.0)
    eff_f_of_plr.setMinimumValueofx(0.0)
    eff_f_of_plr.setMaximumValueofx(1.0)
    water_heater.setHeaterFuelType('Electricity')
    water_heater.setHeaterThermalEfficiency(1.0)
    water_heater.setPartLoadFactorCurve(eff_f_of_plr)
    water_heater.setOffCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOnCycleParasiticFuelConsumptionRate(parasitic_fuel_consumption_rate)
    water_heater.setOffCycleParasiticFuelType('Electricity')
    water_heater.setOnCycleParasiticFuelType('Electricity')
    water_heater.setOffCycleLossCoefficienttoAmbientTemperature(1.053)
    water_heater.setOnCycleLossCoefficienttoAmbientTemperature(1.053)
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "#{water_heater_fuel} is not a valid water heater fuel.  Valid choices are Electricity, NaturalGas, and HeatPump.")
  end

  if set_peak_use_flowrate
    rated_flow_rate_m3_per_s = peak_flowrate
    rated_flow_rate_gal_per_min = OpenStudio.convert(rated_flow_rate_m3_per_s, 'm^3/s', 'gal/min').get
    water_heater.setPeakUseFlowRate(rated_flow_rate_m3_per_s)

    schedule = model_add_schedule(model, flowrate_schedule)
    water_heater.setUseFlowRateFractionSchedule(schedule)
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Added water heater called #{water_heater.name}")

  return water_heater
end
model_add_water_source_hp(model, thermal_zones, condenser_loop, ventilation: true) click to toggle source

Adds zone level water-to-air heat pumps for each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones served by heat pumps @param condenser_loop [OpenStudio::Model::PlantLoop] the condenser loop for the heat pumps # @param ventilation [Boolean] if true, ventilation will be supplied through the unit.

If false, no ventilation will be supplied through the unit, with the expectation that it will be provided by a DOAS or separate system.

@return [Array<OpenStudio::Model::ZoneHVACWaterToAirHeatPump>] an array of heat pumps

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 5607
def model_add_water_source_hp(model,
                              thermal_zones,
                              condenser_loop,
                              ventilation: true)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', 'Adding zone water-to-air heat pump.')

  water_to_air_hp_systems = []
  thermal_zones.each do |zone|
    supplemental_htg_coil = create_coil_heating_electric(model,
                                                         name: "#{zone.name} Supplemental Htg Coil")
    htg_coil = create_coil_heating_water_to_air_heat_pump_equation_fit(model,
                                                                       condenser_loop,
                                                                       name: "#{zone.name} Water-to-Air HP Htg Coil")
    clg_coil = create_coil_cooling_water_to_air_heat_pump_equation_fit(model,
                                                                       condenser_loop,
                                                                       name: "#{zone.name} Water-to-Air HP Clg Coil")

    # add fan
    fan = create_fan_by_name(model,
                             'WSHP_Fan',
                             fan_name: "#{zone.name} WSHP Fan")
    fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

    water_to_air_hp_system = OpenStudio::Model::ZoneHVACWaterToAirHeatPump.new(model,
                                                                               model.alwaysOnDiscreteSchedule,
                                                                               fan,
                                                                               htg_coil,
                                                                               clg_coil,
                                                                               supplemental_htg_coil)
    water_to_air_hp_system.setName("#{zone.name} WSHP")
    unless ventilation
      water_to_air_hp_system.setOutdoorAirFlowRateDuringHeatingOperation(0.0)
      water_to_air_hp_system.setOutdoorAirFlowRateDuringCoolingOperation(0.0)
      water_to_air_hp_system.setOutdoorAirFlowRateWhenNoCoolingorHeatingisNeeded(0.0)
    end
    water_to_air_hp_system.addToThermalZone(zone)

    water_to_air_hp_systems << water_to_air_hp_system
  end

  return water_to_air_hp_systems
end
model_add_waterside_economizer(model, chilled_water_loop, condenser_water_loop, integrated: true) click to toggle source

Adds a waterside economizer to the chilled water and condenser loop

@param model [OpenStudio::Model::Model] OpenStudio model object @param integrated [Boolean] when set to true, models an integrated waterside economizer

Integrated: in series with chillers, can run simultaneously with chillers
Non-Integrated: in parallel with chillers, chillers locked out during operation
# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6588
def model_add_waterside_economizer(model, chilled_water_loop, condenser_water_loop,
                                   integrated: true)

  # make a new heat exchanger
  heat_exchanger = OpenStudio::Model::HeatExchangerFluidToFluid.new(model)
  heat_exchanger.setHeatExchangeModelType('CounterFlow')
  # zero degree minimum necessary to allow both economizer and heat exchanger to operate in both integrated and non-integrated archetypes
  # possibly results from an EnergyPlus issue that didn't get resolved correctly https://github.com/NREL/EnergyPlus/issues/5626
  heat_exchanger.setMinimumTemperatureDifferencetoActivateHeatExchanger(OpenStudio.convert(0.0, 'R', 'K').get)
  heat_exchanger.setHeatTransferMeteringEndUseType('FreeCooling')
  heat_exchanger.setOperationMinimumTemperatureLimit(OpenStudio.convert(35.0, 'F', 'C').get)
  heat_exchanger.setOperationMaximumTemperatureLimit(OpenStudio.convert(72.0, 'F', 'C').get)
  heat_exchanger.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

  # get the chillers on the chilled water loop
  chillers = chilled_water_loop.supplyComponents('OS:Chiller:Electric:EIR'.to_IddObjectType)

  if integrated
    if chillers.empty?
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "No chillers were found on #{chilled_water_loop.name}; only modeling waterside economizer")
    end

    # set methods for integrated heat exchanger
    heat_exchanger.setName('Integrated Waterside Economizer Heat Exchanger')
    heat_exchanger.setControlType('CoolingDifferentialOnOff')

    # add the heat exchanger to the chilled water loop upstream of the chiller
    heat_exchanger.addToNode(chilled_water_loop.supplyInletNode)

    # Copy the setpoint managers from the plant's supply outlet node to the chillers and HX outlets.
    # This is necessary so that the correct type of operation scheme will be created.
    # Without this, OS will create an uncontrolled operation scheme and the chillers will never run.
    chw_spms = chilled_water_loop.supplyOutletNode.setpointManagers
    objs = []
    chillers.each do |obj|
      objs << obj.to_ChillerElectricEIR.get
    end
    objs << heat_exchanger
    objs.each do |obj|
      outlet = obj.supplyOutletModelObject.get.to_Node.get
      chw_spms.each do |spm|
        new_spm = spm.clone.to_SetpointManager.get
        new_spm.addToNode(outlet)
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Copied SPM #{spm.name} to the outlet of #{obj.name}.")
      end
    end
  else
    # non-integrated
    # if the heat exchanger can meet the entire load, the heat exchanger will run and the chiller is disabled.
    # In E+, only one chiller can be tied to a given heat exchanger, so if you have multiple chillers,
    # they will cannot be tied to a single heat exchanger without EMS.
    chiller = nil
    if chillers.empty?
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "No chillers were found on #{chilled_water_loop.name}; cannot add a non-integrated waterside economizer.")
      heat_exchanger.setControlType('CoolingSetpointOnOff')
    elsif chillers.size > 1
      chiller = chillers.min
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "More than one chiller was found on #{chilled_water_loop.name}.  EnergyPlus only allows a single chiller to be interlocked with the HX.  Chiller #{chiller.name} was selected.  Additional chillers will not be locked out during HX operation.")
    else # 1 chiller
      chiller = chillers[0]
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Chiller '#{chiller.name}' will be locked out during HX operation.")
    end
    chiller = chiller.to_ChillerElectricEIR.get

    # set methods for non-integrated heat exchanger
    heat_exchanger.setName('Non-Integrated Waterside Economizer Heat Exchanger')
    heat_exchanger.setControlType('CoolingSetpointOnOffWithComponentOverride')

    # add the heat exchanger to a supply side branch of the chilled water loop parallel with the chiller(s)
    chilled_water_loop.addSupplyBranchForComponent(heat_exchanger)

    # Copy the setpoint managers from the plant's supply outlet node to the HX outlet.
    # This is necessary so that the correct type of operation scheme will be created.
    # Without this, the HX will never run
    chw_spms = chilled_water_loop.supplyOutletNode.setpointManagers
    outlet = heat_exchanger.supplyOutletModelObject.get.to_Node.get
    chw_spms.each do |spm|
      new_spm = spm.clone.to_SetpointManager.get
      new_spm.addToNode(outlet)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Copied SPM #{spm.name} to the outlet of #{heat_exchanger.name}.")
    end

    # set the supply and demand inlet fields to interlock the heat exchanger with the chiller
    chiller_supply_inlet = chiller.supplyInletModelObject.get.to_Node.get
    heat_exchanger.setComponentOverrideLoopSupplySideInletNode(chiller_supply_inlet)
    chiller_demand_inlet = chiller.demandInletModelObject.get.to_Node.get
    heat_exchanger.setComponentOverrideLoopDemandSideInletNode(chiller_demand_inlet)

    # check if the chilled water pump is on a branch with the chiller.
    # if it is, move this pump before the splitter so that it can push water through either the chiller or the heat exchanger.
    pumps_on_branches = []
    # search for constant and variable speed pumps  between supply splitter and supply mixer.
    chilled_water_loop.supplyComponents(chilled_water_loop.supplySplitter, chilled_water_loop.supplyMixer).each do |supply_comp|
      if supply_comp.to_PumpConstantSpeed.is_initialized
        pumps_on_branches << supply_comp.to_PumpConstantSpeed.get
      elsif supply_comp.to_PumpVariableSpeed.is_initialized
        pumps_on_branches << supply_comp.to_PumpVariableSpeed.get
      end
    end
    # If only one pump is found, clone it, put the clone on the supply inlet node, and delete the original pump.
    # If multiple branch pumps, clone the first pump found, add it to the inlet of the heat exchanger, and warn user.
    if pumps_on_branches.size == 1
      pump = pumps_on_branches[0]
      pump_clone = pump.clone(model).to_StraightComponent.get
      pump_clone.addToNode(chilled_water_loop.supplyInletNode)
      pump.remove
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', 'Since you need a pump to move water through the HX, the pump serving the chiller was moved so that it can also serve the HX depending on the desired control sequence.')
    elsif pumps_on_branches.size > 1
      hx_inlet_node = heat_exchanger.inletModelObject.get.to_Node.get
      pump = pumps_on_branches[0]
      pump_clone = pump.clone(model).to_StraightComponent.get
      pump_clone.addToNode(hx_inlet_node)
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', 'Found 2 or more pumps on branches.  Since you need a pump to move water through the HX, the first pump encountered was copied and placed in series with the HX.  This pump might not be reasonable for this duty, please check.')
    end
  end

  # add heat exchanger to condenser water loop
  condenser_water_loop.addDemandBranchForComponent(heat_exchanger)

  # change setpoint manager on condenser water loop to allow waterside economizing
  dsgn_sup_wtr_temp_f = 42.0
  dsgn_sup_wtr_temp_c = OpenStudio.convert(dsgn_sup_wtr_temp_f, 'F', 'C').get
  condenser_water_loop.supplyOutletNode.setpointManagers.each do |spm|
    if spm.to_SetpointManagerFollowOutdoorAirTemperature.is_initialized
      spm = spm.to_SetpointManagerFollowOutdoorAirTemperature.get
      spm.setMinimumSetpointTemperature(dsgn_sup_wtr_temp_c)
    elsif spm.to_SetpointManagerScheduled.is_initialized
      spm = spm.to_SetpointManagerScheduled.get
      cw_temp_sch = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                    dsgn_sup_wtr_temp_c,
                                                                                    name: "#{chilled_water_loop.name} Temp - #{dsgn_sup_wtr_temp_f.round(0)}F",
                                                                                    schedule_type_limit: 'Temperature')
      spm.setSchedule(cw_temp_sch)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Changing condenser water loop setpoint for '#{condenser_water_loop.name}' to '#{cw_temp_sch.name}' to account for the waterside economizer.")
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', "Condenser water loop '#{condenser_water_loop.name}' setpoint manager '#{spm.name}' is not a recognized setpoint manager type.  Cannot change to account for the waterside economizer.")
    end
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Added #{heat_exchanger.name} to condenser water loop #{condenser_water_loop.name} and chilled water loop #{chilled_water_loop.name} to enable waterside economizing.")

  return heat_exchanger
end
model_add_window_ac(model, thermal_zones) click to toggle source

Adds a window air conditioner to each zone. Code adapted from: github.com/NREL/OpenStudio-BEopt/blob/master/measures/ResidentialHVACRoomAirConditioner/measure.rb

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to add fan coil units to. @return [Array<OpenStudio::Model::ZoneHVACPackagedTerminalAirConditioner>] and array of PTACs used as window AC units

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 5278
def model_add_window_ac(model,
                        thermal_zones)

  # Defaults
  eer = 8.5 # Btu/W-h
  cop = OpenStudio.convert(eer, 'Btu/h', 'W').get
  shr = 0.65 # The sensible heat ratio (ratio of the sensible portion of the load to the total load) at the nominal rated capacity
  # airflow_cfm_per_ton = 350.0 # cfm/ton

  acs = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding window AC for #{zone.name}.")

    clg_coil = create_coil_cooling_dx_single_speed(model,
                                                   name: "#{zone.name} Window AC Cooling Coil",
                                                   type: 'Window AC',
                                                   cop: cop)
    clg_coil.setRatedSensibleHeatRatio(shr)
    clg_coil.setRatedEvaporatorFanPowerPerVolumeFlowRate(OpenStudio::OptionalDouble.new(773.3))
    clg_coil.setEvaporativeCondenserEffectiveness(OpenStudio::OptionalDouble.new(0.9))
    clg_coil.setMaximumOutdoorDryBulbTemperatureForCrankcaseHeaterOperation(OpenStudio::OptionalDouble.new(10))
    clg_coil.setBasinHeaterSetpointTemperature(OpenStudio::OptionalDouble.new(2))

    fan = create_fan_by_name(model,
                             'Window_AC_Supply_Fan',
                             fan_name: "#{zone.name} Window AC Supply Fan",
                             end_use_subcategory: 'Window AC Fans')
    fan.setAvailabilitySchedule(model.alwaysOnDiscreteSchedule)

    htg_coil = create_coil_heating_electric(model,
                                            name: "#{zone.name} Window AC Always Off Htg Coil",
                                            schedule: model.alwaysOffDiscreteSchedule,
                                            nominal_capacity: 0)
    ptac = OpenStudio::Model::ZoneHVACPackagedTerminalAirConditioner.new(model,
                                                                         model.alwaysOnDiscreteSchedule,
                                                                         fan,
                                                                         htg_coil,
                                                                         clg_coil)
    ptac.setName("#{zone.name} Window AC")
    ptac.setSupplyAirFanOperatingModeSchedule(model.alwaysOffDiscreteSchedule)
    ptac.addToThermalZone(zone)
    acs << ptac
  end

  return acs
end
model_add_zone_erv(model, thermal_zones) click to toggle source

Adds zone level ERVs for each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to add heat pumps to. @return [Array<OpenStudio::Model::ZoneHVACEnergyRecoveryVentilator>] an array of zone ERVs @todo review the static pressure rise for the ERV

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 5657
def model_add_zone_erv(model,
                       thermal_zones)
  ervs = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding ERV for #{zone.name}.")

    # Determine the OA requirement for this zone
    min_oa_flow_m3_per_s_per_m2 = OpenstudioStandards::ThermalZone.thermal_zone_get_outdoor_airflow_rate_per_area(zone)
    supply_fan = create_fan_by_name(model,
                                    'ERV_Supply_Fan',
                                    fan_name: "#{zone.name} ERV Supply Fan")
    impeller_eff = fan_baseline_impeller_efficiency(supply_fan)
    fan_change_impeller_efficiency(supply_fan, impeller_eff)
    exhaust_fan = create_fan_by_name(model,
                                     'ERV_Supply_Fan',
                                     fan_name: "#{zone.name} ERV Exhaust Fan")
    fan_change_impeller_efficiency(exhaust_fan, impeller_eff)

    erv_controller = OpenStudio::Model::ZoneHVACEnergyRecoveryVentilatorController.new(model)
    erv_controller.setName("#{zone.name} ERV Controller")
    # erv_controller.setExhaustAirTemperatureLimit("NoExhaustAirTemperatureLimit")
    # erv_controller.setExhaustAirEnthalpyLimit("NoExhaustAirEnthalpyLimit")
    # erv_controller.setTimeofDayEconomizerFlowControlSchedule(self.alwaysOnDiscreteSchedule)
    # erv_controller.setHighHumidityControlFlag(false)

    heat_exchanger = OpenStudio::Model::HeatExchangerAirToAirSensibleAndLatent.new(model)
    heat_exchanger.setName("#{zone.name} ERV HX")
    heat_exchanger.setHeatExchangerType('Plate')
    heat_exchanger.setEconomizerLockout(false)
    heat_exchanger.setSupplyAirOutletTemperatureControl(false)
    heat_exchanger.setSensibleEffectivenessat100HeatingAirFlow(0.76)
    heat_exchanger.setSensibleEffectivenessat75HeatingAirFlow(0.81)
    heat_exchanger.setLatentEffectivenessat100HeatingAirFlow(0.68)
    heat_exchanger.setLatentEffectivenessat75HeatingAirFlow(0.73)
    heat_exchanger.setSensibleEffectivenessat100CoolingAirFlow(0.76)
    heat_exchanger.setSensibleEffectivenessat75CoolingAirFlow(0.81)
    heat_exchanger.setLatentEffectivenessat100CoolingAirFlow(0.68)
    heat_exchanger.setLatentEffectivenessat75CoolingAirFlow(0.73)

    zone_hvac = OpenStudio::Model::ZoneHVACEnergyRecoveryVentilator.new(model, heat_exchanger, supply_fan, exhaust_fan)
    zone_hvac.setName("#{zone.name} ERV")
    zone_hvac.setVentilationRateperUnitFloorArea(min_oa_flow_m3_per_s_per_m2)
    zone_hvac.setController(erv_controller)
    zone_hvac.addToThermalZone(zone)

    # ensure the ERV takes priority, so ventilation load is included when treated by other zonal systems
    # From EnergyPlus I/O reference:
    # "For situations where one or more equipment types has limited capacity or limited control capability, order the
    #  sequence so that the most controllable piece of equipment runs last. For example, with a dedicated outdoor air
    #  system (DOAS), the air terminal for the DOAS should be assigned Heating Sequence = 1 and Cooling Sequence = 1.
    #  Any other equipment should be assigned sequence 2 or higher so that it will see the net load after the DOAS air
    #  is added to the zone."
    zone.setCoolingPriority(zone_hvac.to_ModelObject.get, 1)
    zone.setHeatingPriority(zone_hvac.to_ModelObject.get, 1)

    # set the cooling and heating fraction to zero so that the ERV does not try to meet the heating or cooling load.
    if model.version < OpenStudio::VersionString.new('2.8.0')
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Model.Model', 'OpenStudio version is less than 2.8.0; ERV will attempt to meet heating and cooling load up to ventilation rate.  If this is not intended, use a newer version of OpenStudio.')
    else
      zone.setSequentialCoolingFraction(zone_hvac.to_ModelObject.get, 0.0)
      zone.setSequentialHeatingFraction(zone_hvac.to_ModelObject.get, 0.0)
    end

    # Calculate ERV SAT during sizing periods
    # Standard rating conditions based on AHRI Std 1060 - 2013
    # heating design
    oat_f = 35.0
    return_air_f = 70.0
    eff = heat_exchanger.sensibleEffectivenessat100HeatingAirFlow
    coldest_erv_supply_f = oat_f - (eff * (oat_f - return_air_f))
    coldest_erv_supply_c = OpenStudio.convert(coldest_erv_supply_f, 'F', 'C').get

    # cooling design
    oat_f = 95.0
    return_air_f = 75.0
    eff = heat_exchanger.sensibleEffectivenessat100CoolingAirFlow
    hottest_erv_supply_f = oat_f - (eff * (oat_f - return_air_f))
    hottest_erv_supply_c = OpenStudio.convert(hottest_erv_supply_f, 'F', 'C').get

    # Ensure that zone sizing accounts for OA from ERV
    sizing_zone = zone.sizingZone
    sizing_zone.setAccountforDedicatedOutdoorAirSystem(true)
    sizing_zone.setDedicatedOutdoorAirSystemControlStrategy('NeutralSupplyAir')
    sizing_zone.setDedicatedOutdoorAirLowSetpointTemperatureforDesign(coldest_erv_supply_c)
    sizing_zone.setDedicatedOutdoorAirHighSetpointTemperatureforDesign(hottest_erv_supply_c)

    ervs << zone_hvac
  end

  return ervs
end
model_add_zone_heat_cool_request_count_program(model, thermal_zones) click to toggle source

Make EMS program that will compare ‘measured’ zone air temperatures to thermostats setpoint to determine if zone needs cooling or heating. Program will output the total zones needing heating and cooling and the their ratio using the total number of zones.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones to dictate cooling or heating mode of water plant

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6444
def model_add_zone_heat_cool_request_count_program(model, thermal_zones)
  # create container schedules to hold number of zones needing heating and cooling
  sch_zones_needing_heating = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                              0,
                                                                                              name: 'Zones Needing Heating Count Schedule',
                                                                                              schedule_type_limit: 'Dimensionless')

  zone_needing_heating_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_zones_needing_heating,
                                                                                        'Schedule:Year',
                                                                                        'Schedule Value')
  zone_needing_heating_actuator.setName('Zones_Needing_Heating')

  sch_zones_needing_cooling = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                              0,
                                                                                              name: 'Zones Needing Cooling Count Schedule',
                                                                                              schedule_type_limit: 'Dimensionless')

  zone_needing_cooling_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_zones_needing_cooling,
                                                                                        'Schedule:Year',
                                                                                        'Schedule Value')
  zone_needing_cooling_actuator.setName('Zones_Needing_Cooling')

  # create container schedules to hold ratio of zones needing heating and cooling
  sch_zones_needing_heating_ratio = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                    0,
                                                                                                    name: 'Zones Needing Heating Ratio Schedule',
                                                                                                    schedule_type_limit: 'Dimensionless')

  zone_needing_heating_ratio_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_zones_needing_heating_ratio,
                                                                                              'Schedule:Year',
                                                                                              'Schedule Value')
  zone_needing_heating_ratio_actuator.setName('Zone_Heating_Ratio')

  sch_zones_needing_cooling_ratio = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                    0,
                                                                                                    name: 'Zones Needing Cooling Ratio Schedule',
                                                                                                    schedule_type_limit: 'Dimensionless')

  zone_needing_cooling_ratio_actuator = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_zones_needing_cooling_ratio,
                                                                                              'Schedule:Year',
                                                                                              'Schedule Value')
  zone_needing_cooling_ratio_actuator.setName('Zone_Cooling_Ratio')

  #####
  # Create EMS program to check comfort exceedances
  ####

  # initalize inner body for heating and cooling requests programs
  determine_zone_cooling_needs_prg_inner_body = ''
  determine_zone_heating_needs_prg_inner_body = ''

  thermal_zones.each do |zone|
    # get existing 'sensors'
    exisiting_ems_sensors = model.getEnergyManagementSystemSensors
    exisiting_ems_sensors_names = exisiting_ems_sensors.collect { |sensor| sensor.name.get + '-' + sensor.outputVariableOrMeterName }

    # Create zone air temperature 'sensor' for the zone.
    zone_name = ems_friendly_name(zone.name)
    zone_air_sensor_name = "#{zone_name}_ctrl_temperature"

    unless exisiting_ems_sensors_names.include? zone_air_sensor_name + '-Zone Air Temperature'
      zone_ctrl_temperature = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Zone Air Temperature')
      zone_ctrl_temperature.setName(zone_air_sensor_name)
      zone_ctrl_temperature.setKeyName(zone.name.get)
    end

    # check for zone thermostats
    zone_thermostat = zone.thermostatSetpointDualSetpoint
    unless zone_thermostat.is_initialized
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Zone #{zone.name} does not have thermostats.")
      return false
    end

    zone_thermostat = zone.thermostatSetpointDualSetpoint.get
    zone_clg_thermostat = zone_thermostat.coolingSetpointTemperatureSchedule.get
    zone_htg_thermostat = zone_thermostat.heatingSetpointTemperatureSchedule.get

    # create new sensor for zone thermostat if it does not exist already
    zone_clg_thermostat_sensor_name = "#{zone_name}_upper_comfort_limit"
    zone_htg_thermostat_sensor_name = "#{zone_name}_lower_comfort_limit"

    unless exisiting_ems_sensors_names.include? zone_clg_thermostat_sensor_name + '-Schedule Value'
      # Upper comfort limit for the zone. Taken from existing thermostat schedules in the zone.
      zone_upper_comfort_limit = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')
      zone_upper_comfort_limit.setName(zone_clg_thermostat_sensor_name)
      zone_upper_comfort_limit.setKeyName(zone_clg_thermostat.name.get)
    end

    unless exisiting_ems_sensors_names.include? zone_htg_thermostat_sensor_name + '-Schedule Value'
      # Lower comfort limit for the zone. Taken from existing thermostat schedules in the zone.
      zone_lower_comfort_limit = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')
      zone_lower_comfort_limit.setName(zone_htg_thermostat_sensor_name)
      zone_lower_comfort_limit.setKeyName(zone_htg_thermostat.name.get)
    end

    # create program inner body for determining zone cooling needs
    if thermal_zones.include? zone
      determine_zone_cooling_needs_prg_inner_body += "IF #{zone_air_sensor_name} > #{zone_clg_thermostat_sensor_name},
                                                      SET Zones_Needing_Cooling = Zones_Needing_Cooling + 1,
                                                    ENDIF,\n"
    end

    # create program inner body for determining zone cooling needs
    if thermal_zones.include? zone
      determine_zone_heating_needs_prg_inner_body += "IF #{zone_air_sensor_name} < #{zone_htg_thermostat_sensor_name},
                                                      SET Zones_Needing_Heating = Zones_Needing_Heating + 1,
                                                    ENDIF,\n"
    end
  end

  # create program for determining zone cooling needs
  determine_zone_cooling_needs_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
  determine_zone_cooling_needs_prg.setName('Determine_Zone_Cooling_Needs')
  determine_zone_cooling_needs_prg_body =
    "SET Zones_Needing_Cooling = 0,
      #{determine_zone_cooling_needs_prg_inner_body}
    SET Total_Zones = #{thermal_zones.length},
    SET Zone_Cooling_Ratio = Zones_Needing_Cooling/Total_Zones"
  determine_zone_cooling_needs_prg.setBody(determine_zone_cooling_needs_prg_body)

  # create program for determining zone heating needs
  determine_zone_heating_needs_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
  determine_zone_heating_needs_prg.setName('Determine_Zone_Heating_Needs')
  determine_zone_heating_needs_prg_body =
    "SET Zones_Needing_Heating = 0,
      #{determine_zone_heating_needs_prg_inner_body}
    SET Total_Zones = #{thermal_zones.length},
    SET Zone_Heating_Ratio = Zones_Needing_Heating/Total_Zones"
  determine_zone_heating_needs_prg.setBody(determine_zone_heating_needs_prg_body)

  # create EMS program manager objects
  programs_at_beginning_of_timestep = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
  programs_at_beginning_of_timestep.setName('Heating_Cooling_Request_Programs_At_End_Of_Timestep')
  programs_at_beginning_of_timestep.setCallingPoint('EndOfZoneTimestepAfterZoneReporting')
  programs_at_beginning_of_timestep.addProgram(determine_zone_cooling_needs_prg)
  programs_at_beginning_of_timestep.addProgram(determine_zone_heating_needs_prg)
end
model_add_zone_ventilation(model, thermal_zones, ventilation_type: nil, flow_rate: nil, availability_sch_name: nil) click to toggle source

Adds a zone ventilation design flow rate to each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] an array of thermal zones @param ventilation_type [String] the zone ventilation type either Exhaust, Natural, or Intake @param flow_rate [Double] the ventilation design flow rate in m^3/s @param availability_sch_name [String] the name of the fan availability schedule @return [Array<OpenStudio::Model::ZoneVentilationDesignFlowRate>] an array of zone ventilation objects created

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6148
def model_add_zone_ventilation(model,
                               thermal_zones,
                               ventilation_type: nil,
                               flow_rate: nil,
                               availability_sch_name: nil)

  if availability_sch_name.nil?
    availability_schedule = model.alwaysOnDiscreteSchedule
  else
    availability_schedule = model_add_schedule(model, availability_sch_name)
  end

  if flow_rate.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Flow rate nil for zone ventilation.')
  end

  # make a zone ventilation object for each zone
  zone_ventilations = []
  thermal_zones.each do |zone|
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Model.Model', "Adding zone ventilation fan for #{zone.name}.")
    ventilation = OpenStudio::Model::ZoneVentilationDesignFlowRate.new(model)
    ventilation.setName("#{zone.name} Ventilation")
    ventilation.setSchedule(availability_schedule)

    if ventilation_type == 'Exhaust'
      ventilation.setDesignFlowRate(flow_rate)
      ventilation.setFanPressureRise(31.1361206455786)
      ventilation.setFanTotalEfficiency(0.51)
      ventilation.setConstantTermCoefficient(1.0)
      ventilation.setVelocityTermCoefficient(0.0)
      ventilation.setTemperatureTermCoefficient(0.0)
      ventilation.setMinimumIndoorTemperature(29.4444452244559)
      ventilation.setMaximumIndoorTemperature(100.0)
      ventilation.setDeltaTemperature(-100.0)
    elsif ventilation_type == 'Natural'
      ventilation.setDesignFlowRate(flow_rate)
      ventilation.setFanPressureRise(0.0)
      ventilation.setFanTotalEfficiency(1.0)
      ventilation.setConstantTermCoefficient(0.0)
      ventilation.setVelocityTermCoefficient(0.224)
      ventilation.setTemperatureTermCoefficient(0.0)
      ventilation.setMinimumIndoorTemperature(-73.3333352760033)
      ventilation.setMaximumIndoorTemperature(29.4444452244559)
      ventilation.setDeltaTemperature(-100.0)
    elsif ventilation_type == 'Intake'
      ventilation.setFlowRateperZoneFloorArea(flow_rate)
      ventilation.setFanPressureRise(49.8)
      ventilation.setFanTotalEfficiency(0.53625)
      ventilation.setConstantTermCoefficient(1.0)
      ventilation.setVelocityTermCoefficient(0.0)
      ventilation.setTemperatureTermCoefficient(0.0)
      ventilation.setMinimumIndoorTemperature(7.5)
      ventilation.setMaximumIndoorTemperature(35)
      ventilation.setDeltaTemperature(-27.5)
      ventilation.setMinimumOutdoorTemperature(-30.0)
      ventilation.setMaximumOutdoorTemperature(50.0)
      ventilation.setMaximumWindSpeed(6.0)
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "ventilation type #{ventilation_type} invalid for zone ventilation.")
    end
    ventilation.setVentilationType(ventilation_type)
    ventilation.addToThermalZone(zone)
    zone_ventilations << ventilation
  end

  return zone_ventilations
end
model_apply_baseline_exterior_lighting(model) click to toggle source

Apply baseline values to exterior lights objects Only implemented for stable baseline

@param model [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4722
def model_apply_baseline_exterior_lighting(model)
  return false
end
model_apply_hvac_efficiency_standard(model, climate_zone, apply_controls: true, sql_db_vars_map: nil, necb_ref_hp: false) click to toggle source

Applies the HVAC parts of the template to all objects in the model using the the template specified in the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param apply_controls [Boolean] toggle whether to apply air loop and plant loop controls @param sql_db_vars_map [Hash] hash map @param necb_ref_hp [Boolean] for compatability with NECB ruleset only. @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2222
def model_apply_hvac_efficiency_standard(model, climate_zone, apply_controls: true, sql_db_vars_map: nil, necb_ref_hp: false)
  sql_db_vars_map = {} if sql_db_vars_map.nil?

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Started applying HVAC efficiency standards for #{template} template.")

  # Air Loop Controls
  if apply_controls.nil? || apply_controls == true
    model.getAirLoopHVACs.sort.each { |obj| air_loop_hvac_apply_standard_controls(obj, climate_zone) }
  end

  # Plant Loop Controls
  if apply_controls.nil? || apply_controls == true
    model.getPlantLoops.sort.each { |obj| plant_loop_apply_standard_controls(obj, climate_zone) }
  end

  # Zone HVAC Controls
  model.getZoneHVACComponents.sort.each { |obj| zone_hvac_component_apply_standard_controls(obj) }

  ##### Apply equipment efficiencies

  # Fans
  model.getFanVariableVolumes.sort.each { |obj| fan_apply_standard_minimum_motor_efficiency(obj, fan_brake_horsepower(obj)) }
  model.getFanConstantVolumes.sort.each { |obj| fan_apply_standard_minimum_motor_efficiency(obj, fan_brake_horsepower(obj)) }
  model.getFanOnOffs.sort.each { |obj| fan_apply_standard_minimum_motor_efficiency(obj, fan_brake_horsepower(obj)) }
  model.getFanZoneExhausts.sort.each { |obj| fan_apply_standard_minimum_motor_efficiency(obj, fan_brake_horsepower(obj)) }

  # Pumps
  model.getPumpConstantSpeeds.sort.each { |obj| pump_apply_standard_minimum_motor_efficiency(obj) }
  model.getPumpVariableSpeeds.sort.each { |obj| pump_apply_standard_minimum_motor_efficiency(obj) }
  model.getHeaderedPumpsConstantSpeeds.sort.each { |obj| pump_apply_standard_minimum_motor_efficiency(obj) }
  model.getHeaderedPumpsVariableSpeeds.sort.each { |obj| pump_apply_standard_minimum_motor_efficiency(obj) }

  # Unitary HPs
  # set DX HP coils before DX clg coils because when DX HP coils need to first
  # pull the capacities of their paired DX clg coils, and this does not work
  # correctly if the DX clg coil efficiencies have been set because they are renamed.
  model.getCoilHeatingDXSingleSpeeds.sort.each { |obj| sql_db_vars_map = coil_heating_dx_single_speed_apply_efficiency_and_curves(obj, sql_db_vars_map, necb_ref_hp) }

  # Unitary ACs
  model.getCoilCoolingDXTwoSpeeds.sort.each { |obj| sql_db_vars_map = coil_cooling_dx_two_speed_apply_efficiency_and_curves(obj, sql_db_vars_map) }
  model.getCoilCoolingDXSingleSpeeds.sort.each { |obj| sql_db_vars_map = coil_cooling_dx_single_speed_apply_efficiency_and_curves(obj, sql_db_vars_map, necb_ref_hp) }
  model.getCoilCoolingDXMultiSpeeds.sort.each { |obj| sql_db_vars_map = coil_cooling_dx_multi_speed_apply_efficiency_and_curves(obj, sql_db_vars_map) }

  # WSHPs
  # set WSHP heating coils before cooling coils to get cooling coil capacities before they are renamed
  model.getCoilHeatingWaterToAirHeatPumpEquationFits.sort.each { |obj| sql_db_vars_map = coil_heating_water_to_air_heat_pump_apply_efficiency_and_curves(obj, sql_db_vars_map) }
  model.getCoilCoolingWaterToAirHeatPumpEquationFits.sort.each { |obj| sql_db_vars_map = coil_cooling_water_to_air_heat_pump_apply_efficiency_and_curves(obj, sql_db_vars_map) }

  # Chillers
  clg_tower_objs = model.getCoolingTowerSingleSpeeds
  model.getChillerElectricEIRs.sort.each { |obj| chiller_electric_eir_apply_efficiency_and_curves(obj, clg_tower_objs) }

  # Boilers
  model.getBoilerHotWaters.sort.each { |obj| boiler_hot_water_apply_efficiency_and_curves(obj) }

  # Water Heaters
  model.getWaterHeaterMixeds.sort.each { |obj| water_heater_mixed_apply_efficiency(obj) }

  # Cooling Towers
  model.getCoolingTowerSingleSpeeds.sort.each { |obj| cooling_tower_single_speed_apply_efficiency_and_curves(obj) }
  model.getCoolingTowerTwoSpeeds.sort.each { |obj| cooling_tower_two_speed_apply_efficiency_and_curves(obj) }
  model.getCoolingTowerVariableSpeeds.sort.each { |obj| cooling_tower_variable_speed_apply_efficiency_and_curves(obj) }

  # Fluid Coolers
  model.getFluidCoolerSingleSpeeds.sort.each { |obj| fluid_cooler_apply_minimum_power_per_flow(obj, equipment_type: 'Dry Cooler') }
  model.getFluidCoolerTwoSpeeds.sort.each { |obj| fluid_cooler_apply_minimum_power_per_flow(obj, equipment_type: 'Dry Cooler') }
  model.getEvaporativeFluidCoolerSingleSpeeds.sort.each { |obj| fluid_cooler_apply_minimum_power_per_flow(obj, equipment_type: 'Closed Cooling Tower') }
  model.getEvaporativeFluidCoolerTwoSpeeds.sort.each { |obj| fluid_cooler_apply_minimum_power_per_flow(obj, equipment_type: 'Closed Cooling Tower') }

  # ERVs
  model.getHeatExchangerAirToAirSensibleAndLatents.each { |obj| heat_exchanger_air_to_air_sensible_and_latent_apply_effectiveness(obj) }

  # Gas Heaters
  model.getCoilHeatingGass.sort.each { |obj| coil_heating_gas_apply_efficiency_and_curves(obj) }
  model.getCoilHeatingGasMultiStages.each { |obj| coil_heating_gas_multi_stage_apply_efficiency_and_curves(obj) }

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Finished applying HVAC efficiency standards for #{template} template.")
  return true
end
model_apply_infiltration_standard(model) click to toggle source

Apply the air leakage requirements to the model, as described in PNNL section 5.2.1.6. This method creates customized infiltration objects for each space and removes the SpaceType-level infiltration objects.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not @todo This infiltration method is not used by the Reference buildings, fix this inconsistency.

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2332
def model_apply_infiltration_standard(model)
  # Set the infiltration rate at each space
  model.getSpaces.sort.each do |space|
    space_apply_infiltration_rate(space)
  end

  # Remove infiltration rates set at the space type
  model.getSpaceTypes.sort.each do |space_type|
    space_type.spaceInfiltrationDesignFlowRates.each(&:remove)
  end

  return true
end
model_apply_multizone_vav_outdoor_air_sizing(model) click to toggle source

Applies the multi-zone VAV outdoor air sizing requirements to all applicable air loops in the model. @note This must be performed before the sizing run because it impacts component sizes, which in turn impact efficiencies.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2205
def model_apply_multizone_vav_outdoor_air_sizing(model)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Started applying multizone vav OA sizing.')

  # Multi-zone VAV outdoor air sizing
  model.getAirLoopHVACs.sort.each { |obj| air_loop_hvac_apply_multizone_vav_outdoor_air_sizing(obj) }

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Finished applying multizone vav OA sizing.')
end
model_apply_prm_baseline_sizing_schedule(model) click to toggle source

Add design day schedule objects for space loads, not used for 2013 and earlier @author Xuechen (Jerry) Lei, PNNL @param model [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/standards/Standards.Model.rb, line 732
def model_apply_prm_baseline_sizing_schedule(model)
  return true
end
model_apply_prm_baseline_skylight_to_roof_ratio(model) click to toggle source

Reduces the SRR to the values specified by the PRM. SRR reduction will be done by shrinking vertices toward the centroid.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not @todo support semiheated spaces as a separate SRR category @todo add skylight frame area to calculation of SRR

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4579
def model_apply_prm_baseline_skylight_to_roof_ratio(model)
  # Loop through all spaces in the model, and
  # per the PNNL PRM Reference Manual, find the areas
  # of each space conditioning category (res, nonres, semi-heated)
  # separately.  Include space multipliers.
  nr_wall_m2 = 0.001 # Avoids divide by zero errors later
  nr_sky_m2 = 0
  res_wall_m2 = 0.001
  res_sky_m2 = 0
  sh_wall_m2 = 0.001
  sh_sky_m2 = 0
  total_roof_m2 = 0.001
  total_subsurface_m2 = 0
  model.getSpaces.sort.each do |space|
    # Loop through all surfaces in this space
    wall_area_m2 = 0
    sky_area_m2 = 0
    space.surfaces.sort.each do |surface|
      # Skip non-outdoor surfaces
      next unless surface.outsideBoundaryCondition == 'Outdoors'
      # Skip non-walls
      next unless surface.surfaceType == 'RoofCeiling'

      # This wall's gross area (including skylight area)
      wall_area_m2 += surface.grossArea * space.multiplier
      # Subsurfaces in this surface
      surface.subSurfaces.sort.each do |ss|
        next unless ss.subSurfaceType == 'Skylight'

        sky_area_m2 += ss.netArea * space.multiplier
      end
    end

    # Determine the space category
    cat = 'NonRes'
    if OpenstudioStandards::Space.space_residential?(space)
      cat = 'Res'
    end
    # if space.is_semiheated
    # cat = 'Semiheated'
    # end

    # Add to the correct category
    case cat
      when 'NonRes'
        nr_wall_m2 += wall_area_m2
        nr_sky_m2 += sky_area_m2
      when 'Res'
        res_wall_m2 += wall_area_m2
        res_sky_m2 += sky_area_m2
      when 'Semiheated'
        sh_wall_m2 += wall_area_m2
        sh_sky_m2 += sky_area_m2
    end
    total_roof_m2 += wall_area_m2
    total_subsurface_m2 += sky_area_m2
  end

  # Calculate the SRR of each category
  srr_nr = ((nr_sky_m2 / nr_wall_m2) * 100).round(1)
  srr_res = ((res_sky_m2 / res_wall_m2) * 100).round(1)
  srr_sh = ((sh_sky_m2 / sh_wall_m2) * 100).round(1)
  srr = ((total_subsurface_m2 / total_roof_m2) * 100.0).round(1)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "The skylight to roof ratios (SRRs) are: NonRes: #{srr_nr.round}%, Res: #{srr_res.round}%.")

  # SRR limit
  srr_lim = model_prm_skylight_to_roof_ratio_limit(model)

  # Check against SRR limit
  red_nr = srr_nr > srr_lim
  red_res = srr_res > srr_lim
  red_sh = srr_sh > srr_lim

  # Stop here unless skylights need reducing
  return true unless red_nr || red_res || red_sh

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Reducing the size of all skylights equally down to the limit of #{srr_lim.round}%.")

  # Determine the factors by which to reduce the skylight area
  mult_nr_red = srr_lim / srr_nr
  mult_res_red = srr_lim / srr_res
  # mult_sh_red = srr_lim / srr_sh

  # Reduce the skylight area if any of the categories necessary
  model.getSpaces.sort.each do |space|
    # Determine the space category
    cat = 'NonRes'
    if OpenstudioStandards::Space.space_residential?(space)
      cat = 'Res'
    end
    # if space.is_semiheated
    # cat = 'Semiheated'
    # end

    # Skip spaces whose skylights don't need to be reduced
    case cat
      when 'NonRes'
        next unless red_nr

        mult = mult_nr_red
      when 'Res'
        next unless red_res

        mult = mult_res_red
      when 'Semiheated'
        next unless red_sh
      # mult = mult_sh_red
    end

    # Loop through all surfaces in this space
    space.surfaces.sort.each do |surface|
      # Skip non-outdoor surfaces
      next unless surface.outsideBoundaryCondition == 'Outdoors'
      # Skip non-walls
      next unless surface.surfaceType == 'RoofCeiling'

      # Subsurfaces in this surface
      surface.subSurfaces.sort.each do |ss|
        next unless ss.subSurfaceType == 'Skylight'

        # Reduce the size of the skylight
        red = 1.0 - mult
        OpenstudioStandards::Geometry.sub_surface_reduce_area_by_percent_by_shrinking_toward_centroid(ss, red)
      end
    end
  end

  return true
end
model_apply_prm_baseline_window_to_wall_ratio(model, climate_zone, wwr_building_type: nil) click to toggle source

Reduces the WWR to the values specified by the PRM. WWR reduction will be done by moving vertices inward toward centroid. This causes the least impact on the daylighting area calculations and controls placement.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not @todo add proper support for 90.1-2013 with all those building type specific values @todo support 90.1-2004 requirement that windows be modeled as horizontal bands.

Currently just using existing window geometry, and shrinking as necessary if WWR is above limit.

@todo support semiheated spaces as a separate WWR category @todo add window frame area to calculation of WWR

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4296
def model_apply_prm_baseline_window_to_wall_ratio(model, climate_zone, wwr_building_type: nil)
  # Define a Hash that will contain wall and window area for all
  # building area types included in the model
  # bat = building area type
  bat_win_wall_info = {}

  # Store the baseline wwr, only used for 90.1-PRM-2019,
  # it is necessary for looking up baseline fenestration
  # U-factor and SHGC requirements
  base_wwr = {}

  # Store the space conditioning category for later use
  space_cats = {}

  model.getSpaces.sort.each do |space|
    # Get standards space type and
    # catch spaces without space types
    #
    # Currently, priority is given to the wwr_building_type,
    # meaning that only one building area type is used. The
    # method can however handle models with multiple building
    # area type, if they are specified through each space's
    # space type standards building type.
    if space.hasAdditionalProperties && space.additionalProperties.hasFeature('building_type_for_wwr')
      std_spc_type = space.additionalProperties.getFeatureAsString('building_type_for_wwr').get
    else
      std_spc_type = 'no_space_type'
      if !wwr_building_type.nil?
        std_spc_type = wwr_building_type
      elsif space.spaceType.is_initialized
        std_spc_type = space.spaceType.get.standardsBuildingType.to_s
      end
      # insert space wwr type as additional properties for later search
      space.additionalProperties.setFeature('building_type_for_wwr', std_spc_type)
    end

    # Initialize intermediate variables if space type hasn't
    # been encountered yet
    if !bat_win_wall_info.key?(std_spc_type)
      bat_win_wall_info[std_spc_type] = {}
      bat = bat_win_wall_info[std_spc_type]

      # Loop through all spaces in the model, and
      # per the PNNL PRM Reference Manual, find the areas
      # of each space conditioning category (res, nonres, semi-heated)
      # separately.  Include space multipliers.
      bat.store('nr_wall_m2', 0.001) # Avoids divide by zero errors later
      bat.store('nr_fene_only_wall_m2', 0.001)
      bat.store('nr_plenum_wall_m2', 0.001)
      bat.store('nr_wind_m2', 0)
      bat.store('res_wall_m2', 0.001)
      bat.store('res_fene_only_wall_m2', 0.001)
      bat.store('res_wind_m2', 0)
      bat.store('res_plenum_wall_m2', 0.001)
      bat.store('sh_wall_m2', 0.001)
      bat.store('sh_fene_only_wall_m2', 0.001)
      bat.store('sh_wind_m2', 0)
      bat.store('sh_plenum_wall_m2', 0.001)
      bat.store('total_wall_m2', 0.001)
      bat.store('total_plenum_m2', 0.001)
    else
      bat = bat_win_wall_info[std_spc_type]
    end

    # Loop through all surfaces in this space
    wall_area_m2 = 0
    wind_area_m2 = 0
    # save wall area from walls that have fenestrations (subsurfaces)
    wall_only_area_m2 = 0
    space.surfaces.sort.each do |surface|
      # Skip non-outdoor surfaces
      next unless surface.outsideBoundaryCondition == 'Outdoors'
      # Skip non-walls
      next unless surface.surfaceType.casecmp('wall').zero?

      # This wall's gross area (including window area)
      wall_area_m2 += surface.grossArea * space.multiplier
      unless surface.subSurfaces.empty?
        # Subsurfaces in this surface
        surface.subSurfaces.sort.each do |ss|
          next unless ss.subSurfaceType == 'FixedWindow' || ss.subSurfaceType == 'OperableWindow' || ss.subSurfaceType == 'GlassDoor'

          # Only add wall surfaces when the wall actually have windows
          wind_area_m2 += ss.netArea * space.multiplier
        end
      end
      if wind_area_m2 > 0.0
        wall_only_area_m2 += surface.grossArea * space.multiplier
      end
    end

    # Determine the space category
    if model_create_prm_baseline_building_requires_proposed_model_sizing_run(model)
      # For PRM 90.1-2019 and onward, determine space category
      # based on sizing run results
      cat = space_conditioning_category(space)
    else
      # @todo This should really use the heating/cooling loads from the proposed building.
      # However, in an attempt to avoid another sizing run just for this purpose,
      # conditioned status is based on heating/cooling setpoints.
      # If heated-only, will be assumed Semiheated.
      # The full-bore method is on the next line in case needed.
      # cat = thermal_zone_conditioning_category(space, template, climate_zone)
      cooled = OpenstudioStandards::Space.space_cooled?(space)
      heated = OpenstudioStandards::Space.space_heated?(space)
      cat = 'Unconditioned'
      # Unconditioned
      if !heated && !cooled
        cat = 'Unconditioned'
        # Heated-Only
      elsif heated && !cooled
        cat = 'Semiheated'
        # Heated and Cooled
      else
        res = OpenstudioStandards::Space.space_residential?(space)
        cat = if res
                'ResConditioned'
              else
                'NonResConditioned'
              end
      end
    end
    space_cats[space] = cat

    # Add to the correct category is_space_plenum?
    case cat
      when 'Unconditioned'
        next # Skip unconditioned spaces
      when 'NonResConditioned'
        space_is_plenum(space) ? bat['nr_plenum_wall_m2'] += wall_area_m2 : bat['nr_plenum_wall_m2'] += 0.0
        bat['nr_wall_m2'] += wall_area_m2
        bat['nr_fene_only_wall_m2'] += wall_only_area_m2
        bat['nr_wind_m2'] += wind_area_m2
      when 'ResConditioned'
        space_is_plenum(space) ? bat['res_plenum_wall_m2'] += wall_area_m2 : bat['res_plenum_wall_m2'] += 0.0
        bat['res_wall_m2'] += wall_area_m2
        bat['res_fene_only_wall_m2'] += wall_only_area_m2
        bat['res_wind_m2'] += wind_area_m2
      when 'Semiheated'
        space_is_plenum(space) ? bat['sh_plenum_wall_m2'] += wall_area_m2 : bat['sh_plenum_wall_m2'] += 0.0
        bat['sh_wall_m2'] += wall_area_m2
        bat['sh_fene_only_wall_m2'] += wall_only_area_m2
        bat['sh_wind_m2'] += wind_area_m2
    end
  end

  # Retrieve WWR info for all Building Area Types included in the model
  # and perform adjustements if
  # bat = building area type
  bat_win_wall_info.each do |bat, vals|
    # Calculate the WWR of each category
    vals.store('wwr_nr', ((vals['nr_wind_m2'] / vals['nr_wall_m2']) * 100.0).round(1))
    vals.store('wwr_res', ((vals['res_wind_m2'] / vals['res_wall_m2']) * 100).round(1))
    vals.store('wwr_sh', ((vals['sh_wind_m2'] / vals['sh_wall_m2']) * 100).round(1))

    # Convert to IP and report
    vals.store('nr_wind_ft2', OpenStudio.convert(vals['nr_wind_m2'], 'm^2', 'ft^2').get)
    vals.store('nr_wall_ft2', OpenStudio.convert(vals['nr_wall_m2'], 'm^2', 'ft^2').get)

    vals.store('res_wind_ft2', OpenStudio.convert(vals['res_wind_m2'], 'm^2', 'ft^2').get)
    vals.store('res_wall_ft2', OpenStudio.convert(vals['res_wall_m2'], 'm^2', 'ft^2').get)

    vals.store('sh_wind_ft2', OpenStudio.convert(vals['sh_wind_m2'], 'm^2', 'ft^2').get)
    vals.store('sh_wall_ft2', OpenStudio.convert(vals['sh_wall_m2'], 'm^2', 'ft^2').get)

    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "WWR NonRes = #{vals['wwr_nr'].round}%; window = #{vals['nr_wind_ft2'].round} ft2, wall = #{vals['nr_wall_ft2'].round} ft2.")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "WWR Res = #{vals['wwr_res'].round}%; window = #{vals['res_wind_ft2'].round} ft2, wall = #{vals['res_wall_ft2'].round} ft2.")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "WWR Semiheated = #{vals['wwr_sh'].round}%; window = #{vals['sh_wind_ft2'].round} ft2, wall = #{vals['sh_wall_ft2'].round} ft2.")

    # WWR limit or target
    wwr_lim = model_get_bat_wwr_target(bat, [vals['wwr_nr'], vals['wwr_res'], vals['wwr_sh']])

    # Check against WWR limit
    vals['red_nr'] = vals['wwr_nr'] > wwr_lim
    vals['red_res'] = vals['wwr_res'] > wwr_lim
    vals['red_sh'] = vals['wwr_sh'] > wwr_lim

    # Stop here unless windows need reducing or increasing
    return true, base_wwr unless model_does_require_wwr_adjustment?(wwr_lim, [vals['wwr_nr'], vals['wwr_res'], vals['wwr_sh']])

    # Determine the factors by which to reduce the window area
    vals['mult_nr_red'] = wwr_lim / vals['wwr_nr']
    vals['mult_res_red'] = wwr_lim / vals['wwr_res']
    vals['mult_sh_red'] = wwr_lim / vals['wwr_sh']

    # Report baseline WWR
    vals['wwr_nr'] *= vals['mult_nr_red']
    vals['wwr_res'] *= vals['mult_res_red']
    vals['wwr_sh'] *= vals['mult_sh_red']
    wwrs = [vals['wwr_nr'], vals['wwr_res'], vals['wwr_sh']]
    max_wwrs = []
    wwrs.each do |w|
      max_wwrs << w unless w.nan?
    end
    base_wwr[bat] = max_wwrs.max

    # Reduce the window area if any of the categories necessary
    model.getSpaces.sort.each do |space|
      # Catch spaces without space types
      std_spc_type = space.additionalProperties.getFeatureAsString('building_type_for_wwr').get
      # skip process the space unless the space wwr type matched.
      next unless bat == std_spc_type
      # supply and return plenum is now conditioned space but should be excluded from window adjustment
      next if space_is_plenum(space)

      # Determine the space category
      # from the previously stored values
      cat = space_cats[space]

      # Get the correct multiplier
      case cat
        when 'Unconditioned'
          next # Skip unconditioned spaces
        when 'NonResConditioned'
          mult = vals['mult_nr_red']
          total_wall_area = vals['nr_wall_m2']
          total_wall_with_fene_area = vals['nr_fene_only_wall_m2']
          total_plenum_wall_area = vals['nr_plenum_wall_m2']
          total_fene_area = vals['nr_wind_m2']
        when 'ResConditioned'
          mult = vals['mult_res_red']
          total_wall_area = vals['res_wall_m2']
          total_wall_with_fene_area = vals['res_fene_only_wall_m2']
          total_plenum_wall_area = vals['res_plenum_wall_m2']
          total_fene_area = vals['res_wind_m2']
        when 'Semiheated'
          mult = vals['mult_sh_red']
          total_wall_area = vals['sh_wall_m2']
          total_wall_with_fene_area = vals['sh_fene_only_wall_m2']
          total_plenum_wall_area = vals['sh_plenum_wall_m2']
          total_fene_area = vals['sh_wind_m2']
      end

      # used for counting how many window area is left for doors
      residual_fene = 0.0
      # Loop through all surfaces in this space
      space.surfaces.sort.each do |surface|
        # Skip non-outdoor surfaces
        next unless surface.outsideBoundaryCondition == 'Outdoors'
        # Skip non-walls
        next unless surface.surfaceType.casecmp('wall').zero?

        # Reduce the size of the window
        # If a vertical rectangle, raise sill height to avoid
        # impacting daylighting areas, otherwise
        # reduce toward centroid.
        #
        # daylighting control isn't modeled
        red = surface_get_wwr_reduction_ratio(mult,
                                              surface,
                                              wwr_building_type: bat,
                                              wwr_target: wwr_lim / 100, # divide by 100 to revise it to decimals
                                              total_wall_m2: total_wall_area,
                                              total_wall_with_fene_m2: total_wall_with_fene_area,
                                              total_fene_m2: total_fene_area,
                                              total_plenum_wall_m2: total_plenum_wall_area)

        if red < 0.0
          # surface with fenestration to its maximum but adjusted by door areas when need to add windows in surfaces no fenestration
          # turn negative to positive to get the correct adjustment factor.
          red = -red
          surface_wwr = OpenstudioStandards::Geometry.surface_get_window_to_wall_ratio(surface)
          residual_fene += (0.9 - red * surface_wwr) * surface.grossArea
        end
        surface_adjust_fenestration_in_a_surface(surface, red, model)
      end

      if residual_fene > 0.0
        residual_ratio = residual_fene / (total_wall_area - total_wall_with_fene_area)
        model_readjust_surface_wwr(residual_ratio, space, model)
      end
    end
  end

  return true, base_wwr
end
model_apply_prm_construction_types(model) click to toggle source

Go through the default construction sets and hard-assigned constructions. Clone the existing constructions and set their intended surface type and standards construction type per the PRM. For some standards, this will involve making modifications. For others, it will not.

90.1-2007, 90.1-2010, 90.1-2013 @param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4063
def model_apply_prm_construction_types(model)
  types_to_modify = []

  # Possible boundary conditions are
  # Adiabatic
  # Surface
  # Outdoors
  # Ground

  # Possible surface types are
  # AtticFloor
  # AtticWall
  # AtticRoof
  # DemisingFloor
  # DemisingWall
  # DemisingRoof
  # ExteriorFloor
  # ExteriorWall
  # ExteriorRoof
  # ExteriorWindow
  # ExteriorDoor
  # GlassDoor
  # GroundContactFloor
  # GroundContactWall
  # GroundContactRoof
  # InteriorFloor
  # InteriorWall
  # InteriorCeiling
  # InteriorPartition
  # InteriorWindow
  # InteriorDoor
  # OverheadDoor
  # Skylight
  # TubularDaylightDome
  # TubularDaylightDiffuser

  # Possible standards construction types
  # Mass
  # SteelFramed
  # WoodFramed
  # IEAD
  # View
  # Daylight
  # Swinging
  # NonSwinging
  # Heated
  # Unheated
  # RollUp
  # Sliding
  # Metal
  # Nonmetal framing (all)
  # Metal framing (curtainwall/storefront)
  # Metal framing (entrance door)
  # Metal framing (all other)
  # Metal Building
  # Attic and Other
  # Glass with Curb
  # Plastic with Curb
  # Without Curb

  # Create an array of types
  types_to_modify << ['Outdoors', 'ExteriorWall', 'SteelFramed']
  types_to_modify << ['Outdoors', 'ExteriorRoof', 'IEAD']
  types_to_modify << ['Outdoors', 'ExteriorFloor', 'SteelFramed']
  types_to_modify << ['Ground', 'GroundContactFloor', 'Unheated']
  types_to_modify << ['Ground', 'GroundContactWall', 'Mass']

  # Modify all constructions of each type
  types_to_modify.each do |boundary_cond, surf_type, const_type|
    constructions = OpenstudioStandards::Constructions.model_get_constructions(model, boundary_cond, surf_type)

    constructions.sort.each do |const|
      standards_info = const.standardsInformation
      standards_info.setIntendedSurfaceType(surf_type)
      standards_info.setStandardsConstructionType(const_type)
    end
  end

  return true
end
model_apply_prm_sizing_parameters(model) click to toggle source

Changes the sizing parameters to the PRM specifications.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4835
def model_apply_prm_sizing_parameters(model)
  clg = 1.15
  htg = 1.25

  sizing_params = model.getSizingParameters
  sizing_params.setHeatingSizingFactor(htg)
  sizing_params.setCoolingSizingFactor(clg)

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.Model', "Set sizing factors to #{htg} for heating and #{clg} for cooling.")
  return true
end
model_apply_standard_constructions(model, climate_zone, wwr_building_type: nil, wwr_info: {}) click to toggle source

Apply the standard construction to each surface in the model, based on the construction type currently assigned.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4149
def model_apply_standard_constructions(model, climate_zone, wwr_building_type: nil, wwr_info: {})
  types_to_modify = []

  # Possible boundary conditions are
  # Adiabatic
  # Surface
  # Outdoors
  # Ground

  # Possible surface types are
  # Floor
  # Wall
  # RoofCeiling
  # FixedWindow
  # OperableWindow
  # Door
  # GlassDoor
  # OverheadDoor
  # Skylight
  # TubularDaylightDome
  # TubularDaylightDiffuser

  # Create an array of surface types
  types_to_modify << ['Outdoors', 'Floor']
  types_to_modify << ['Outdoors', 'Wall']
  types_to_modify << ['Outdoors', 'RoofCeiling']
  types_to_modify << ['Outdoors', 'FixedWindow']
  types_to_modify << ['Outdoors', 'OperableWindow']
  types_to_modify << ['Outdoors', 'Door']
  types_to_modify << ['Outdoors', 'GlassDoor']
  types_to_modify << ['Outdoors', 'OverheadDoor']
  types_to_modify << ['Outdoors', 'Skylight']
  types_to_modify << ['Ground', 'Floor']
  types_to_modify << ['Ground', 'Wall']

  # Find just those surfaces
  surfaces_to_modify = []
  surface_category = {}
  types_to_modify.each do |boundary_condition, surface_type|
    # Surfaces
    model.getSurfaces.sort.each do |surf|
      next unless surf.outsideBoundaryCondition == boundary_condition
      next unless surf.surfaceType == surface_type

      if boundary_condition == 'Outdoors'
        surface_category[surf] = 'ExteriorSurface'
      elsif boundary_condition == 'Ground'
        surface_category[surf] = 'GroundSurface'
      else
        surface_category[surf] = 'NA'
      end
      surfaces_to_modify << surf
    end

    # SubSurfaces
    model.getSubSurfaces.sort.each do |surf|
      next unless surf.outsideBoundaryCondition == boundary_condition
      next unless surf.subSurfaceType == surface_type

      surface_category[surf] = 'ExteriorSubSurface'
      surfaces_to_modify << surf
    end
  end

  # Modify these surfaces
  prev_created_consts = {}
  surfaces_to_modify.sort.each do |surf|
    prev_created_consts = planar_surface_apply_standard_construction(surf, climate_zone, prev_created_consts, wwr_building_type, wwr_info, surface_category[surf])
  end

  # List the unique array of constructions
  if prev_created_consts.size.zero?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', 'None of the constructions in your proposed model have both Intended Surface Type and Standards Construction Type')
  else
    prev_created_consts.each do |surf_type, construction|
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For #{surf_type.join(' ')}, applied #{construction.name}.")
    end
  end

  return true
end
model_apply_standard_infiltration(model, specific_space_infiltration_rate_75_pa = nil) click to toggle source

For backward compatibility, infiltration standard not used for 2013 and earlier

@return [Boolean] true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2321
def model_apply_standard_infiltration(model, specific_space_infiltration_rate_75_pa = nil)
  return true
end
model_attach_water_fixtures_to_spaces?(model) click to toggle source

Determine whether or not water fixtures are attached to spaces @todo For hotels and apartments, add the water fixture at the space level @param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.ServiceWaterHeating.rb, line 1079
def model_attach_water_fixtures_to_spaces?(model)
  # if building_type!=nil && ((building_type.downcase.include?"hotel") || (building_type.downcase.include?"apartment"))
  #   return true
  # end
  return false
end
model_baseline_system_vav_fan_type(model) click to toggle source

Determines the fan type used by VAV_Reheat and VAV_PFP_Boxes systems. Defaults to two speed fan.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [String] the fan type: TwoSpeed Fan, Variable Speed Fan

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1880
def model_baseline_system_vav_fan_type(model)
  fan_type = 'TwoSpeed Fan'
  return fan_type
end
model_create_exterior_lighting_area_length_count_hash(model, space_type_hash, use_model_for_entries_and_canopies) click to toggle source

get exterior lighting areas, distances, and counts

@param model [OpenStudio::Model::Model] OpenStudio model object @param space_type_hash [Hash] hash of space types @param use_model_for_entries_and_canopies [Boolean] use building geometry for number of entries and canopy size @return [Hhash] hash of exterior lighting value types and building type and model specific values @todo add code in to determine number of entries and canopy area from model geoemtry @todo come up with better logic for entry widths

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.exterior_lights.rb, line 293
def model_create_exterior_lighting_area_length_count_hash(model, space_type_hash, use_model_for_entries_and_canopies)
  # populate building_type_hashes from space_type_hash
  building_type_hashes = {}
  space_type_hash.each do |space_type, hash|
    # if space type standards building type already exists,
    # add data to that standards building type in building_type_hashes
    if building_type_hashes.key?(hash[:stds_bldg_type])
      building_type_hashes[hash[:stds_bldg_type]][:effective_num_spaces] += hash[:effective_num_spaces]
      building_type_hashes[hash[:stds_bldg_type]][:floor_area] += hash[:floor_area]
      building_type_hashes[hash[:stds_bldg_type]][:num_people] += hash[:num_people]
      building_type_hashes[hash[:stds_bldg_type]][:num_students] += hash[:num_students]
      building_type_hashes[hash[:stds_bldg_type]][:num_units] += hash[:num_units]
      building_type_hashes[hash[:stds_bldg_type]][:num_beds] += hash[:num_beds]
    else
      # initialize hash for this building type
      building_type_hash = {}
      building_type_hash[:effective_num_spaces] = hash[:effective_num_spaces]
      building_type_hash[:floor_area] = hash[:floor_area]
      building_type_hash[:num_people] = hash[:num_people]
      building_type_hash[:num_students] = hash[:num_students]
      building_type_hash[:num_units] = hash[:num_units]
      building_type_hash[:num_beds] = hash[:num_beds]
      building_type_hashes[hash[:stds_bldg_type]] = building_type_hash
    end
  end

  # rename Office to SmallOffice, MediumOffice or LargeOffice depending on size
  if building_type_hashes.key?('Office')
    office_type = model_remap_office(model, building_type_hashes['Office'][:floor_area])
    building_type_hashes[office_type] = building_type_hashes.delete('Office')
  end

  # initialize parking areas and drives area variables
  parking_area_and_drives_area = 0.0
  main_entries = 0.0
  other_doors = 0.0
  drive_through_windows = 0.0
  canopy_entry_area = 0.0
  canopy_emergency_area = 0.0

  # calculate exterior lighting properties for each building type
  building_type_hashes.each do |building_type, hash|
    # calculate floor area and ground floor area in IP units
    floor_area_ip = OpenStudio.convert(hash[:floor_area], 'm^2', 'ft^2').get
    effective_num_stories = model_effective_num_stories(model)
    ground_floor_area_ip = floor_area_ip / effective_num_stories[:above_grade]

    # load illuminated parking area properties for standards building type
    search_criteria = { 'building_type' => building_type }
    illuminated_parking_area_lookup = standards_lookup_table_first(table_name: 'parking', search_criteria: search_criteria)
    if illuminated_parking_area_lookup.nil?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.prototype.exterior_lights', "Could not find parking data for #{building_type}.")
      return {} # empty hash
    end

    # calculate number of parking spots
    num_spots = 0.0
    if !illuminated_parking_area_lookup['building_area_per_spot'].nil?
      num_spots += floor_area_ip / illuminated_parking_area_lookup['building_area_per_spot'].to_f
    elsif !illuminated_parking_area_lookup['units_per_spot'].nil?
      num_spots += hash[:num_units] / illuminated_parking_area_lookup['units_per_spot'].to_f
    elsif !illuminated_parking_area_lookup['students_per_spot'].nil?
      num_spots += hash[:num_students] / illuminated_parking_area_lookup['students_per_spot'].to_f
    elsif !illuminated_parking_area_lookup['beds_per_spot'].nil?
      num_spots += hash[:num_beds] / illuminated_parking_area_lookup['beds_per_spot'].to_f
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.prototype.exterior_lights', "Unexpected key, can't calculate number of parking spots from #{illuminated_parking_area_lookup.keys.first}.")
    end
    # add to cumulative parking area
    parking_area_and_drives_area += num_spots * illuminated_parking_area_lookup['parking_area_per_spot']

    # load entryways data for standards building type
    search_criteria = { 'building_type' => building_type }
    exterior_lighting_assumptions_lookup = standards_lookup_table_first(table_name: 'entryways', search_criteria: search_criteria)

    if exterior_lighting_assumptions_lookup.nil?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.prototype.exterior_lights', "Could not find entryway data for #{building_type}.")
      return {} # empty hash
    end

    # calculate door, window, and canopy length properties for exterior lighting
    if use_model_for_entries_and_canopies
      # @todo get number of entries and canopy size from model geometry
    else

      # main entries
      main_entries = (ground_floor_area_ip / 10_000.0) * exterior_lighting_assumptions_lookup['entrance_doors_per_10,000']

      # other doors
      other_doors += (ground_floor_area_ip / 10_000.0) * exterior_lighting_assumptions_lookup['others_doors_per_10,000']

      # drive through windows
      unless exterior_lighting_assumptions_lookup['floor_area_per_drive_through_window'].nil?
        drive_through_windows += ground_floor_area_ip / exterior_lighting_assumptions_lookup['floor_area_per_drive_through_window'].to_f
      end

      # rollup doors are currently excluded

      # entrance canopies
      if !exterior_lighting_assumptions_lookup['entrance_canopies'].nil? && !exterior_lighting_assumptions_lookup['canopy_size'].nil?
        canopy_entry_area = exterior_lighting_assumptions_lookup['entrance_canopies'] * exterior_lighting_assumptions_lookup['canopy_size']
      end

      # emergency canopies
      if !exterior_lighting_assumptions_lookup['emergency_canopies'].nil? && !exterior_lighting_assumptions_lookup['canopy_size'].nil?
        canopy_emergency_area = exterior_lighting_assumptions_lookup['emergency_canopies'] * exterior_lighting_assumptions_lookup['canopy_size']
      end
    end
  end

  # no source for width of different entry types
  main_entry_width_ip = 8 # ft
  other_doors_width_ip = 4 # ft

  # ensure the building has at least 1 main entry
  main_entries = 1.0 if main_entries > 0 && main_entries < 1

  # populate hash
  area_length_count_hash = {}
  area_length_count_hash[:parking_area_and_drives_area] = parking_area_and_drives_area
  area_length_count_hash[:main_entries] = main_entries * main_entry_width_ip
  area_length_count_hash[:other_doors] = other_doors * other_doors_width_ip
  area_length_count_hash[:drive_through_windows] = drive_through_windows
  area_length_count_hash[:canopy_entry_area] = canopy_entry_area
  area_length_count_hash[:canopy_emergency_area] = canopy_emergency_area

  # determine effective number of stories to find first above grade story exterior wall area
  effective_num_stories = model_effective_num_stories(model)
  ground_story = effective_num_stories[:story_hash].keys[effective_num_stories[:below_grade]]
  ground_story_ext_wall_area_si = effective_num_stories[:story_hash][ground_story][:ext_wall_area]
  ground_story_ext_wall_area_ip = OpenStudio.convert(ground_story_ext_wall_area_si, 'm^2', 'ft^2').get

  # building_facades
  # reference buildings uses first story and plenum area all around
  # prototype uses Table 4.19 by building type lit facade vs. total facade
  area_length_count_hash[:building_facades] = ground_story_ext_wall_area_ip

  return area_length_count_hash
end
model_create_multizone_fan_schedule(model, zone_op_hrs, pri_zones, system_name) click to toggle source

For a multizone system, create the fan schedule based on zone occupancy/fan schedules @author Doug Maddox, PNNL @param model [OpenStudio::Model::Model] OpenStudio model object @param zone_op_hrs [Hash] hash of zoneName zone_op_hrs @param pri_zones [Array<String>] names of zones served by the multizone system @param system_name [String] name of air loop

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2195
def model_create_multizone_fan_schedule(model, zone_op_hrs, pri_zones, system_name)
  # Not applicable if not stable baseline
  return
end
model_create_prm_any_baseline_building(user_model, building_type, climate_zone, hvac_building_type = 'All others', wwr_building_type = 'All others', swh_building_type = 'All others', model_deep_copy = false, create_proposed_model = false, custom = nil, sizing_run_dir = Dir.pwd, run_all_orients = false, unmet_load_hours_check = true, debug = false) click to toggle source

Creates a Performance Rating Method (aka 90.1-Appendix G) baseline building model based on the inputs currently in the user model.

@note Per 90.1, the Performance Rating Method “does NOT offer an alternative compliance path for minimum standard compliance.” This means you can’t use this method for code compliance to get a permit. @param user_model [OpenStudio::Model::Model] User specified OpenStudio model @param building_type [String] the building type @param climate_zone [String] the climate zone @param hvac_building_type [String] the building type for baseline HVAC system determination (90.1-2016 and onward) @param wwr_building_type [String] the building type for baseline WWR determination (90.1-2016 and onward) @param swh_building_type [String] the building type for baseline SWH determination (90.1-2016 and onward) @param model_deep_copy [Boolean] indicate if the baseline model is created based on a deep copy of the user specified model @param custom [String] the custom logic that will be applied during baseline creation. Valid choices are ‘Xcel Energy CO EDA’ or ‘90.1-2007 with addenda dn’.

If nothing is specified, no custom logic will be applied; the process will follow the template logic explicitly.

@param sizing_run_dir [String] the directory where the sizing runs will be performed @param run_all_orients [Boolean] indicate weather a baseline model should be created for all 4 orientations: same as user model, +90 deg, +180 deg, +270 deg @param debug [Boolean] If true, will report out more detailed debugging output @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 65
def model_create_prm_any_baseline_building(user_model, building_type, climate_zone, hvac_building_type = 'All others', wwr_building_type = 'All others', swh_building_type = 'All others', model_deep_copy = false, create_proposed_model = false, custom = nil, sizing_run_dir = Dir.pwd, run_all_orients = false, unmet_load_hours_check = true, debug = false)
  # User data process
  # bldg_type_hvac_zone_hash could be an empty hash if all zones in the models are unconditioned
  # TODO - move this portion to the top of the function
  bldg_type_hvac_zone_hash = {}
  handle_user_input_data(user_model, climate_zone, sizing_run_dir, hvac_building_type, wwr_building_type, swh_building_type, bldg_type_hvac_zone_hash)

  # enforce the user model to be a non-leap year, defaulting to 2009 if the model year is a leap year
  if user_model.yearDescription.is_initialized
    year_description = user_model.yearDescription.get
    if year_description.isLeapYear
      OpenStudio.logFree(OpenStudio::Warn, 'prm.log',
                         "The user model year #{year_description.assumedYear} is a leap year. Changing to 2009, a non-leap year, as required by PRM guidelines.")
      year_description.setCalendarYear(2009)
    end
  end

  if create_proposed_model
    # Perform a user model design day run only to make sure
    # that the user model is valid, i.e. can run without major
    # errors
    if !model_run_sizing_run(user_model, "#{sizing_run_dir}/USER-SR")
      OpenStudio.logFree(OpenStudio::Warn, 'prm.log',
                         "The user model is not a valid OpenStudio model. Baseline and proposed model(s) won't be created.")
      prm_raise(false,
                sizing_run_dir,
                "The user model is not a valid OpenStudio model. Baseline and proposed model(s) won't be created.")
    end

    # Check if proposed HVAC system is autosized
    if model_is_hvac_autosized(user_model)
      OpenStudio.logFree(OpenStudio::Warn, 'prm.log',
                         "The user model's HVAC system is partly autosized.")
    end

    # Generate proposed model from the user-provided model
    proposed_model = model_create_prm_proposed_building(user_model)
  end

  # Check proposed model unmet load hours
  if unmet_load_hours_check
    # Run user model; need annual simulation to get unmet load hours
    if model_run_simulation_and_log_errors(proposed_model, run_dir = "#{sizing_run_dir}/PROP")
      umlh = OpenstudioStandards::SqlFile.model_get_annual_occupied_unmet_hours(proposed_model)
      if umlh > 300
        OpenStudio.logFree(OpenStudio::Warn, 'prm.log',
                           "Proposed model unmet load hours (#{umlh}) exceed 300. Baseline model(s) won't be created.")
        prm_raise(false,
                  sizing_run_dir,
                  "Proposed model unmet load hours exceed 300. Baseline model(s) won't be created.")
      end
    else
      OpenStudio.logFree(OpenStudio::Error, 'prm.log',
                         'Simulation failed. Check the model to make sure no severe errors.')
      prm_raise(false,
                sizing_run_dir,
                'Simulation on proposed model failed. Baseline generation is stopped.')
    end
  end
  if create_proposed_model
    # Make the run directory if it doesn't exist
    unless Dir.exist?(sizing_run_dir)
      FileUtils.mkdir_p(sizing_run_dir)
    end
    # Save proposed model
    proposed_model.save(OpenStudio::Path.new("#{sizing_run_dir}/proposed_final.osm"), true)
    forward_translator = OpenStudio::EnergyPlus::ForwardTranslator.new
    idf = forward_translator.translateModel(proposed_model)
    idf_path = OpenStudio::Path.new("#{sizing_run_dir}/proposed_final.idf")
    idf.save(idf_path, true)
  end

  # Define different orientation from original orientation
  # for each individual baseline models
  # Need to run proposed model sizing simulation if no sql data is available
  degs_from_org = run_all_orientations(run_all_orients, user_model) ? [0, 90, 180, 270] : [0]

  # Create baseline model for each orientation
  degs_from_org.each do |degs|
    # New baseline model:
    # Starting point is the original proposed model
    # Create a deep copy of the user model if requested
    model = model_deep_copy ? BTAP::FileIO.deep_copy(user_model) : user_model
    model.getBuilding.setName("#{template}-#{building_type}-#{climate_zone} PRM baseline created: #{Time.new}")

    # Rotate building if requested,
    # Site shading isn't rotated
    model_rotate(model, degs) unless degs == 0
    # Perform a sizing run of the proposed model.
    #
    # Among others, one of the goal is to get individual
    # space load to determine each space's conditioning
    # type: conditioned, unconditioned, semiheated.
    if model_create_prm_baseline_building_requires_proposed_model_sizing_run(model)
      # Set up some special reports to be used for baseline system selection later
      # Zone return air flows
      node_list = []
      var_name = 'System Node Standard Density Volume Flow Rate'
      frequency = 'hourly'
      model.getThermalZones.each do |zone|
        port_list = zone.returnPortList
        port_list_objects = port_list.modelObjects
        port_list_objects.each do |node|
          node_name = node.nameString
          node_list << node_name
          output = OpenStudio::Model::OutputVariable.new(var_name, model)
          output.setKeyValue(node_name)
          output.setReportingFrequency(frequency)
        end
      end

      # air loop relief air flows
      var_name = 'System Node Standard Density Volume Flow Rate'
      frequency = 'hourly'
      model.getAirLoopHVACs.sort.each do |air_loop_hvac|
        relief_node = air_loop_hvac.reliefAirNode.get
        output = OpenStudio::Model::OutputVariable.new(var_name, model)
        output.setKeyValue(relief_node.nameString)
        output.setReportingFrequency(frequency)
      end

      # Run the sizing run
      if model_run_sizing_run(model, "#{sizing_run_dir}/SR_PROP#{degs}") == false
        return false
      end

      # Set baseline model space conditioning category based on proposed model
      model.getSpaces.each do |space|
        # Get conditioning category at the space level
        space_conditioning_category = space_conditioning_category(space)

        # Set space conditioning category
        space.additionalProperties.setFeature('space_conditioning_category', space_conditioning_category)
      end

      # The following should be done after a sizing run of the proposed model
      # because the proposed model zone design air flow is needed
      model_identify_return_air_type(model)
    end
    # Remove external shading devices
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Removing External Shading Devices ***')
    model_remove_external_shading_devices(model)

    # Reduce the WWR and SRR, if necessary
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Adjusting Window and Skylight Ratios ***')
    success, wwr_info = model_apply_prm_baseline_window_to_wall_ratio(model, climate_zone, wwr_building_type: wwr_building_type)
    model_apply_prm_baseline_skylight_to_roof_ratio(model)

    # Assign building stories to spaces in the building where stories are not yet assigned.
    OpenstudioStandards::Geometry.model_assign_spaces_to_building_stories(model)

    # Modify the internal loads in each space type, keeping user-defined schedules.
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Changing Lighting Loads ***')
    model.getSpaceTypes.sort.each do |space_type|
      set_people = false
      set_lights = true
      set_electric_equipment = false
      set_gas_equipment = false
      set_ventilation = false
      set_infiltration = false
      # For PRM, it only applies lights for now.
      space_type_apply_internal_loads(space_type, set_people, set_lights, set_electric_equipment, set_gas_equipment, set_ventilation, set_infiltration)
    end

    # Modify the lighting schedule to handle lighting occupancy sensors
    # Modify the upper limit value of fractional schedule to avoid the fatal error caused by schedule value higher than 1
    space_type_light_sch_change(model)

    # Modify electric equipment computer room schedule
    model.getSpaces.sort.each do |space|
      space_add_prm_computer_room_equipment_schedule(space)
    end

    model_apply_baseline_exterior_lighting(model)

    # Modify the elevator motor peak power
    model_add_prm_elevators(model)

    # Calculate infiltration as per 90.1 PRM rules
    model_apply_standard_infiltration(model)

    # Apply user outdoor air specs as per 90.1 PRM rules exceptions
    model_apply_userdata_outdoor_air(model)

    # If any of the lights are missing schedules, assign an always-off schedule to those lights.
    # This is assumed to be the user's intent in the proposed model.
    model.getLightss.sort.each do |lights|
      if lights.schedule.empty?
        lights.setSchedule(model.alwaysOffDiscreteSchedule)
      end
    end

    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Adding Daylighting Controls ***')

    # Run a sizing run to calculate VLT for layer-by-layer windows.
    if model_create_prm_baseline_building_requires_vlt_sizing_run(model)
      if model_run_sizing_run(model, "#{sizing_run_dir}/SRVLT") == false
        return false
      end
    end

    # Add or remove daylighting controls to each space
    # Add daylighting controls for 90.1-2013 and prior
    # Remove daylighting control for 90.1-PRM-2019 and onward
    model.getSpaces.sort.each do |space|
      space_set_baseline_daylighting_controls(space, true, false)
    end

    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Applying Baseline Constructions ***')

    # Modify some of the construction types as necessary
    model_apply_prm_construction_types(model)

    # Get the groups of zones that define the baseline HVAC systems for later use.
    # This must be done before removing the HVAC systems because it requires knowledge of proposed HVAC fuels.
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Grouping Zones by Fuel Type and Occupancy Type ***')
    zone_fan_scheds = nil

    sys_groups = model_prm_baseline_system_groups(model, custom, bldg_type_hvac_zone_hash)

    # Also get hash of zoneName:boolean to record which zones have district heating, if any
    district_heat_zones = model_get_district_heating_zones(model)

    # Store occupancy and fan operation schedules for each zone before deleting HVAC objects
    zone_fan_scheds = get_fan_schedule_for_each_zone(model)

    # Set the construction properties of all the surfaces in the model
    model_apply_constructions(model, climate_zone, wwr_building_type, wwr_info)

    # Update ground temperature profile (for F/C-factor construction objects)
    model_update_ground_temperature_profile(model, climate_zone)

    # Identify non-mechanically cooled systems if necessary
    model_identify_non_mechanically_cooled_systems(model)

    # Get supply, return, relief fan power for each air loop
    if model_get_fan_power_breakdown
      model.getAirLoopHVACs.sort.each do |air_loop|
        supply_fan_w = air_loop_hvac_get_supply_fan_power(air_loop)
        return_fan_w = air_loop_hvac_get_return_fan_power(air_loop)
        relief_fan_w = air_loop_hvac_get_relief_fan_power(air_loop)

        # Save fan power at the zone to determining
        # baseline fan power
        air_loop.thermalZones.sort.each do |zone|
          zone.additionalProperties.setFeature('supply_fan_w', supply_fan_w.to_f)
          zone.additionalProperties.setFeature('return_fan_w', return_fan_w.to_f)
          zone.additionalProperties.setFeature('relief_fan_w', relief_fan_w.to_f)
        end
      end
    end

    # Compute and marke DCV related information before deleting proposed model HVAC systems
    model_evaluate_dcv_requirements(model)

    # Remove all HVAC from model, excluding service water heating
    model_remove_prm_hvac(model)

    # Remove all EMS objects from the model
    model_remove_prm_ems_objects(model)

    # Modify the service water heating loops per the baseline rules
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Cleaning up Service Water Heating Loops ***')
    model_apply_baseline_swh_loops(model, building_type)

    # Determine the baseline HVAC system type for each of the groups of zones and add that system type.
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Adding Baseline HVAC Systems ***')
    air_loop_name_array = []
    sys_groups.each do |sys_group|
      # Determine the primary baseline system type
      system_type = model_prm_baseline_system_type(model, climate_zone, sys_group, custom, hvac_building_type, district_heat_zones)

      sys_group['zones'].sort.each_slice(5) do |zone_list|
        zone_names = []
        zone_list.each do |zone|
          zone_names << zone.name.get.to_s
        end
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "--- #{zone_names.join(', ')}")
      end

      # Add system type reference to zone
      sys_group['zones'].sort.each do |zone|
        zone.additionalProperties.setFeature('baseline_system_type', system_type[0])
      end

      # Add the system type for these zones
      model_add_prm_baseline_system(model,
                                    system_type[0],
                                    system_type[1],
                                    system_type[2],
                                    system_type[3],
                                    sys_group['zones'],
                                    zone_fan_scheds)

      model.getAirLoopHVACs.each do |air_loop|
        air_loop_name = air_loop.name.get
        unless air_loop_name_array.include?(air_loop_name)
          air_loop.additionalProperties.setFeature('zone_group_type', sys_group['zone_group_type'] || 'None')
          air_loop.additionalProperties.setFeature('sys_group_occ', sys_group['occ'] || 'None')
          air_loop_name_array << air_loop_name
        end

        # Determine return air type
        plenum, return_air_type = model_determine_baseline_return_air_type(model, system_type[0], air_loop.thermalZones)
        air_loop.thermalZones.sort.each do |zone|
          # Set up return air plenum
          zone.setReturnPlenum(model.getThermalZoneByName(plenum).get) if return_air_type == 'return_plenum'
        end
      end
    end

    # Add system type reference to all air loops
    model.getAirLoopHVACs.sort.each do |air_loop|
      if air_loop.thermalZones[0].additionalProperties.hasFeature('baseline_system_type')
        sys_type = air_loop.thermalZones[0].additionalProperties.getFeatureAsString('baseline_system_type').get
        air_loop.additionalProperties.setFeature('baseline_system_type', sys_type)
      else
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Thermal zone #{air_loop.thermalZones[0].name} is not associated to a particular system type.")
      end
    end

    # Set the zone sizing SAT for each zone in the model
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Applying Baseline HVAC System Sizing Settings ***')
    model.getThermalZones.each do |zone|
      thermal_zone_apply_prm_baseline_supply_temperatures(zone)
    end

    # Set the system sizing properties based on the zone sizing information
    model.getAirLoopHVACs.each do |air_loop|
      air_loop_hvac_apply_prm_sizing_temperatures(air_loop)
    end

    # Set internal load sizing run schedules
    model_apply_prm_baseline_sizing_schedule(model)

    # Set the heating and cooling sizing parameters
    model_apply_prm_sizing_parameters(model)

    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Applying Baseline HVAC System Controls ***')

    # SAT reset, economizers
    model.getAirLoopHVACs.sort.each do |air_loop|
      air_loop_hvac_apply_prm_baseline_controls(air_loop, climate_zone)
    end

    # Apply the baseline system water loop temperature reset control
    model.getPlantLoops.sort.each do |plant_loop|
      # Skip the SWH loops
      next if plant_loop_swh_loop?(plant_loop)

      plant_loop_apply_prm_baseline_temperatures(plant_loop)
    end

    # Run sizing run with the HVAC equipment
    if model_run_sizing_run(model, "#{sizing_run_dir}/SR1") == false
      return false
    end

    # Apply the minimum damper positions, assuming no DDC control of VAV terminals
    model.getAirLoopHVACs.sort.each do |air_loop|
      air_loop_hvac_apply_minimum_vav_damper_positions(air_loop, false)
    end

    # If there are any multi-zone systems, reset damper positions to achieve a 60% ventilation effectiveness minimum for the system
    # following the ventilation rate procedure from 62.1
    model_apply_multizone_vav_outdoor_air_sizing(model)

    # Set the baseline fan power for all air loops
    model.getAirLoopHVACs.sort.each do |air_loop|
      air_loop_hvac_apply_prm_baseline_fan_power(air_loop)
    end

    # Set the baseline fan power for all zone HVAC
    model.getZoneHVACComponents.sort.each do |zone_hvac|
      zone_hvac_component_apply_prm_baseline_fan_power(zone_hvac)
    end

    # Set the baseline number of boilers and chillers
    model.getPlantLoops.sort.each do |plant_loop|
      # Skip the SWH loops
      next if plant_loop_swh_loop?(plant_loop)

      plant_loop_apply_prm_number_of_boilers(plant_loop)
      plant_loop_apply_prm_number_of_chillers(plant_loop, sizing_run_dir)
    end

    # Set the baseline number of cooling towers
    # Must be done after all chillers are added
    model.getPlantLoops.sort.each do |plant_loop|
      # Skip the SWH loops
      next if plant_loop_swh_loop?(plant_loop)

      plant_loop_apply_prm_number_of_cooling_towers(plant_loop)
    end

    # Run sizing run with the new chillers, boilers, and cooling towers to determine capacities
    if model_run_sizing_run(model, "#{sizing_run_dir}/SR2") == false
      return false
    end

    # Set the pumping control strategy and power
    # Must be done after sizing components
    model.getPlantLoops.sort.each do |plant_loop|
      # Skip the SWH loops
      next if plant_loop_swh_loop?(plant_loop)

      plant_loop_apply_prm_baseline_pump_power(plant_loop)
      plant_loop_apply_prm_baseline_pumping_type(plant_loop)
    end

    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', '*** Applying Prescriptive HVAC Controls and Equipment Efficiencies ***')

    # Apply the HVAC efficiency standard
    model_apply_hvac_efficiency_standard(model, climate_zone)

    # Set baseline DCV system
    model_set_baseline_demand_control_ventilation(model, climate_zone)

    # Final sizing run and adjustements to values that need refinement
    model_refine_size_dependent_values(model, sizing_run_dir)

    # Fix EMS references.
    # Temporary workaround for OS issue #2598
    model_temp_fix_ems_references(model)

    # Delete all the unused resource objects
    model_remove_unused_resource_objects(model)

    # Add reporting tolerances
    model_add_reporting_tolerances(model)

    # @todo: turn off self shading
    # Set Solar Distribution to MinimalShadowing... problem is when you also have detached shading such as surrounding buildings etc
    # It won't be taken into account, while it should: only self shading from the building itself should be turned off but to my knowledge there isn't a way to do this in E+

    model_status = degs > 0 ? "baseline_final_#{degs}" : 'baseline_final'
    model.save(OpenStudio::Path.new("#{sizing_run_dir}/#{model_status}.osm"), true)

    # Translate to IDF and save for debugging
    forward_translator = OpenStudio::EnergyPlus::ForwardTranslator.new
    idf = forward_translator.translateModel(model)
    idf_path = OpenStudio::Path.new("#{sizing_run_dir}/#{model_status}.idf")
    idf.save(idf_path, true)

    # Check unmet load hours
    if unmet_load_hours_check
      nb_adjustments = 0
      loop do
        # Loop break condition: Limit the number of zone sizing factor adjustment to 3
        unless nb_adjustments < 3
          OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "After 3 rounds of zone sizing factor adjustments the unmet load hours for the baseline model (#{degs} degree of rotation) still exceed 300 hours. Please open an issue on GitHub (https://github.com/NREL/openstudio-standards/issues) and share your user model with the developers.")
          break
        end
        # Close the previous SQL session if open to prevent EnergyPlus from overloading the same session
        sql = model.sqlFile.get
        if sql.connectionOpen
          sql.close
        end

        # simulation failure, raise the exception
        unless model_run_simulation_and_log_errors(model, "#{sizing_run_dir}/final#{degs}")
          raise('OpenStudio simulation failed.')
        end

        # If UMLH are greater than the threshold allowed by Appendix G,
        # increase zone air flow and load as per the recommendation in
        # the PRM-RM; Note that the PRM-RM only suggest to increase
        # air zone air flow, but the zone sizing factor in EnergyPlus
        # increase both air flow and load.
        umlh = OpenstudioStandards::SqlFile.model_get_annual_occupied_unmet_hours(proposed_model)
        if umlh > 300
          model.getThermalZones.each do |thermal_zone|
            # Cooling adjustments
            clg_umlh = OpenstudioStandards::SqlFile.thermal_zone_get_annual_occupied_unmet_cooling_hours(thermal_zone)
            if clg_umlh > 50
              sizing_factor = 1.0
              if thermal_zone.sizingZone.zoneCoolingSizingFactor.is_initialized
                sizing_factor = thermal_zone.sizingZone.zoneCoolingSizingFactor.get
              end
              # Make adjustment to zone cooling sizing factor
              # Do not adjust factors greater or equal to 2
              clg_umlh > 150 ? sizing_factor = [2.0, sizing_factor * 1.1].min : sizing_factor = [2.0, sizing_factor * 1.05].min
              thermal_zone.sizingZone.setZoneCoolingSizingFactor(sizing_factor)
            end

            # Heating adjustments
            # Reset sizing factor
            htg_umlh = OpenstudioStandards::SqlFile.thermal_zone_get_annual_occupied_unmet_heating_hours(thermal_zone)
            if htg_umlh > 50
              sizing_factor = 1.0
              if thermal_zone.sizingZone.zoneHeatingSizingFactor.is_initialized
                # Get zone heating sizing factor
                sizing_factor = thermal_zone.sizingZone.zoneHeatingSizingFactor.get
              end

              # Make adjustment to zone heating sizing factor
              # Do not adjust factors greater or equal to 2
              htg_umlh > 150 ? sizing_factor = [2.0, sizing_factor * 1.1].min : sizing_factor = [2.0, sizing_factor * 1.05].min
              thermal_zone.sizingZone.setZoneHeatingSizingFactor(sizing_factor)
            end
          end
        end

        nb_adjustments += 1
      end
    end
  end

  if debug
    generate_baseline_log(sizing_run_dir)
  end

  return true
end
model_create_prm_baseline_building(model, building_type, climate_zone, custom = nil, sizing_run_dir = Dir.pwd, debug = false) click to toggle source

Creates a Performance Rating Method (aka Appendix G aka LEED) baseline building model Method used for 90.1-2013 and prior @param model [OpenStudio::Model::Model] User specified OpenStudio model @param building_type [String] the building type @param climate_zone [String] the climate zone @param custom [String] the custom logic that will be applied during baseline creation. Valid choices are ‘Xcel Energy CO EDA’ or ‘90.1-2007 with addenda dn’.

If nothing is specified, no custom logic will be applied; the process will follow the template logic explicitly.

@param sizing_run_dir [String] the directory where the sizing runs will be performed @param debug [Boolean] if true, will report out more detailed debugging output

# File lib/openstudio-standards/standards/Standards.Model.rb, line 43
def model_create_prm_baseline_building(model, building_type, climate_zone, custom = nil, sizing_run_dir = Dir.pwd, debug = false)
  model_create_prm_any_baseline_building(model, building_type, climate_zone, 'All others', 'All others', 'All others', false, false, custom, sizing_run_dir, false, false, debug)
end
model_create_prm_baseline_building_requires_proposed_model_sizing_run(model) click to toggle source

Determine if there is a need for a proposed model sizing run. A typical application of such sizing run is to determine space conditioning type.

@param model [OpenStudio::Model::Model] OpenStudio model object

@return [Boolean] Returns true if a sizing run is required

# File lib/openstudio-standards/standards/Standards.Model.rb, line 723
def model_create_prm_baseline_building_requires_proposed_model_sizing_run(model)
  return false
end
model_create_prm_baseline_building_requires_vlt_sizing_run(model) click to toggle source

Determine if there needs to be a sizing run after constructions are added so that EnergyPlus can calculate the VLTs of layer-by-layer glazing constructions. These VLT values are needed for the daylighting controls logic for some templates.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 712
def model_create_prm_baseline_building_requires_vlt_sizing_run(model)
  return false # Not required for most templates
end
model_create_prm_proposed_building(user_model) click to toggle source

Creates a Performance Rating Method (aka 90.1-Appendix G) proposed building model based on the inputs currently in the user model.

@param user_model [OpenStudio::model::Model] User specified OpenStudio model @return [OpenStudio::model::Model] returns the proposed building model corresponding to a user model

# File lib/openstudio-standards/standards/Standards.Model.rb, line 585
def model_create_prm_proposed_building(user_model)
  # Create copy of the user model
  proposed_model = BTAP::FileIO.deep_copy(user_model)

  # Get user building level data
  building_name = proposed_model.building.get.name.get
  user_buildings = @standards_data.key?('userdata_building') ? @standards_data['userdata_building'] : nil

  # If needed, modify user model infiltration
  if user_buildings
    user_building_index = user_buildings.index { |user_building| building_name.include? user_building['name'] }
    # TODO: Move the user data processing section
    infiltration_modeled_from_field_verification_results = 'false'
    if user_building_index && user_buildings[user_building_index]['infiltration_modeled_from_field_verification_results']
      infiltration_modeled_from_field_verification_results = user_buildings[user_building_index]['infiltration_modeled_from_field_verification_results'].to_s.downcase
    end

    # Calculate total infiltration flow rate per envelope area
    building_envelope_area_m2 = model_building_envelope_area(proposed_model)
    curr_tot_infil_m3_per_s_per_envelope_area = model_current_building_envelope_infiltration_at_75pa(proposed_model, building_envelope_area_m2)
    curr_tot_infil_cfm_per_envelope_area = OpenStudio.convert(curr_tot_infil_m3_per_s_per_envelope_area, 'm^3/s*m^2', 'cfm/ft^2').get

    # Warn users if the infiltration modeling in the user/proposed model is not based on field verification
    # If not modeled based on field verification, it should be modeled as 0.6 cfm/ft2
    unless infiltration_modeled_from_field_verification_results.casecmp('true')
      if curr_tot_infil_cfm_per_envelope_area < 0.6
        OpenStudio.logFree(OpenStudio::Info, 'prm.log', "The user model's I_75Pa is estimated to be #{curr_tot_infil_cfm_per_envelope_area} m3/s per m2 of total building envelope")
      end
    end

    # Modify model to follow the PRM infiltration modeling method
    model_apply_standard_infiltration(proposed_model, curr_tot_infil_cfm_per_envelope_area)
  end

  # If needed, remove all non-adiabatic pipes of SWH loops
  proposed_model.getPlantLoops.sort.each do |plant_loop|
    # Skip non service water heating loops
    next unless plant_loop_swh_loop?(plant_loop)

    plant_loop_adiabatic_pipes_only(plant_loop)
  end

  # TODO: Once data refactoring has been completed lookup values from the database;
  #       For now, hard-code LPD for selected spaces. Current Standards Space Type
  #       of OS:SpaceType is the PRM interior lighting space type. These values are
  #       from Table 9.6.1 as required by Section G3.1.6.e.
  proposed_lpd_residential_spaces = {
    'dormitory - living quarters' => 0.5, # "primary_space_type": "Dormitory - Living Quarters",
    'apartment - hardwired' => 0.6, # "primary_space_type": "Dwelling Unit"
    'guest room' => 0.41 # "primary_space_type": "Guest Room",
  }

  # Make proposed model space related adjustments
  proposed_model.getSpaces.each do |space|
    # If needed, modify computer equipment schedule
    # Section G3.1.3.16
    space_add_prm_computer_room_equipment_schedule(space)

    # If needed, modify lighting power denstities in residential spaces/zones
    # Section G3.1.6.e
    standard_space_type = prm_get_optional_handler(space, @sizing_run_dir, 'spaceType', 'standardsSpaceType').downcase
    user_spaces = @standards_data.key?('userdata_space') ? @standards_data['userdata_space'] : nil
    if ['dormitory - living quarters', 'apartment - hardwired', 'guest room'].include?(standard_space_type)
      user_spaces.each do |user_data|
        if user_data['name'].to_s == space.name.to_s && user_data['has_residential_exception'].to_s.downcase != 'yes'
          # Get LPDs
          lpd_w_per_m2 = space.lightingPowerPerFloorArea
          ref_space_lpd_per_ft2 = proposed_lpd_residential_spaces[standard_space_type]
          ref_space_lpd_per_m2 = OpenStudio.convert(ref_space_lpd_per_ft2, 'W/ft^2', 'W/m^2').get
          # Set new LPD
          space.setLightingPowerPerFloorArea([lpd_w_per_m2, ref_space_lpd_per_m2].max)
        end
      end
    end
  end

  return proposed_model
end
model_create_prm_stable_baseline_building(model, climate_zone, hvac_building_type, wwr_building_type, swh_building_type, output_dir = Dir.pwd, unmet_load_hours_check = true, debug = false) click to toggle source

Creates a Performance Rating Method (aka Appendix G aka LEED) baseline building model Method used for 90.1-2016 and onward

@note Per 90.1, the Performance Rating Method “does NOT offer an alternative compliance path for minimum standard compliance.” This means you can’t use this method for code compliance to get a permit. @param model [OpenStudio::Model::Model] User specified OpenStudio model @param climate_zone [String] the climate zone @param hvac_building_type [String] the building type for baseline HVAC system determination (90.1-2016 and onward) @param wwr_building_type [String] the building type for baseline WWR determination (90.1-2016 and onward) @param swh_building_type [String] the building type for baseline SWH determination (90.1-2016 and onward) @param output_dir [String] the directory where the PRM generations will be performed @param debug [Boolean] If true, will report out more detailed debugging output @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 30
def model_create_prm_stable_baseline_building(model, climate_zone, hvac_building_type, wwr_building_type, swh_building_type, output_dir = Dir.pwd, unmet_load_hours_check = true, debug = false)
  model_create_prm_any_baseline_building(model, '', climate_zone, hvac_building_type, wwr_building_type, swh_building_type, true, true, false, output_dir, true, unmet_load_hours_check, debug)
end
model_create_space_type_hash(model, trust_effective_num_spaces = false) click to toggle source

create space_type_hash with info such as effective_num_spaces, num_units, num_meds, num_meals

@param model [OpenStudio::Model::Model] OpenStudio model object @param trust_effective_num_spaces [Boolean] defaults to false - set to true if modeled every space as a real rpp, vs. space as collection of rooms @return [Hash] hash of space types with misc information @todo - add code when determining number of units to makeuse of trust_effective_num_spaces arg

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5243
def model_create_space_type_hash(model, trust_effective_num_spaces = false)
  # assumed class size to deduct teachers from occupant count for classrooms
  typical_class_size = 20.0

  space_type_hash = {}
  model.getSpaceTypes.sort.each do |space_type|
    # get standards info
    stds_bldg_type = space_type.standardsBuildingType
    stds_space_type = space_type.standardsSpaceType
    if stds_bldg_type.is_initialized && stds_space_type.is_initialized && !space_type.spaces.empty?
      stds_bldg_type = stds_bldg_type.get
      stds_space_type = stds_space_type.get
      effective_num_spaces = 0
      floor_area = 0.0
      num_people = 0.0
      num_students = 0.0
      num_units = 0.0
      num_beds = 0.0
      num_people_bldg_total = nil # may need this in future, not same as sumo of people for all space types.
      num_meals = nil
      # determine num_elevators in another method
      # determine num_parking_spots in another method

      # loop through spaces to get mis values
      space_type.spaces.sort.each do |space|
        next unless space.partofTotalFloorArea

        effective_num_spaces += space.multiplier
        floor_area += space.floorArea * space.multiplier
        num_people += space.numberOfPeople * space.multiplier
      end

      # determine number of units
      if stds_bldg_type == 'SmallHotel' && stds_space_type.include?('GuestRoom') # doesn't always == GuestRoom so use include?
        avg_unit_size = OpenStudio.convert(354.2, 'ft^2', 'm^2').get # calculated from prototype
        num_units = floor_area / avg_unit_size
      elsif stds_bldg_type == 'LargeHotel' && stds_space_type.include?('GuestRoom')
        avg_unit_size = OpenStudio.convert(279.7, 'ft^2', 'm^2').get # calculated from prototype
        num_units = floor_area / avg_unit_size
      elsif stds_bldg_type == 'MidriseApartment' && stds_space_type.include?('Apartment')
        avg_unit_size = OpenStudio.convert(949.9, 'ft^2', 'm^2').get # calculated from prototype
        num_units = floor_area / avg_unit_size
      elsif stds_bldg_type == 'HighriseApartment' && stds_space_type.include?('Apartment')
        avg_unit_size = OpenStudio.convert(949.9, 'ft^2', 'm^2').get # calculated from prototype
        num_units = floor_area / avg_unit_size
      elsif stds_bldg_type == 'StripMall'
        avg_unit_size = OpenStudio.convert(22_500.0 / 10.0, 'ft^2', 'm^2').get # calculated from prototype
        num_units = floor_area / avg_unit_size
      elsif stds_bldg_type == 'Htl' && (stds_space_type.include?('GuestRmOcc') || stds_space_type.include?('GuestRmUnOcc'))
        avg_unit_size = OpenStudio.convert(354.2, 'ft^2', 'm^2').get # calculated from prototype
        num_units = floor_area / avg_unit_size
      elsif stds_bldg_type == 'MFm' && (stds_space_type.include?('ResBedroom') || stds_space_type.include?('ResLiving'))
        avg_unit_size = OpenStudio.convert(949.9, 'ft^2', 'm^2').get # calculated from prototype
        num_units = floor_area / avg_unit_size
      elsif stds_bldg_type == 'Mtl' && (stds_space_type.include?('GuestRmOcc') || stds_space_type.include?('GuestRmUnOcc'))
        avg_unit_size = OpenStudio.convert(354.2, 'ft^2', 'm^2').get # calculated from prototype
        num_units = floor_area / avg_unit_size
      elsif stds_bldg_type == 'Nrs' && stds_space_type.include?('PatientRoom')
        avg_unit_size = OpenStudio.convert(354.2, 'ft^2', 'm^2').get # calculated from prototype
        num_units = floor_area / avg_unit_size
      end

      # determine number of beds
      if stds_bldg_type == 'Hospital' && ['PatRoom', 'ICU_PatRm', 'ICU_Open'].include?(stds_space_type)
        num_beds = num_people
      elsif stds_bldg_type == 'Hsp' && ['PatientRoom', 'HspSurgOutptLab', 'HspNursing'].include?(stds_space_type)
        num_beds = num_people
      end

      # determine number of students
      if ['PrimarySchool', 'SecondarySchool'].include?(stds_bldg_type) && stds_space_type == 'Classroom'
        num_students += num_people * ((typical_class_size - 1.0) / typical_class_size)
      elsif ['EPr', 'ESe', 'ERC', 'EUn', 'ECC'].include?(stds_bldg_type) && stds_space_type == 'Classroom'
        num_students += num_people * ((typical_class_size - 1.0) / typical_class_size)
      end

      space_type_hash[space_type] = {}
      space_type_hash[space_type][:stds_bldg_type] = stds_bldg_type
      space_type_hash[space_type][:stds_space_type] = stds_space_type
      space_type_hash[space_type][:effective_num_spaces] = effective_num_spaces
      space_type_hash[space_type][:floor_area] = floor_area
      space_type_hash[space_type][:num_people] = num_people
      space_type_hash[space_type][:num_students] = num_students
      space_type_hash[space_type][:num_units] = num_units
      space_type_hash[space_type][:num_beds] = num_beds

      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For #{space_type.name}, floor area = #{OpenStudio.convert(floor_area, 'm^2', 'ft^2').get.round} ft^2.") unless floor_area == 0.0
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For #{space_type.name}, number of spaces = #{effective_num_spaces}.") unless effective_num_spaces == 0.0
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For #{space_type.name}, number of units = #{num_units}.") unless num_units == 0.0
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For #{space_type.name}, number of people = #{num_people.round}.") unless num_people == 0.0
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For #{space_type.name}, number of students = #{num_students}.") unless num_students == 0.0
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For #{space_type.name}, number of beds = #{num_beds}.") unless num_beds == 0.0
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For #{space_type.name}, number of meals = #{num_meals}.") unless num_meals.nil?

    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Cannot identify standards building type and space type for #{space_type.name}, it won't be added to space_type_hash.")
    end
  end

  return space_type_hash.sort.to_h
end
model_create_story_hash(model) click to toggle source

Create sorted hash of stories with data need to determine effective number of stories above and below grade the key should be the story object, which would allow other measures the ability to for example loop through spaces of the bottom story

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Hash] hash of space types with data in value necessary to determine effective number of stories above and below grade

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5123
def model_create_story_hash(model)
  story_hash = {}

  # loop through stories
  model.getBuildingStorys.sort.each do |story|
    # skip of story doesn't have any spaces
    next if story.spaces.empty?

    story_min_z = nil
    story_zone_multipliers = []
    story_spaces_part_of_floor_area = []
    story_spaces_not_part_of_floor_area = []
    story_ext_wall_area = 0.0
    story_ground_wall_area = 0.0

    # loop through space surfaces to find min z value
    story.spaces.each do |space|
      # skip of space doesn't have any geometry
      next if space.surfaces.empty?

      # get space multiplier
      story_zone_multipliers << space.multiplier

      # space part of floor area check
      if space.partofTotalFloorArea
        story_spaces_part_of_floor_area << space
      else
        story_spaces_not_part_of_floor_area << space
      end

      # update exterior wall area (not sure if this is net or gross)
      story_ext_wall_area += space.exteriorWallArea

      space_min_z = nil
      z_points = []
      space.surfaces.each do |surface|
        surface.vertices.each do |vertex|
          z_points << vertex.z
        end

        # update count of ground wall areas
        next if surface.surfaceType != 'Wall'
        next if surface.outsideBoundaryCondition != 'Ground'

        # @todo make more flexible for slab/basement model.modeling

        story_ground_wall_area += surface.grossArea
      end

      # skip if surface had no vertices
      next if z_points.empty?

      # update story min_z
      space_min_z = z_points.min + space.zOrigin
      if story_min_z.nil? || (story_min_z > space_min_z)
        story_min_z = space_min_z
      end
    end

    # update story hash
    story_hash[story] = {}
    story_hash[story][:min_z] = story_min_z
    story_hash[story][:multipliers] = story_zone_multipliers
    story_hash[story][:part_of_floor_area] = story_spaces_part_of_floor_area
    story_hash[story][:not_part_of_floor_area] = story_spaces_not_part_of_floor_area
    story_hash[story][:ext_wall_area] = story_ext_wall_area
    story_hash[story][:ground_wall_area] = story_ground_wall_area
  end

  # sort hash by min_z low to high
  story_hash = story_hash.sort_by { |k, v| v[:min_z] }

  # reassemble into hash after sorting
  hash = {}
  story_hash.each do |story, props|
    hash[story] = props
  end

  return hash
end
model_cw_loop_cooling_tower_fan_type(model) click to toggle source

Determine which type of fan the cooling tower will have. Defaults to TwoSpeed Fan.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [String] the fan type: TwoSpeed Fan, Variable Speed Fan

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6271
def model_cw_loop_cooling_tower_fan_type(model)
  fan_type = 'Variable Speed Fan'
  return fan_type
end
model_differentiate_primary_secondary_thermal_zones(model, zones, zone_fan_scheds = nil) click to toggle source

Determine which of the zones should be served by the primary HVAC system. First, eliminate zones that differ by more# than 40 full load hours per week. In this case, lighting schedule is used as the proxy for operation instead of occupancy to avoid accidentally removing transition spaces. Second, eliminate zones whose design internal loads differ from the area-weighted average of all other zones on the system by more than 10 Btu/hr*ft^2.

@param model [OpenStudio::Model::Model] OpenStudio model object @param zones [Array<OpenStudio::Model::ThermalZone>] an array of zones @return [Hash] A hash of two arrays of ThermalZones, where the keys are ‘primary’ and ‘secondary’

# File lib/openstudio-standards/standards/Standards.Model.rb, line 2044
def model_differentiate_primary_secondary_thermal_zones(model, zones, zone_fan_scheds = nil)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', 'Determining which zones are served by the primary vs. secondary HVAC system.')

  # Determine the operational hours (proxy is annual
  # full load lighting hours) for all zones
  zone_data_1 = []
  zones.each do |zone|
    data = {}
    data['zone'] = zone
    # Get the area
    area_ft2 = OpenStudio.convert(zone.floorArea * zone.multiplier, 'm^2', 'ft^2').get
    data['area_ft2'] = area_ft2
    # OpenStudio::logFree(OpenStudio::Info, "openstudio.Standards.Model", "#{zone.name}")
    zone.spaces.each do |space|
      # OpenStudio::logFree(OpenStudio::Info, "openstudio.Standards.Model", "***#{space.name}")
      # Get all lights from either the space
      # or the space type.
      all_lights = []
      all_lights += space.lights
      if space.spaceType.is_initialized
        all_lights += space.spaceType.get.lights
      end
      # Base the annual operational hours
      # on the first lights schedule with hours
      # greater than zero.
      ann_op_hrs = 0
      all_lights.sort.each do |lights|
        # OpenStudio::logFree(OpenStudio::Info, "openstudio.Standards.Model", "******#{lights.name}")
        # Get the fractional lighting schedule
        lights_sch = lights.schedule
        full_load_hrs = 0.0
        # Skip lights with no schedule
        next if lights_sch.empty?

        lights_sch = lights_sch.get
        full_load_hrs = OpenstudioStandards::Schedules.schedule_get_equivalent_full_load_hours(lights_sch)
        if full_load_hrs > 0
          ann_op_hrs = full_load_hrs
          break # Stop after the first schedule with more than 0 hrs
        end
      end
      wk_op_hrs = ann_op_hrs / 52.0
      data['wk_op_hrs'] = wk_op_hrs
      # OpenStudio::logFree(OpenStudio::Info, "openstudio.Standards.Model", "******wk_op_hrs = #{wk_op_hrs.round}")
    end

    zone_data_1 << data
  end

  # Filter out any zones that operate differently by more than 40hrs/wk.
  # This will be determined by a difference of more than (40 hrs/wk * 52 wks/yr) = 2080 annual full load hrs.
  zones_same_hrs = model_eliminate_outlier_zones(model, zone_data_1, 'wk_op_hrs', 40, 'weekly operating hrs', 'hrs')

  # Get the internal loads for
  # all remaining zones.
  zone_data_2 = []
  zones_same_hrs.each do |zn_data|
    data = {}
    zone = zn_data['zone']
    data['zone'] = zone
    # Get the area
    area_m2 = zone.floorArea * zone.multiplier
    area_ft2 = OpenStudio.convert(area_m2, 'm^2', 'ft^2').get
    data['area_ft2'] = area_ft2
    # Get the internal loads
    int_load_w = OpenstudioStandards::ThermalZone.thermal_zone_get_design_internal_load(zone) * zone.multiplier
    # Normalize per-area
    int_load_w_per_m2 = int_load_w / area_m2
    int_load_btu_per_ft2 = OpenStudio.convert(int_load_w_per_m2, 'W/m^2', 'Btu/hr*ft^2').get
    data['int_load_btu_per_ft2'] = int_load_btu_per_ft2
    zone_data_2 << data
  end

  # Filter out any zones that are +/- 10 Btu/hr*ft^2 from the average
  pri_zn_data = model_eliminate_outlier_zones(model, zone_data_2, 'int_load_btu_per_ft2', 10, 'internal load', 'Btu/hr*ft^2')

  # Get just the primary zones themselves
  pri_zones = []
  pri_zone_names = []
  pri_zn_data.each do |zn_data|
    pri_zones << zn_data['zone']
    pri_zone_names << zn_data['zone'].name.get.to_s
  end

  # Get the secondary zones
  sec_zones = []
  sec_zone_names = []
  zones.each do |zone|
    unless pri_zones.include?(zone)
      sec_zones << zone
      sec_zone_names << zone.name.get.to_s
    end
  end

  # Report out the primary vs. secondary zones
  unless pri_zone_names.empty?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Primary system zones = #{pri_zone_names.join(', ')}.")
  end
  unless sec_zone_names.empty?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Secondary system zones = #{sec_zone_names.join(', ')}.")
  end

  zone_op_hrs = []
  return { 'primary' => pri_zones, 'secondary' => sec_zones, 'zone_op_hrs' => zone_op_hrs }
end
model_effective_num_stories(model) click to toggle source

populate this method Determine the effective number of stories above and below grade

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Hash] hash with effective_num_stories_below_grade and effective_num_stories_above_grade

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5209
def model_effective_num_stories(model)
  below_grade = 0
  above_grade = 0

  # call model_create_story_hash(model)
  story_hash = model_create_story_hash(model)

  story_hash.each do |story, hash|
    # skip if no spaces in story are included in the building area
    next if hash[:part_of_floor_area].empty?

    # only count as below grade if ground wall area is greater than ext wall area and story below is also below grade
    if above_grade.zero? && (hash[:ground_wall_area] > hash[:ext_wall_area])
      below_grade += 1 * hash[:multipliers].min
    else
      above_grade += 1 * hash[:multipliers].min
    end
  end

  # populate hash
  effective_num_stories = {}
  effective_num_stories[:below_grade] = below_grade
  effective_num_stories[:above_grade] = above_grade
  effective_num_stories[:story_hash] = story_hash

  return effective_num_stories
end
model_elevator_fan_pwr(model, vent_rate_cfm) click to toggle source

Determines the power of the elevator ventilation fan. Defaults to 90.1-2010, which had no requirement for ventilation fan efficiency.

@param model [OpenStudio::Model::Model] OpenStudio model object @param vent_rate_cfm [Double] the ventilation rate in ft^3/min @return [Double] the ventilation fan power in watts

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.elevators.rb, line 139
def model_elevator_fan_pwr(model, vent_rate_cfm)
  vent_pwr_per_flow_w_per_cfm = 0.33
  vent_pwr_w = vent_pwr_per_flow_w_per_cfm * vent_rate_cfm

  return vent_pwr_w
end
model_elevator_lift_power(model, elevator_type, building_type) click to toggle source

Determines the power required by an individual elevator of a given type. Defaults to the values used by the DOE prototype buildings.

@param model [OpenStudio::Model::Model] OpenStudio model object @param elevator_type [String] valid choices are Traction, Hydraulic @param building_type [String] the building type @return [Double] lift power in watts

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.elevators.rb, line 108
def model_elevator_lift_power(model, elevator_type, building_type)
  lift_pwr_w = 0
  if elevator_type == 'Traction'
    lift_pwr_w += 20_370.0
  elsif elevator_type == 'Hydraulic'
    lift_pwr_w += 16_055.0
  else
    lift_pwr_w += 16_055.0
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "Elevator type '#{elevator_type}', not recognized, will assume Hydraulic elevator, #{lift_pwr_w} W.")
  end

  return lift_pwr_w
end
model_elevator_lighting_pct_incandescent(model) click to toggle source

Determines the percentage of the elevator cab lighting that is incandescent. The remainder is assumed to be LED. Defaults to 70% incandescent, representing older elevators.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Double] incandescent lighting percentage

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.elevators.rb, line 128
def model_elevator_lighting_pct_incandescent(model)
  pct_incandescent = 0.7
  return pct_incandescent
end
model_eliminate_outlier_zones(model, array_of_zones, key_to_inspect, tolerance, field_name, units) click to toggle source

elimates outlier zones based on a set of keys

@param model [OpenStudio::Model::Model] OpenStudio model object @param array_of_zones [Array] an array of Hashes for each zone, with the keys ‘zone’ @param key_to_inspect [String] hash key to inspect in array of zones @param tolerance [Double] tolerance @param field_name [String] field name to inspect @param units [String] units @return [Array] an array of Hashes for each zone

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1964
def model_eliminate_outlier_zones(model, array_of_zones, key_to_inspect, tolerance, field_name, units)
  # Sort the zones by the desired key
  begin
    array_of_zones = array_of_zones.sort_by { |hsh| hsh[key_to_inspect] }
  rescue ArgumentError => e
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Unable to sort array_of_zones by #{key_to_inspect} due to #{e.message}, defaulting to order that was passed")
  end

  # Calculate the area-weighted average
  total = 0.0
  total_area = 0.0
  all_vals = []
  all_areas = []
  all_zn_names = []
  array_of_zones.each do |zn|
    val = zn[key_to_inspect]
    area = zn['area_ft2']
    total += val * area
    total_area += area
    all_vals << val.round(1)
    all_areas << area.round
    all_zn_names << zn['zone'].name.get.to_s
  end

  if total_area == 0
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Total area is zero for array_of_zones with key #{key_to_inspect}, unable to calculate area-weighted average.")
    return false
  end

  avg = total / total_area
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Values for #{field_name}, tol = #{tolerance} #{units}, area ft2:")
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "vals  #{all_vals.join(', ')}")
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "areas #{all_areas.join(', ')}")
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "names #{all_zn_names.join(', ')}")

  # Calculate the biggest delta and the index of the biggest delta
  biggest_delta_i = 0 # array at first item in case delta is 0
  biggest_delta = 0.0
  worst = nil
  array_of_zones.each_with_index do |zn, i|
    val = zn[key_to_inspect]
    if worst.nil? # array at first item in case delta is 0
      worst = val
    end
    delta = (val - avg).abs
    if delta >= biggest_delta
      biggest_delta = delta
      biggest_delta_i = i
      worst = val
    end
  end

  # puts "   #{worst} - #{avg.round} = #{biggest_delta.round} biggest delta"

  # Compare the biggest delta against the difference and eliminate that zone if higher than the limit.
  if biggest_delta > tolerance
    zn_name = array_of_zones[biggest_delta_i]['zone'].name.get.to_s
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For zone #{zn_name}, the #{field_name} of #{worst.round(1)} #{units} is more than #{tolerance} #{units} outside the area-weighted average of #{avg.round(1)} #{units}; it will be placed on its own secondary system.")
    array_of_zones.delete_at(biggest_delta_i)
    # Call method recursively if something was eliminated
    array_of_zones = model_eliminate_outlier_zones(model, array_of_zones, key_to_inspect, tolerance, field_name, units)
  else
    zn_name = array_of_zones[biggest_delta_i]['zone'].name.get.to_s
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "For zone #{zn_name}, the #{field_name} #{worst.round(2)} #{units} - average #{field_name} #{avg.round(2)} #{units} = #{biggest_delta.round(2)} #{units} less than the tolerance of #{tolerance} #{units}, stopping elimination process.")
  end

  return array_of_zones
end
model_find_and_add_construction(model, climate_zone_set, intended_surface_type, standards_construction_type, building_category, wwr_building_type: nil, wwr_info: {}, surface: nil) click to toggle source

Helper method to find a particular construction and add it to the model after modifying the insulation value if necessary.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone_set [String] climate zone set @param intended_surface_type [String] intended surface type @param standards_construction_type [String] standards construction type @param building_category [String] building category @param wwr_building_type [String] building type used to determine WWR for the PRM baseline model @param wwr_info [Hash] @Todo - check what this is used for @param surface [OpenStudio::Model::Surface] OpenStudio surface object, only used for surface specific construction, e.g F/C-factor constructions @return [OpenStudio::Model::Construction] construction object

# File lib/openstudio-standards/standards/Standards.Model.rb, line 3264
def model_find_and_add_construction(model, climate_zone_set, intended_surface_type, standards_construction_type, building_category, wwr_building_type: nil, wwr_info: {}, surface: nil)
  # Get the construction properties,
  # which specifies properties by construction category by climate zone set.
  # AKA the info in Tables 5.5-1-5.5-8

  search_criteria = { 'template' => template,
                      'climate_zone_set' => climate_zone_set,
                      'intended_surface_type' => intended_surface_type,
                      'standards_construction_type' => standards_construction_type,
                      'building_category' => building_category }

  # Check if WWR criteria is needed for the construction search
  wwr_parameter = { 'intended_surface_type' => intended_surface_type }
  if wwr_building_type
    wwr_parameter['wwr_building_type'] = wwr_building_type
    wwr_parameter['wwr_info'] = wwr_info
  end
  wwr_range = model_get_percent_of_surface_range(model, wwr_parameter)

  if !wwr_range['minimum_percent_of_surface'].nil? && !wwr_range['maximum_percent_of_surface'].nil?
    search_criteria['minimum_percent_of_surface'] = wwr_range['minimum_percent_of_surface']
    search_criteria['maximum_percent_of_surface'] = wwr_range['maximum_percent_of_surface']
  end

  # First search
  props = model_find_object(standards_data['construction_properties'], search_criteria)

  if !props
    # Second search: In case need to use climate zone (e.g: 3) instead of sub-climate zone (e.g: 3A) for search
    climate_zone = climate_zone_set[0..-2]
    search_criteria['climate_zone_set'] = climate_zone
    props = model_find_object(standards_data['construction_properties'], search_criteria)
  end

  if !props
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Could not find construction properties for: #{template}-#{climate_zone_set}-#{intended_surface_type}-#{standards_construction_type}-#{building_category}.")
    # Return an empty construction
    construction = OpenStudio::Model::Construction.new(model)
    construction.setName('Could not find construction properties set to Adiabatic ')
    almost_adiabatic = OpenStudio::Model::MasslessOpaqueMaterial.new(model, 'Smooth', 500)
    construction.insertLayer(0, almost_adiabatic)
    return construction
  end

  # Make sure that a construction is specified
  if props['construction'].nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "No typical construction is specified for construction properties of: #{template}-#{climate_zone_set}-#{intended_surface_type}-#{standards_construction_type}-#{building_category}.  Make sure it is entered in the spreadsheet.")
    # Return an empty construction
    construction = OpenStudio::Model::Construction.new(model)
    construction.setName('No typical construction was specified')
    return construction
  end

  # Add the construction, modifying properties as necessary
  construction = model_add_construction(model, props['construction'], props, surface)

  return construction
end
model_find_ashrae_hot_water_demand(model) click to toggle source

Returns average daily hot water consumption by building type recommendations from 2011 ASHRAE Handbook - HVAC Applications Table 7 section 50.14 Not all building types are included in lookup some recommendations have multiple values based on number of units. Will return an array of hashes. Many may have one array entry. all values other than block size are gallons.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Array] array of hashes. Each array entry based on different capacity

specific to building type. Array will be empty for some building types.
# File lib/openstudio-standards/standards/Standards.Model.rb, line 4857
def model_find_ashrae_hot_water_demand(model)
  # @todo for types not in table use standards area normalized swh values

  # get building type
  building_data = model_get_building_properties(model)
  building_type = building_data['building_type']

  result = []
  if building_type == 'FullServiceRestaurant'
    result << { units: 'meal', block: nil, max_hourly: 1.5, max_daily: 11.0, avg_day_unit: 2.4 }
  elsif building_type == 'Hospital'
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "No SWH rules of thumbs for #{building_type}.")
  elsif ['LargeHotel', 'SmallHotel'].include? building_type
    result << { units: 'unit', block: 20, max_hourly: 6.0, max_daily: 35.0, avg_day_unit: 24.0 }
    result << { units: 'unit', block: 60, max_hourly: 5.0, max_daily: 25.0, avg_day_unit: 14.0 }
    result << { units: 'unit', block: 100, max_hourly: 4.0, max_daily: 15.0, avg_day_unit: 10.0 }
  elsif building_type == 'MidriseApartment'
    result << { units: 'unit', block: 20, max_hourly: 12.0, max_daily: 80.0, avg_day_unit: 42.0 }
    result << { units: 'unit', block: 50, max_hourly: 10.0, max_daily: 73.0, avg_day_unit: 40.0 }
    result << { units: 'unit', block: 75, max_hourly: 8.5, max_daily: 66.0, avg_day_unit: 38.0 }
    result << { units: 'unit', block: 100, max_hourly: 7.0, max_daily: 60.0, avg_day_unit: 37.0 }
    result << { units: 'unit', block: 200, max_hourly: 5.0, max_daily: 50.0, avg_day_unit: 35.0 }
  elsif ['Office', 'LargeOffice', 'MediumOffice', 'SmallOffice', 'LargeOfficeDetailed', 'MediumOfficeDetailed', 'SmallOfficeDetailed'].include? building_type
    result << { units: 'person', block: nil, max_hourly: 0.4, max_daily: 2.0, avg_day_unit: 1.0 }
  elsif building_type == 'Outpatient'
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "No SWH rules of thumbs for #{building_type}.")
  elsif building_type == 'PrimarySchool'
    result << { units: 'student', block: nil, max_hourly: 0.6, max_daily: 1.5, avg_day_unit: 0.6 }
  elsif building_type == 'QuickServiceRestaurant'
    result << { units: 'meal', block: nil, max_hourly: 0.7, max_daily: 6.0, avg_day_unit: 0.7 }
  elsif building_type == 'Retail'
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "No SWH rules of thumbs for #{building_type}.")
  elsif building_type == 'SecondarySchool'
    result << { units: 'student', block: nil, max_hourly: 1.0, max_daily: 3.6, avg_day_unit: 1.8 }
  elsif building_type == 'StripMall'
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "No SWH rules of thumbs for #{building_type}.")
  elsif building_type == 'SuperMarket'
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "No SWH rules of thumbs for #{building_type}.")
  elsif building_type == 'Warehouse'
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "No SWH rules of thumbs for #{building_type}.")
  elsif ['SmallDataCenterLowITE', 'SmallDataCenterHighITE', 'LargeDataCenterLowITE', 'LargeDataCenterHighITE', 'Laboratory'].include? building_type
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "No SWH rules of thumbs for #{building_type}.")
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Didn't find expected building type. As a result can't determine hot water demand recommendations")
  end

  return result
end
model_find_climate_zone_set(model, climate_zone) click to toggle source

Helper method to find out which climate zone set contains a specific climate zone. Returns climate zone set name as String if success, nil if not found.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [String] climate zone set

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5042
def model_find_climate_zone_set(model, climate_zone)
  result = nil

  possible_climate_zone_sets = []
  standards_data['climate_zone_sets'].each do |climate_zone_set|
    if climate_zone_set['climate_zones'].include?(climate_zone)
      possible_climate_zone_sets << climate_zone_set['name']
    end
  end

  # Check the results
  if possible_climate_zone_sets.size.zero?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Cannot find a climate zone set containing #{climate_zone}.  Make sure to use ASHRAE standards with ASHRAE climate zones and DEER or CA Title 24 standards with CEC climate zones.")
  elsif possible_climate_zone_sets.size > 2
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Found more than 2 climate zone sets containing #{climate_zone}; will return last matching climate zone set.")
  end

  # Get the climate zone from the possible set
  climate_zone_set = model_get_climate_zone_set_from_list(model, possible_climate_zone_sets)

  # Check that a climate zone set was found
  if climate_zone_set.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Cannot find a climate zone set in standard #{template}")
  end

  return climate_zone_set
end
model_find_icc_iecc_2015_hot_water_demand(model, units_per_bldg, bedrooms_per_unit) click to toggle source

Returns average daily hot water consumption for residential buildings gal/day from ICC IECC 2015 Residential Standard Reference Design from Table R405.5.2(1)

@param model [OpenStudio::Model::Model] OpenStudio model object @param units_per_bldg [Double] number of units in the building @param bedrooms_per_unit [Double] number of bedrooms per unit @return [Double] gal/day

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4914
def model_find_icc_iecc_2015_hot_water_demand(model, units_per_bldg, bedrooms_per_unit)
  swh_gal_per_day = units_per_bldg * (30.0 + (10.0 * bedrooms_per_unit))

  return swh_gal_per_day
end
model_find_icc_iecc_2015_internal_loads(model, units_per_bldg, bedrooms_per_unit) click to toggle source

Returns average daily internal loads for residential buildings from Table R405.5.2(1)

@param model [OpenStudio::Model::Model] OpenStudio model object @param units_per_bldg [Double] number of units in the building @param bedrooms_per_unit [Double] number of bedrooms per unit @return [Hash] mech_vent_cfm, infiltration_ach, igain_btu_per_day, internal_mass_lbs

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4926
def model_find_icc_iecc_2015_internal_loads(model, units_per_bldg, bedrooms_per_unit)
  # get total and conditioned floor area
  total_floor_area = model.getBuilding.floorArea
  if model.getBuilding.conditionedFloorArea.is_initialized
    conditioned_floor_area = model.getBuilding.conditionedFloorArea.get
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', 'Cannot find conditioned floor area, will use total floor area.')
    conditioned_floor_area = total_floor_area
  end

  # get climate zone value
  climate_zone = OpenstudioStandards::Weather.model_get_climate_zone(model)

  internal_loads = {}
  internal_loads['mech_vent_cfm'] = units_per_bldg * (0.01 * conditioned_floor_area + 7.5 * (bedrooms_per_unit + 1.0))
  internal_loads['infiltration_ach'] = if ['1A', '1B', '2A', '2B'].include? climate_zone_value
                                         5.0
                                       else
                                         3.0
                                       end
  internal_loads['igain_btu_per_day'] = units_per_bldg * (17_900.0 + 23.8 * conditioned_floor_area + 4104.0 * bedrooms_per_unit)
  internal_loads['internal_mass_lbs'] = total_floor_area * 8.0

  return internal_loads
end
model_find_object(hash_of_objects, search_criteria, capacity = nil, date = nil, area = nil, num_floors = nil, fan_motor_bhp = nil, volume = nil, capacity_per_volume = nil) click to toggle source

Method to search through a hash for an object that meets the desired search criteria, as passed via a hash. If capacity is supplied, the object will only be returned if the specified capacity is between the minimum_capacity and maximum_capacity values.

@param hash_of_objects [Hash] hash of objects to search through @param search_criteria [Hash] hash of search criteria @param capacity [Double] capacity of the object in question. If capacity is supplied,

the objects will only be returned if the specified capacity is between the minimum_capacity and maximum_capacity values.

@param date [<OpenStudio::Date>] date of the object in question. If date is supplied,

the objects will only be returned if the specified date is between the start_date and end_date.

@param area [Double] area of the object in question. If area is supplied,

the objects will only be returned if the specified area is between the minimum_area and maximum_area values.

@param num_floors [Double] capacity of the object in question. If num_floors is supplied,

the objects will only be returned if the specified num_floors is between the minimum_floors and maximum_floors values.

@return [Hash] Return tbe first matching object hash if successful, nil if not. @example Find the motor that meets these size criteria

search_criteria = {
'template' => template,
'number_of_poles' => 4.0,
'type' => 'Enclosed',
}
motor_properties = self.model.find_object(motors, search_criteria, capacity: 2.5)
# File lib/openstudio-standards/standards/Standards.Model.rb, line 2554
def model_find_object(hash_of_objects, search_criteria, capacity = nil, date = nil, area = nil, num_floors = nil, fan_motor_bhp = nil, volume = nil, capacity_per_volume = nil)
  matching_objects = model_find_objects(hash_of_objects, search_criteria, capacity, date, area, num_floors, fan_motor_bhp, volume, capacity_per_volume)

  # Check the number of matching objects found
  if matching_objects.size.zero?
    desired_object = nil
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Find object search criteria returned no results. Search criteria: #{search_criteria}. Called from #{caller(0)[1]}")
  elsif matching_objects.size == 1
    desired_object = matching_objects[0]
  else
    desired_object = matching_objects[0]
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Find object search criteria returned #{matching_objects.size} results, the first one will be returned. Called from #{caller(0)[1]}. \n Search criteria: \n #{search_criteria}, capacity = #{capacity} \n  All results: \n #{matching_objects.join("\n")}")
  end

  return desired_object
end
model_find_objects(hash_of_objects, search_criteria, capacity = nil, date = nil, area = nil, num_floors = nil, fan_motor_bhp = nil, volume = nil, capacity_per_volume = nil) click to toggle source

Method to search through a hash for the objects that meets the desired search criteria, as passed via a hash. Returns an Array (empty if nothing found) of matching objects.

@param hash_of_objects [Hash] hash of objects to search through @param search_criteria [Hash] hash of search criteria @param capacity [Double] capacity of the object in question. If capacity is supplied,

the objects will only be returned if the specified capacity is between the minimum_capacity and maximum_capacity values.

@param date [<OpenStudio::Date>] date of the object in question. If date is supplied,

the objects will only be returned if the specified date is between the start_date and end_date.

@param area [Double] area of the object in question. If area is supplied,

the objects will only be returned if the specified area is between the minimum_area and maximum_area values.

@param num_floors [Double] capacity of the object in question. If num_floors is supplied,

the objects will only be returned if the specified num_floors is between the minimum_floors and maximum_floors values.

@param fan_motor_bhp [Double] fan motor brake horsepower. @param volume [Double] Equipment storage capacity in gallons. @param capacity_per_volume [Double] Equipment capacity per storage capacity in Btu/h/gal. @return [Array] returns an array of hashes, one hash per object. Array is empty if no results. @example Find all the schedule rules that match the name

rules = model_find_objects(standards_data['schedules'], 'name' => schedule_name)
if rules.size.zero?
  OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Cannot find data for schedule: #{schedule_name}, will not be created.")
  return false
end
# File lib/openstudio-standards/standards/Standards.Model.rb, line 2369
def model_find_objects(hash_of_objects, search_criteria, capacity = nil, date = nil, area = nil, num_floors = nil, fan_motor_bhp = nil, volume = nil, capacity_per_volume = nil)
  matching_objects = []
  if hash_of_objects.is_a?(Hash) && hash_of_objects.key?('table')
    hash_of_objects = hash_of_objects['table']
  end

  # Compare each of the objects against the search criteria
  raise("This is not a table #{hash_of_objects}") unless hash_of_objects.respond_to?(:each)

  hash_of_objects.each do |object|
    meets_all_search_criteria = true
    search_criteria.each do |key, value|
      # Don't check non-existent search criteria
      next unless object.key?(key)

      # Stop as soon as one of the search criteria is not met
      # 'Any' is a special key that matches anything
      unless object[key] == value || object[key] == 'Any'
        meets_all_search_criteria = false
        break
      end
    end
    # Skip objects that don't meet all search criteria
    next unless meets_all_search_criteria

    # If made it here, object matches all search criteria
    matching_objects << object
  end

  # If capacity was specified, narrow down the matching objects
  unless capacity.nil?
    # Skip objects that don't have fields for minimum_capacity and maximum_capacity
    matching_objects = matching_objects.reject { |object| !object.key?('minimum_capacity') || !object.key?('maximum_capacity') }

    # Skip objects that don't have values specified for minimum_capacity and maximum_capacity
    matching_objects = matching_objects.reject { |object| object['minimum_capacity'].nil? || object['maximum_capacity'].nil? }

    # Round up if capacity is an integer
    if capacity == capacity.round
      capacity += (capacity * 0.01)
    end
    # Skip objects whose the minimum capacity is below or maximum capacity above the specified capacity
    matching_capacity_objects = matching_objects.reject { |object| capacity.to_f <= object['minimum_capacity'].to_f || capacity.to_f > object['maximum_capacity'].to_f }

    # If no object was found, round the capacity down in case the number fell between the limits in the json file.
    if matching_capacity_objects.size.zero?
      capacity *= 0.99
      # Skip objects whose minimum capacity is below or maximum capacity above the specified capacity
      matching_objects = matching_objects.reject { |object| capacity.to_f <= object['minimum_capacity'].to_f || capacity.to_f > object['maximum_capacity'].to_f }
    else
      matching_objects = matching_capacity_objects
    end
  end

  # If volume was specified, narrow down the matching objects
  unless volume.nil?
    # Skip objects that don't have fields for minimum_storage and maximum_storage
    matching_objects = matching_objects.reject { |object| !object.key?('minimum_storage') || !object.key?('maximum_storage') }

    # Skip objects that don't have values specified for minimum_storage and maximum_storage
    matching_objects = matching_objects.reject { |object| object['minimum_storage'].nil? || object['maximum_storage'].nil? }

    # Skip objects whose the minimum volume is below or maximum volume above the specified volume
    matching_volume_objects = matching_objects.reject { |object| volume.to_f < object['minimum_storage'].to_f || volume.to_f > object['maximum_storage'].to_f }

    # If no object was found, round the volume down in case the number fell between the limits in the json file.
    if matching_volume_objects.size.zero?
      volume *= 0.99
      # Skip objects whose minimum volume is below or maximum volume above the specified volume
      matching_objects = matching_objects.reject { |object| volume.to_f <= object['minimum_storage'].to_f || volume.to_f >= object['maximum_storage'].to_f }
    else
      matching_objects = matching_volume_objects
    end
  end

  # If capacity_per_volume was specified, narrow down the matching objects
  unless capacity_per_volume.nil?
    # Skip objects that don't have fields for minimum_capacity_per_storage and maximum_capacity_per_storage
    matching_objects = matching_objects.reject { |object| !object.key?('minimum_capacity_per_storage') || !object.key?('maximum_capacity_per_storage') }

    # Skip objects that don't have values specified for minimum_capacity_per_storage and maximum_capacity_per_storage
    matching_objects = matching_objects.reject { |object| object['minimum_capacity_per_storage'].nil? || object['maximum_capacity_per_storage'].nil? }

    # Skip objects whose the minimum capacity_per_volume is below or maximum capacity_per_volume above the specified capacity_per_volume
    matching_capacity_per_volume_objects = matching_objects.reject { |object| capacity_per_volume.to_f <= object['minimum_capacity_per_storage'].to_f || capacity_per_volume.to_f >= object['maximum_capacity_per_storage'].to_f }

    # If no object was found, round the volume down in case the number fell between the limits in the json file.
    if matching_capacity_per_volume_objects.size.zero?
      capacity_per_volume *= 0.99
      # Skip objects whose minimum capacity_per_volume is below or maximum capacity_per_volume above the specified capacity_per_volume
      matching_objects = matching_objects.reject { |object| capacity_per_volume.to_f <= object['minimum_capacity_per_storage'].to_f || capacity_per_volume.to_f >= object['maximum_capacity_per_storage'].to_f }
    else
      matching_objects = matching_capacity_per_volume_objects
    end
  end

  # If fan_motor_bhp was specified, narrow down the matching objects
  unless fan_motor_bhp.nil?
    # Skip objects that don't have fields for minimum_capacity and maximum_capacity
    matching_objects = matching_objects.reject { |object| !object.key?('minimum_capacity') || !object.key?('maximum_capacity') }

    # Skip objects that don't have values specified for minimum_capacity and maximum_capacity
    matching_objects = matching_objects.reject { |object| object['minimum_capacity'].nil? || object['maximum_capacity'].nil? }

    # Skip objects whose the minimum capacity is below or maximum capacity above the specified fan_motor_bhp
    matching_capacity_objects = matching_objects.reject { |object| fan_motor_bhp.to_f <= object['minimum_capacity'].to_f || fan_motor_bhp.to_f > object['maximum_capacity'].to_f }

    # Filter based on motor type
    matching_capacity_objects = matching_capacity_objects.select { |object| object['type'].downcase == search_criteria['type'].downcase } if search_criteria.keys.include?('type')

    # If no object was found, round the fan_motor_bhp down in case the number fell between the limits in the json file.
    if matching_capacity_objects.size.zero?
      fan_motor_bhp *= 0.99
      # Skip objects whose minimum capacity is below or maximum capacity above the specified fan_motor_bhp
      matching_objects = matching_objects.reject { |object| fan_motor_bhp.to_f <= object['minimum_capacity'].to_f || fan_motor_bhp.to_f > object['maximum_capacity'].to_f }
    else
      matching_objects = matching_capacity_objects
    end
  end

  # If date was specified, narrow down the matching objects
  unless date.nil?
    # Skip objects that don't have fields for start_date and end_date
    matching_objects = matching_objects.reject { |object| !object.key?('start_date') || !object.key?('end_date') }

    # Skip objects whose start date is earlier than the specified date
    matching_objects = matching_objects.reject { |object| date <= Date.parse(object['start_date']) }

    # Skip objects whose end date is later than the specified date
    matching_objects = matching_objects.reject { |object| date > Date.parse(object['end_date']) }
  end

  # If area was specified, narrow down the matching objects
  unless area.nil?
    # Skip objects that don't have fields for minimum_area and maximum_area
    matching_objects = matching_objects.reject { |object| !object.key?('minimum_area') || !object.key?('maximum_area') }

    # Skip objects that don't have values specified for minimum_area and maximum_area
    matching_objects = matching_objects.reject { |object| object['minimum_area'].nil? || object['maximum_area'].nil? }

    # Skip objects whose minimum area is below or maximum area is above area
    matching_objects = matching_objects.reject { |object| area.to_f <= object['minimum_area'].to_f || area.to_f > object['maximum_area'].to_f }
  end

  # If area was specified, narrow down the matching objects
  unless num_floors.nil?
    # Skip objects that don't have fields for minimum_floors and maximum_floors
    matching_objects = matching_objects.reject { |object| !object.key?('minimum_floors') || !object.key?('maximum_floors') }

    # Skip objects that don't have values specified for minimum_floors and maximum_floors
    matching_objects = matching_objects.reject { |object| object['minimum_floors'].nil? || object['maximum_floors'].nil? }

    # Skip objects whose minimum floors is below or maximum floors is above num_floors
    matching_objects = matching_objects.reject { |object| num_floors.to_f < object['minimum_floors'].to_f || num_floors.to_f > object['maximum_floors'].to_f }
  end

  # Check the number of matching objects found
  if matching_objects.size.zero?
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Find objects search criteria returned no results. Search criteria: #{search_criteria}. Called from #{caller(0)[1]}.")
  end

  return matching_objects
end
model_find_prototype_floor_area(model, building_type) click to toggle source

Keep track of floor area for prototype buildings. This is used to calculate EUI’s to compare against non prototype buildings Areas taken from scorecard Excel Files

@param model [OpenStudio::Model::Model] OpenStudio model object @param building_type [String] the building type @return [Double] floor area (m^2) of prototype building for building type passed in.

Returns nil if unexpected building type
# File lib/openstudio-standards/standards/Standards.Model.rb, line 3873
def model_find_prototype_floor_area(model, building_type)
  if building_type == 'FullServiceRestaurant' # 5502 ft^2
    result = 511
  elsif building_type == 'Hospital' # 241,410 ft^2 (including basement)
    result = 22_422
  elsif building_type == 'LargeHotel' # 122,132 ft^2
    result = 11_345
  elsif building_type == 'LargeOffice' # 498,600 ft^2
    result = 46_320
  elsif building_type == 'MediumOffice' # 53,600 ft^2
    result = 4982
  elsif building_type == 'LargeOfficeDetailed' # 498,600 ft^2
    result = 46_320
  elsif building_type == 'MediumOfficeDetailed' # 53,600 ft^2
    result = 4982
  elsif building_type == 'MidriseApartment' # 33,700 ft^2
    result = 3135
  elsif building_type == 'Office'
    result = nil
    # @todo there shouldn't be a prototype building for this
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', 'Measures calling this should choose between SmallOffice, MediumOffice, and LargeOffice')
  elsif building_type == 'Outpatient' # 40.950 ft^2
    result = 3804
  elsif building_type == 'PrimarySchool' # 73,960 ft^2
    result = 6871
  elsif building_type == 'QuickServiceRestaurant' # 2500 ft^2
    result = 232
  elsif building_type == 'Retail' # 24,695 ft^2
    result = 2294
  elsif building_type == 'SecondarySchool' # 210,900 ft^2
    result = 19_592
  elsif building_type == 'SmallHotel' # 43,200 ft^2
    result = 4014
  elsif building_type == 'SmallOffice' # 5500 ft^2
    result = 511
  elsif building_type == 'SmallOfficeDetailed' # 5500 ft^2
    result = 511
  elsif building_type == 'StripMall' # 22,500 ft^2
    result = 2090
  elsif building_type == 'SuperMarket' # 45,002 ft2 (from legacy reference idf file)
    result = 4181
  elsif building_type == 'Warehouse' # 49,495 ft^2 (legacy ref shows 52,045, but I wil calc using 49,495)
    result = 4595
  elsif building_type == 'SmallDataCenterLowITE' || building_type == 'SmallDataCenterHighITE'  # 600 ft^2
    result = 56
  elsif building_type == 'LargeDataCenterLowITE' || building_type == 'LargeDataCenterHighITE'  # 6000 ft^2
    result = 557
  elsif building_type == 'Laboratory' # 90000 ft^2
    result = 8361
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Didn't find expected building type. As a result can't determine floor prototype floor area")
    result = nil
  end

  return result
end
model_find_target_eui(model) click to toggle source

User needs to pass in template as string. The building type and climate zone will come from the model. If the building type or ASHRAE climate zone is not set in the model this will return nil If the lookup doesn’t find matching simulation results this wil return nil

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Double] EUI (MJ/m^2) for target template for given OSM. Returns nil if can’t calculate EUI

# File lib/openstudio-standards/standards/Standards.Model.rb, line 3992
def model_find_target_eui(model)
  building_data = model_get_building_properties(model)
  climate_zone = building_data['climate_zone']
  building_type = building_data['building_type']
  building_template = building_data['standards_template']

  # look up results
  target_consumption = model_process_results_for_datapoint(model, climate_zone, building_type, lkp_template: building_template)

  # lookup target floor area for prototype buildings
  target_floor_area = model_find_prototype_floor_area(model, building_type)

  if target_consumption['total_legacy_energy_val'] > 0
    if target_floor_area > 0
      result = target_consumption['total_legacy_energy_val'] / target_floor_area
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', 'Cannot find prototype building floor area')
      result = nil
    end
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Cannot find target results for #{climate_zone},#{building_type},#{template}")
    result = nil # couldn't calculate EUI consumpiton lookup failed
  end

  return result
end
model_find_target_eui_by_end_use(model) click to toggle source

User needs to pass in template as string. The building type and climate zone will come from the model. If the building type or ASHRAE climate zone is not set in the model this will return nil If the lookup doesn’t find matching simulation results this wil return nil

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Hash] EUI (MJ/m^2) This will return a hash of end uses. key is end use, value is eui

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4026
def model_find_target_eui_by_end_use(model)
  building_data = model_get_building_properties(model)
  climate_zone = building_data['climate_zone']
  building_type = building_data['building_type']
  building_template = building_data['standards_template']

  # look up results
  target_consumption = model_process_results_for_datapoint(model, climate_zone, building_type, lkp_template: building_template)

  # lookup target floor area for prototype buildings
  target_floor_area = model_find_prototype_floor_area(model, building_type)

  if target_consumption['total_legacy_energy_val'] > 0
    if target_floor_area > 0
      result = {}
      target_consumption['total_energy_by_end_use'].each do |end_use, consumption|
        result[end_use] = consumption / target_floor_area
      end
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', 'Cannot find prototype building floor area')
      result = nil
    end
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Cannot find target results for #{climate_zone},#{building_type},#{template}")
    result = nil # couldn't calculate EUI consumpiton lookup failed
  end

  return result
end
model_find_water_heater_capacity_volume_and_parasitic(model, water_use_equipment_array, storage_to_cap_ratio_gal_to_kbtu_per_hr: 1.0, htg_eff: 0.8, inlet_temp_f: 40.0, target_temp_f: 140.0, peak_flow_fraction: 1.0) click to toggle source

Use rules from DOE Prototype Building documentation to determine water heater capacity, volume, pipe dump losses, and pipe thermal losses.

@param model [OpenStudio::Model::Model] OpenStudio model object @param water_use_equipment_array [Array] array of water use equipment objects that will be using this water heater @param storage_to_cap_ratio_gal_to_kbtu_per_hr [Double] storage volume gal to kBtu/hr of capacity @param htg_eff [Double] water heater thermal efficiency, fraction @param inlet_temp_f [Double] inlet cold water temperature, degrees Fahrenheit @param target_temp_f [Double] target supply water temperature from the tank, degrees Fahrenheit @return [Hash] hash with values needed to size water heater made with downstream method

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.swh.rb, line 527
def model_find_water_heater_capacity_volume_and_parasitic(model,
                                                          water_use_equipment_array,
                                                          storage_to_cap_ratio_gal_to_kbtu_per_hr: 1.0,
                                                          htg_eff: 0.8,
                                                          inlet_temp_f: 40.0,
                                                          target_temp_f: 140.0,
                                                          peak_flow_fraction: 1.0)
  # A.1.4 Total Storage Volume and Water Heater Capacity of PrototypeModelEnhancements_2014_0.pdf shows 1 gallon of storage to 1 kBtu/h of capacity

  water_heater_sizing = {}

  # Get the maximum flow rates for all pieces of water use equipment
  adjusted_max_flow_rates_gal_per_hr = [] # gallons per hour
  water_use_equipment_array.sort.each do |water_use_equip|
    water_use_equip_sch = water_use_equip.flowRateFractionSchedule
    next if water_use_equip_sch.empty?

    water_use_equip_sch = water_use_equip_sch.get
    if water_use_equip_sch.to_ScheduleRuleset.is_initialized
      water_use_equip_sch = water_use_equip_sch.to_ScheduleRuleset.get
      max_sch_value = OpenstudioStandards::Schedules.schedule_ruleset_get_min_max(water_use_equip_sch)['max']
    elsif water_use_equip_sch.to_ScheduleConstant.is_initialized
      water_use_equip_sch = water_use_equip_sch.to_ScheduleConstant.get
      max_sch_value = OpenstudioStandards::Schedules.schedule_constant_get_min_max(water_use_equip_sch)['max']
    elsif water_use_equip_sch.to_ScheduleCompact.is_initialized
      water_use_equip_sch = water_use_equip_sch.to_ScheduleCompact.get
      max_sch_value = OpenstudioStandards::Schedules.schedule_compact_get_min_max(water_use_equip_sch)['max']
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "The peak flow rate fraction for #{water_use_equip_sch.name} could not be determined, assuming 1 for water heater sizing purposes.")
      max_sch_value = 1.0
    end

    # Get peak flow rate from water use equipment definition
    peak_flow_rate_m3_per_s = water_use_equip.waterUseEquipmentDefinition.peakFlowRate

    # Calculate adjusted flow rate based on the peak fraction found in the flow rate fraction schedule
    adjusted_peak_flow_rate_m3_per_s = max_sch_value * peak_flow_rate_m3_per_s
    adjusted_max_flow_rates_gal_per_hr << OpenStudio.convert(adjusted_peak_flow_rate_m3_per_s, 'm^3/s', 'gal/hr').get
  end

  # Sum gph values from water use equipment to use in formula
  total_adjusted_flow_rate_gal_per_hr = adjusted_max_flow_rates_gal_per_hr.inject(:+)

  # Calculate capacity based on analysis of combined water use equipment maximum flow rates and schedules
  # Max gal/hr * 8.4 lb/gal * 1 Btu/lb F * (120F - 40F)/0.8 = Btu/hr
  water_heater_capacity_btu_per_hr = peak_flow_fraction * total_adjusted_flow_rate_gal_per_hr * 8.4 * 1.0 * (target_temp_f - inlet_temp_f) / htg_eff
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Capacity of #{water_heater_capacity_btu_per_hr.round} Btu/hr = #{peak_flow_fraction} peak fraction * #{total_adjusted_flow_rate_gal_per_hr.round} gal/hr * 8.4 lb/gal * 1.0 Btu/lb F * (#{target_temp_f.round} - #{inlet_temp_f.round} deltaF / #{htg_eff} htg eff).")
  water_heater_capacity_m3_per_s = OpenStudio.convert(water_heater_capacity_btu_per_hr, 'Btu/hr', 'W').get

  # Calculate volume based on capacity
  # Default assumption is 1 gal of volume per 1 kBtu/hr of heating capacity
  water_heater_capacity_kbtu_per_hr = OpenStudio.convert(water_heater_capacity_btu_per_hr, 'Btu/hr', 'kBtu/hr').get
  water_heater_volume_gal = water_heater_capacity_kbtu_per_hr * storage_to_cap_ratio_gal_to_kbtu_per_hr
  # increase tank size to 40 galons if calculated value is smaller
  water_heater_volume_gal = 40.0 if water_heater_volume_gal < 40.0 # gal
  water_heater_volume_m3 = OpenStudio.convert(water_heater_volume_gal, 'gal', 'm^3').get

  # Populate return hash
  water_heater_sizing[:water_heater_capacity] = water_heater_capacity_m3_per_s
  water_heater_sizing[:water_heater_volume] = water_heater_volume_m3

  return water_heater_sizing
end
model_get_baseline_system_type_by_zone(model, climate_zone, custom = nil) click to toggle source

Looks through the model and creates an hash of what the baseline system type should be for each zone.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param custom [String] custom fuel type @return [Hash] keys are zones, values are system type strings

PTHP, PTAC, PSZ_AC, PSZ_HP, PVAV_Reheat, PVAV_PFP_Boxes,
VAV_Reheat, VAV_PFP_Boxes, Gas_Furnace, Electric_Furnace
# File lib/openstudio-standards/standards/Standards.Model.rb, line 1893
def model_get_baseline_system_type_by_zone(model, climate_zone, custom = nil)
  zone_to_sys_type = {}

  # Get the groups of zones that define the
  # baseline HVAC systems for later use.
  # This must be done before removing the HVAC systems
  # because it requires knowledge of proposed HVAC fuels.
  sys_groups = model_prm_baseline_system_groups(model, custom)

  # Assign building stories to spaces in the building
  # where stories are not yet assigned.
  OpenstudioStandards::Geometry.model_assign_spaces_to_building_stories(model)

  # Determine the baseline HVAC system type for each of
  # the groups of zones and add that system type.
  sys_groups.each do |sys_group|
    # Determine the primary baseline system type
    pri_system_type = model_prm_baseline_system_type(model, climate_zone, sys_group, custom)[0]

    # Record the zone-by-zone system type assignments
    case pri_system_type
      when 'PTAC', 'PTHP', 'PSZ_AC', 'PSZ_HP', 'Gas_Furnace', 'Electric_Furnace'

        sys_group['zones'].each do |zone|
          zone_to_sys_type[zone] = pri_system_type
        end

      when 'PVAV_Reheat', 'PVAV_PFP_Boxes', 'VAV_Reheat', 'VAV_PFP_Boxes'

        # Determine the secondary system type
        sec_system_type = nil
        case pri_system_type
        when 'PVAV_Reheat', 'VAV_Reheat'
          sec_system_type = 'PSZ_AC'
        when 'PVAV_PFP_Boxes', 'VAV_PFP_Boxes'
          sec_system_type = 'PSZ_HP'
        end

        # Group zones by story
        story_zone_lists = OpenstudioStandards::Geometry.model_group_thermal_zones_by_building_story(model, sys_group['zones'])
        # For the array of zones on each story,
        # separate the primary zones from the secondary zones.
        # Add the baseline system type to the primary zones
        # and add the suplemental system type to the secondary zones.
        story_zone_lists.each do |story_group|
          # Differentiate primary and secondary zones
          pri_sec_zone_lists = model_differentiate_primary_secondary_thermal_zones(model, story_group)
          # Record the primary zone system types
          pri_sec_zone_lists['primary'].each do |zone|
            zone_to_sys_type[zone] = pri_system_type
          end
          # Record the secondary zone system types
          pri_sec_zone_lists['secondary'].each do |zone|
            zone_to_sys_type[zone] = sec_system_type
          end
        end
    end
  end

  return zone_to_sys_type
end
model_get_building_properties(model, remap_office = true) click to toggle source

This is used by other methods to get the climate zone and building type from a model. It has logic to break office into small, medium or large based on building area that can be turned off

@param model [OpenStudio::Model::Model] OpenStudio model object @param remap_office [Boolean] re-map small office or leave it alone @return [Hash] key for climate zone, building type, and standards template. All values are strings.

# File lib/openstudio-standards/standards/Standards.Model.rb, line 3937
def model_get_building_properties(model, remap_office = true)
  # get climate zone from model
  climate_zone = OpenstudioStandards::Weather.model_get_climate_zone(model)

  # get building type from model
  building_type = ''
  if model.getBuilding.standardsBuildingType.is_initialized
    building_type = model.getBuilding.standardsBuildingType.get
  end

  # map office building type to small medium or large
  if building_type == 'Office' && remap_office
    open_studio_area = model.getBuilding.floorArea
    building_type = model_remap_office(model, open_studio_area)
  end

  # get standards template
  if model.getBuilding.standardsTemplate.is_initialized
    standards_template = model.getBuilding.standardsTemplate.get
  end

  results = {}
  results['climate_zone'] = climate_zone
  results['building_type'] = building_type
  results['standards_template'] = standards_template

  return results
end
model_get_climate_zone_set_from_list(model, possible_climate_zone_sets) click to toggle source

Determine which climate zone to use. Defaults to the least specific climate zone set. For example, 2A and 2 both contain 2A, so use 2.

@param model [OpenStudio::Model::Model] OpenStudio model object @param possible_climate_zone_sets [Array] climate zone sets @return [String] climate zone ses

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5077
def model_get_climate_zone_set_from_list(model, possible_climate_zone_sets)
  climate_zone_set = possible_climate_zone_sets.max
  return climate_zone_set
end
model_get_construction_properties(model, intended_surface_type, standards_construction_type, building_category, climate_zone = nil) click to toggle source

Returns standards data for selected construction

@param model [OpenStudio::Model::Model] OpenStudio model object @param intended_surface_type [String] the surface type @param standards_construction_type [String] the type of construction @param building_category [String] the type of building @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Hash] hash of construction properties

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4239
def model_get_construction_properties(model, intended_surface_type, standards_construction_type, building_category, climate_zone = nil)
  # get climate_zone_set
  climate_zone = model_get_building_properties(model)['climate_zone'] if climate_zone.nil?
  climate_zone_set = model_find_climate_zone_set(model, climate_zone)

  # populate search hash
  search_criteria = {
    'template' => template,
    'climate_zone_set' => climate_zone_set,
    'intended_surface_type' => intended_surface_type,
    'standards_construction_type' => standards_construction_type,
    'building_category' => building_category
  }

  # switch to use this but update test in standards and measures to load this outside of the method
  construction_properties = model_find_object(standards_data['construction_properties'], search_criteria)

  if !construction_properties
    # Search again use climate zone (e.g. 3) instead of sub-climate zone (3A)
    search_criteria['climate_zone_set'] = climate_zone_set[0..-2]
    construction_properties = model_find_object(standards_data['construction_properties'], search_criteria)
  end

  return construction_properties
end
model_get_construction_set(building_type, space_type = nil) click to toggle source

Returns standards data for selected construction set

@param building_type [String] the type of building @param space_type [String] space type within the building type. Typically nil. @return [Hash] hash of construction set data

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4270
def model_get_construction_set(building_type, space_type = nil)
  # populate search hash
  search_criteria = {
    'template' => template,
    'building_type' => building_type,
    'space_type' => space_type
  }

  # Search construction sets table for the exterior wall building category and construction type
  construction_set_data = model_find_object(standards_data['construction_sets'], search_criteria)

  return construction_set_data
end
model_get_district_heating_zones(model) click to toggle source

Before deleting proposed HVAC components, determine for each zone if it has district heating @return [Hash] Hash of boolean with zone name as key

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1069
def model_get_district_heating_zones(model)
  has_district_hash = {}
  model.getThermalZones.sort.each do |zone|
    has_district_hash['building'] = false

    # error if HVACComponent heating fuels method is not available
    if model.version < OpenStudio::VersionString.new('3.6.0')
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Standards.Model', 'Required HVACComponent method .heatingFuelTypes is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
    end

    htg_fuels = zone.heatingFuelTypes.map(&:valueName)
    if htg_fuels.include?('DistrictHeating') || htg_fuels.include?('DistrictHeatingWater') || htg_fuels.include?('DistrictHeatingSteam')
      has_district_hash[zone.name] = true
      has_district_hash['building'] = true
    else
      has_district_hash[zone.name] = false
    end
  end
  return has_district_hash
end
model_get_lookup_name(building_type) click to toggle source

Get the name of the building type used in lookups

@param building_type [String] the building type @return [String] returns the lookup name as a string @todo Unify the lookup names and eliminate this method

# File lib/openstudio-standards/standards/standard.rb, line 53
def model_get_lookup_name(building_type)
  lookup_name = building_type
  case building_type
  when 'SmallOffice'
    lookup_name = 'Office'
  when 'SmallOfficeDetailed'
    lookup_name = 'Office'
  when 'MediumOffice'
    lookup_name = 'Office'
  when 'MediumOfficeDetailed'
    lookup_name = 'Office'
  when 'LargeOffice'
    lookup_name = 'Office'
  when 'LargeOfficeDetailed'
    lookup_name = 'Office'
  when 'RetailStandalone'
    lookup_name = 'Retail'
  when 'RetailStripmall'
    lookup_name = 'StripMall'
  when 'Office'
    lookup_name = 'Office'
  end
  return lookup_name
end
model_get_or_add_ambient_water_loop(model) click to toggle source

Get the existing ambient water loop in the model or add a new one if there isn’t one already.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::PlantLoop] the ambient water loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6780
def model_get_or_add_ambient_water_loop(model)
  # retrieve the existing hot water loop or add a new one if necessary
  ambient_water_loop = if model.getPlantLoopByName('Ambient Loop').is_initialized
                         model.getPlantLoopByName('Ambient Loop').get
                       else
                         model_add_district_ambient_loop(model)
                       end
  return ambient_water_loop
end
model_get_or_add_chilled_water_loop(model, cool_fuel, chilled_water_loop_cooling_type: 'WaterCooled') click to toggle source

Get the existing chilled water loop in the model or add a new one if there isn’t one already.

@param model [OpenStudio::Model::Model] OpenStudio model object @param cool_fuel [String] the cooling fuel. Valid choices are Electricity, DistrictCooling, and HeatPump. @param chilled_water_loop_cooling_type [String] Archetype for chilled water loops, AirCooled or WaterCooled

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6221
def model_get_or_add_chilled_water_loop(model, cool_fuel,
                                        chilled_water_loop_cooling_type: 'WaterCooled')
  # retrieve the existing chilled water loop or add a new one if necessary
  chilled_water_loop = nil
  if model.getPlantLoopByName('Chilled Water Loop').is_initialized
    chilled_water_loop = model.getPlantLoopByName('Chilled Water Loop').get
  else
    case cool_fuel
    when 'DistrictCooling'
      chilled_water_loop = model_add_chw_loop(model,
                                              chw_pumping_type: 'const_pri',
                                              cooling_fuel: cool_fuel)
    when 'HeatPump'
      condenser_water_loop = model_get_or_add_ambient_water_loop(model)
      chilled_water_loop = model_add_chw_loop(model,
                                              chw_pumping_type: 'const_pri_var_sec',
                                              chiller_cooling_type: 'WaterCooled',
                                              chiller_compressor_type: 'Rotary Screw',
                                              condenser_water_loop: condenser_water_loop)
    when 'Electricity'
      if chilled_water_loop_cooling_type == 'AirCooled'
        chilled_water_loop = model_add_chw_loop(model,
                                                chw_pumping_type: 'const_pri',
                                                cooling_fuel: cool_fuel)
      else
        fan_type = model_cw_loop_cooling_tower_fan_type(model)
        condenser_water_loop = model_add_cw_loop(model,
                                                 cooling_tower_type: 'Open Cooling Tower',
                                                 cooling_tower_fan_type: 'Propeller or Axial',
                                                 cooling_tower_capacity_control: fan_type,
                                                 number_of_cells_per_tower: 1,
                                                 number_cooling_towers: 1)
        chilled_water_loop = model_add_chw_loop(model,
                                                chw_pumping_type: 'const_pri_var_sec',
                                                chiller_cooling_type: 'WaterCooled',
                                                chiller_compressor_type: 'Rotary Screw',
                                                condenser_water_loop: condenser_water_loop)
      end
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', 'No cool_fuel specified.')
    end
  end

  return chilled_water_loop
end
model_get_or_add_ground_hx_loop(model) click to toggle source

Get the existing ground heat exchanger loop in the model or add a new one if there isn’t one already.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::PlantLoop] the ground hx loop

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6794
def model_get_or_add_ground_hx_loop(model)
  # retrieve the existing ground HX loop or add a new one if necessary
  ground_hx_loop = if model.getPlantLoopByName('Ground HX Loop').is_initialized
                     model.getPlantLoopByName('Ground HX Loop').get
                   else
                     model_add_ground_hx_loop(model)
                   end
  return ground_hx_loop
end
model_get_or_add_heat_pump_loop(model, heat_fuel, cool_fuel, heat_pump_loop_cooling_type: 'EvaporativeFluidCooler') click to toggle source

Get the existing heat pump loop in the model or add a new one if there isn’t one already.

@param model [OpenStudio::Model::Model] OpenStudio model object @param heat_fuel [String] the heating fuel. Valid choices are NaturalGas, Electricity, DistrictHeating, DistrictHeatingWater, DistrictHeatingSteam @param cool_fuel [String] the cooling fuel. Valid choices are Electricity and DistrictCooling. @param heat_pump_loop_cooling_type [String] the type of cooling equipment if not DistrictCooling.

Valid options are:
CoolingTower, CoolingTowerSingleSpeed, CoolingTowerTwoSpeed, CoolingTowerVariableSpeed,
FluidCooler, FluidCoolerSingleSpeed, FluidCoolerTwoSpeed,
EvaporativeFluidCooler, EvaporativeFluidCoolerSingleSpeed, EvaporativeFluidCoolerTwoSpeed
# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6814
def model_get_or_add_heat_pump_loop(model, heat_fuel, cool_fuel,
                                    heat_pump_loop_cooling_type: 'EvaporativeFluidCooler')
  # retrieve the existing heat pump loop or add a new one if necessary
  heat_pump_loop = if model.getPlantLoopByName('Heat Pump Loop').is_initialized
                     model.getPlantLoopByName('Heat Pump Loop').get
                   else
                     model_add_hp_loop(model, heating_fuel: heat_fuel, cooling_fuel: cool_fuel, cooling_type: heat_pump_loop_cooling_type)
                   end
  return heat_pump_loop
end
model_get_or_add_hot_water_loop(model, heat_fuel, hot_water_loop_type: 'HighTemperature') click to toggle source

Get the existing hot water loop in the model or add a new one if there isn’t one already.

@param model [OpenStudio::Model::Model] OpenStudio model object @param heat_fuel [String] the heating fuel. Valid choices are NaturalGas, Electricity, DistrictHeating, DistrictHeatingWater, DistrictHeatingSteam @param hot_water_loop_type [String] Archetype for hot water loops

HighTemperature (180F supply) or LowTemperature (120F supply)
# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 6738
def model_get_or_add_hot_water_loop(model, heat_fuel,
                                    hot_water_loop_type: 'HighTemperature')
  if heat_fuel.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Hot water loop fuel type is nil.  Cannot add hot water loop.')
  end
  make_new_hot_water_loop = true
  hot_water_loop = nil
  # retrieve the existing hot water loop or add a new one if not of the correct type
  if model.getPlantLoopByName('Hot Water Loop').is_initialized
    hot_water_loop = model.getPlantLoopByName('Hot Water Loop').get
    design_loop_exit_temperature = hot_water_loop.sizingPlant.designLoopExitTemperature
    design_loop_exit_temperature = OpenStudio.convert(design_loop_exit_temperature, 'C', 'F').get
    # check that the loop is the correct archetype
    if hot_water_loop_type == 'HighTemperature'
      make_new_hot_water_loop = false if design_loop_exit_temperature > 130.0
    elsif hot_water_loop_type == 'LowTemperature'
      make_new_hot_water_loop = false if design_loop_exit_temperature <= 130.0
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Hot water loop archetype #{hot_water_loop_type} not recognized.")
    end
  end

  if make_new_hot_water_loop
    if hot_water_loop_type == 'HighTemperature'
      hot_water_loop = model_add_hw_loop(model, heat_fuel)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'New high temperature hot water loop created.')
    elsif hot_water_loop_type == 'LowTemperature'
      hot_water_loop = model_add_hw_loop(model, heat_fuel,
                                         dsgn_sup_wtr_temp: 120.0,
                                         boiler_draft_type: 'Condensing')
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'New low temperature hot water loop created.')
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Hot water loop archetype #{hot_water_loop_type} not recognized.")
    end
  end
  return hot_water_loop
end
model_is_hvac_autosized(model) click to toggle source

Determine whether or not the HVAC system in a model is autosized

As it is not realistic expectation to have all autosizable fields hard input, the method relies on autosizable field of prime movers (fans, pumps) and heating/cooling devices in the models (boilers, chillers, coils)

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if the HVAC system is likely autosized, false otherwise

# File lib/openstudio-standards/standards/Standards.Model.rb, line 673
def model_is_hvac_autosized(model)
  is_hvac_autosized = false
  model.modelObjects.each do |obj|
    obj_type = obj.iddObjectType.valueName.to_s.downcase

    # Check if the object needs to be checked for autosizing
    obj_to_be_checked_for_autosizing = false
    if obj_type.include?('chiller') || obj_type.include?('boiler') || obj_type.include?('coil') || obj_type.include?('fan') || obj_type.include?('pump') || obj_type.include?('waterheater')
      if !obj_type.include?('controller')
        obj_to_be_checked_for_autosizing = true
      end
    end

    # Check for autosizing
    if obj_to_be_checked_for_autosizing
      casted_obj = model_cast_model_object(obj)

      next if casted_obj.nil?

      casted_obj.methods.each do |method|
        if method.to_s.include?('is') && method.to_s.include?('Autosized')
          if casted_obj.public_send(method) == true
            is_hvac_autosized = true
            OpenStudio.logFree(OpenStudio::Info, 'prm.log', "The #{method.to_s.sub('is', '').sub('Autosized', '').sub(':', '')} field of the #{obj_type} named #{casted_obj.name} is autosized. It should be hard sized.")
          end
        end
      end
    end
  end

  return is_hvac_autosized
end
model_legacy_results_by_end_use_and_fuel_type(model, climate_zone, building_type, run_type, lkp_template: nil) click to toggle source

Find the legacy simulation results from a CSV of previously created results.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param building_type [String] the building type @param run_type [String] design day is dd-only, otherwise annual run @param lkp_template [String] The standards template, e.g.‘90.1-2013’ @return [Hash] a hash of results for each fuel, where the keys are in the form ‘End Use|Fuel Type’,

e.g. Heating|Electricity, Exterior Equipment|Water.  All end use/fuel type combos are present,
with values of 0.0 if none of this end use/fuel type combo was used by the simulation.
Returns nil if the legacy results couldn't be found.
# File lib/openstudio-standards/standards/Standards.Model.rb, line 3747
def model_legacy_results_by_end_use_and_fuel_type(model, climate_zone, building_type, run_type, lkp_template: nil)
  # Load the legacy idf results CSV file into a ruby hash
  top_dir = File.expand_path('../../..', File.dirname(__FILE__))
  standards_data_dir = "#{top_dir}/data/standards"
  temp = ''
  # Run differently depending on whether running from embedded filesystem in OpenStudio CLI or not
  if __dir__[0] == ':' # Running from OpenStudio CLI
    # load file from embedded files
    if run_type == 'dd-only'
      temp = load_resource_relative('../../../data/standards/test_performance_expected_dd_results.csv', 'r:UTF-8')
    else
      temp = load_resource_relative('../../../data/standards/legacy_idf_results.csv', 'r:UTF-8')
    end
  else
    # loaded gem from system path
    if run_type == 'dd-only'
      temp = File.read("#{standards_data_dir}/test_performance_expected_dd_results.csv")
    else
      temp = File.read("#{standards_data_dir}/legacy_idf_results.csv")
    end
  end
  legacy_idf_csv = CSV.new(temp, headers: true, converters: :all)
  legacy_idf_results = legacy_idf_csv.to_a.map(&:to_hash)

  if lkp_template.nil?
    lkp_template = template
  end

  # Get the results for this building
  search_criteria = {
    'Building Type' => building_type,
    'Template' => lkp_template,
    'Climate Zone' => climate_zone
  }
  energy_values = model_find_object(legacy_idf_results, search_criteria)
  if energy_values.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Could not find legacy simulation results for #{search_criteria}")
    return {}
  end

  return energy_values
end
model_make_name(model, climate_zone, building_type, spc_type) click to toggle source

Helper method to make a shortened version of a name that will be readable in a GUI.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param building_type [String] the building type @param spc_type [String] the space type @return [String] string of the model name

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4959
def model_make_name(model, climate_zone, building_type, spc_type)
  climate_zone = climate_zone.gsub('ClimateZone ', 'CZ')
  if climate_zone == 'CZ1-8'
    climate_zone = ''
  end

  if building_type == 'FullServiceRestaurant'
    building_type = 'FullSrvRest'
  elsif building_type == 'Hospital'
    building_type = 'Hospital'
  elsif building_type == 'LargeHotel'
    building_type = 'LrgHotel'
  elsif building_type == 'LargeOffice'
    building_type = 'LrgOffice'
  elsif building_type == 'MediumOffice'
    building_type = 'MedOffice'
  elsif building_type == 'MidriseApartment'
    building_type = 'MidApt'
  elsif building_type == 'HighriseApartment'
    building_type = 'HighApt'
  elsif building_type == 'Office'
    building_type = 'Office'
  elsif building_type == 'Outpatient'
    building_type = 'Outpatient'
  elsif building_type == 'PrimarySchool'
    building_type = 'PriSchl'
  elsif building_type == 'QuickServiceRestaurant'
    building_type = 'QckSrvRest'
  elsif building_type == 'Retail'
    building_type = 'Retail'
  elsif building_type == 'SecondarySchool'
    building_type = 'SecSchl'
  elsif building_type == 'SmallHotel'
    building_type = 'SmHotel'
  elsif building_type == 'SmallOffice'
    building_type = 'SmOffice'
  elsif building_type == 'StripMall'
    building_type = 'StMall'
  elsif building_type == 'SuperMarket'
    building_type = 'SpMarket'
  elsif building_type == 'Warehouse'
    building_type = 'Warehouse'
  elsif building_type == 'SmallDataCenterLowITE'
    building_type = 'SmDCLowITE'
  elsif building_type == 'SmallDataCenterHighITE'
    building_type = 'SmDCHighITE'
  elsif building_type == 'LargeDataCenterLowITE'
    building_type = 'LrgDCLowITE'
  elsif building_type == 'LargeDataCenterHighITE'
    building_type = 'LrgDCHighITE'
  elsif building_type == 'Laboratory'
    building_type = 'Laboratory'
  elsif building_type == 'TallBuilding'
    building_type = 'TallBldg'
  elsif building_type == 'SuperTallBuilding'
    building_type = 'SpTallBldg'
  end

  parts = [template]

  unless building_type.nil?
    parts << building_type
  end

  unless spc_type.nil?
    parts << spc_type
  end

  unless climate_zone.empty?
    parts << climate_zone
  end

  result = parts.join(' - ')

  return result
end
model_prm_baseline_system_change_fuel_type(model, fuel_type, climate_zone) click to toggle source

Change the fuel type based on climate zone, depending on the standard. Defaults to no change.

@param model [OpenStudio::Model::Model] OpenStudio model object @param fuel_type [String] Valid choices are electric, fossil, fossilandelectric,

purchasedheat, purchasedcooling, purchasedheatandcooling

@param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [String] the revised fuel type

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1377
def model_prm_baseline_system_change_fuel_type(model, fuel_type, climate_zone)
  # Don't change fuel type for most templates
  return fuel_type
end
model_prm_baseline_system_groups(model, custom, bldg_type_hvac_zone_hash = nil) click to toggle source

Determine the dominant and exceptional areas of the building based on fuel types and occupancy types.

@param model [OpenStudio::Model::Model] OpenStudio model object @param custom [String] custom fuel type @return [Array<Hash>] an array of hashes of area information,

with keys area_ft2, type, fuel, and zones (an array of zones)
# File lib/openstudio-standards/standards/Standards.Model.rb, line 800
def model_prm_baseline_system_groups(model, custom, bldg_type_hvac_zone_hash = nil)
  # Define the minimum area for the
  # exception that allows a different
  # system type in part of the building.
  if custom == 'Xcel Energy CO EDA'
    # Customization - Xcel EDA Program Manual 2014
    # 3.2.1 Mechanical System Selection ii
    exception_min_area_ft2 = 5000
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.Standards.Model', "Customization; per Xcel EDA Program Manual 2014 3.2.1 Mechanical System Selection ii, minimum area for non-predominant conditions reduced to #{exception_min_area_ft2} ft2.")
  else
    exception_min_area_ft2 = 20_000
  end

  # Get occupancy type, fuel type, and area information for all zones,
  # excluding unconditioned zones.
  # Occupancy types are:
  # Residential
  # NonResidential
  # (and for 90.1-2013)
  # PublicAssembly
  # Retail
  # Fuel types are:
  # fossil
  # electric
  # (and for Xcel Energy CO EDA)
  # fossilandelectric
  zones = model_zones_with_occ_and_fuel_type(model, custom)

  # Ensure that there is at least one conditioned zone
  if zones.size.zero?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', 'The building does not appear to have any conditioned zones. Make sure zones have thermostat with appropriate heating and cooling setpoint schedules.')
    return []
  end

  # Group the zones by occupancy type
  type_to_area = Hash.new { 0.0 }
  zones_grouped_by_occ = zones.group_by { |z| z['occ'] }

  # Determine the dominant occupancy type by area
  zones_grouped_by_occ.each do |occ_type, zns|
    zns.each do |zn|
      type_to_area[occ_type] += zn['area']
    end
  end
  dom_occ = type_to_area.sort_by { |k, v| v }.reverse[0][0]

  # Get the dominant occupancy type group
  dom_occ_group = zones_grouped_by_occ[dom_occ]

  # Check the non-dominant occupancy type groups to see if they are big enough to trigger the occupancy exception.
  # If they are, leave the group standing alone.
  # If they are not, add the zones in that group back to the dominant occupancy type group.
  occ_groups = []
  zones_grouped_by_occ.each do |occ_type, zns|
    # Skip the dominant occupancy type
    next if occ_type == dom_occ

    # Add up the floor area of the group
    area_m2 = 0
    zns.each do |zn|
      area_m2 += zn['area']
    end
    area_ft2 = OpenStudio.convert(area_m2, 'm^2', 'ft^2').get

    # If the non-dominant group is big enough, preserve that group.
    if area_ft2 > exception_min_area_ft2
      occ_groups << [occ_type, zns]
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "The portion of the building with an occupancy type of #{occ_type} is bigger than the minimum exception area of #{exception_min_area_ft2.round} ft2.  It will be assigned a separate HVAC system type.")
      # Otherwise, add the zones back to the dominant group.
    else
      dom_occ_group += zns
    end
  end
  # Add the dominant occupancy group to the list
  occ_groups << [dom_occ, dom_occ_group]

  # Inside of each remaining occupancy group, determine the dominant fuel type.
  # This determination should only include zones that are part of the dominant area type inside of this group.
  occ_and_fuel_groups = []
  occ_groups.each do |occ_type, zns|
    # Separate the zones that are part of the dominant occ type
    dom_occ_zns = []
    nondom_occ_zns = []
    zns.each do |zn|
      if zn['occ'] == occ_type
        dom_occ_zns << zn
      else
        nondom_occ_zns << zn
      end
    end

    # Determine the dominant fuel type from the subset of the dominant area type zones
    fuel_to_area = Hash.new { 0.0 }
    zones_grouped_by_fuel = dom_occ_zns.group_by { |z| z['fuel'] }
    zones_grouped_by_fuel.each do |fuel, zns_by_fuel|
      zns_by_fuel.each do |zn|
        fuel_to_area[fuel] += zn['area']
      end
    end

    sorted_by_area = fuel_to_area.sort_by { |k, v| v }.reverse
    dom_fuel = sorted_by_area[0][0]

    # Don't allow unconditioned to be the dominant fuel, go to the next biggest
    if dom_fuel == 'unconditioned'
      if sorted_by_area.size > 1
        dom_fuel = sorted_by_area[1][0]
      else
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', 'The fuel type was not able to be determined for any zones in this model.  Run with debug messages enabled to see possible reasons.')
        return []
      end
    end

    # Get the dominant fuel type group
    dom_fuel_group = {}
    dom_fuel_group['occ'] = occ_type
    dom_fuel_group['fuel'] = dom_fuel
    dom_fuel_group['zones'] = zones_grouped_by_fuel[dom_fuel]

    # The zones that aren't part of the dominant occ type are automatically added to the dominant fuel group
    dom_fuel_group['zones'] += nondom_occ_zns

    # Check the non-dominant occupancy type groups to see if they are big enough to trigger the occupancy exception.
    # If they are, leave the group standing alone.
    # If they are not, add the zones in that group back to the dominant occupancy type group.
    zones_grouped_by_fuel.each do |fuel_type, zns_by_fuel|
      # Skip the dominant occupancy type
      next if fuel_type == dom_fuel

      # Add up the floor area of the group
      area_m2 = 0
      zns_by_fuel.each do |zn|
        area_m2 += zn['area']
      end
      area_ft2 = OpenStudio.convert(area_m2, 'm^2', 'ft^2').get

      # If the non-dominant group is big enough, preserve that group.
      if area_ft2 > exception_min_area_ft2
        group = {}
        group['occ'] = occ_type
        group['fuel'] = fuel_type
        group['zones'] = zns_by_fuel
        occ_and_fuel_groups << group
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "The portion of the building with an occupancy type of #{occ_type} and fuel type of #{fuel_type} is bigger than the minimum exception area of #{exception_min_area_ft2.round} ft2.  It will be assigned a separate HVAC system type.")
        # Otherwise, add the zones back to the dominant group.
      else
        dom_fuel_group['zones'] += zns_by_fuel
      end
    end
    # Add the dominant occupancy group to the list
    occ_and_fuel_groups << dom_fuel_group
  end

  # Moved heated-only zones into their own groups.
  # Per the PNNL PRM RM, this must be done AFTER the dominant occ and fuel types are determined
  # so that heated-only zone areas are part of the determination.
  final_groups = []
  occ_and_fuel_groups.each do |gp|
    # Skip unconditioned groups
    next if gp['fuel'] == 'unconditioned'

    heated_only_zones = []
    heated_cooled_zones = []
    gp['zones'].each do |zn|
      if OpenstudioStandards::ThermalZone.thermal_zone_heated?(zn['zone']) && !OpenstudioStandards::ThermalZone.thermal_zone_cooled?(zn['zone'])
        heated_only_zones << zn
      else
        heated_cooled_zones << zn
      end
    end
    gp['zones'] = heated_cooled_zones

    # Add the group (less unheated zones) to the final list
    final_groups << gp

    # If there are any heated-only zones, create a new group for them.
    unless heated_only_zones.empty?
      htd_only_group = {}
      htd_only_group['occ'] = 'heatedonly'
      htd_only_group['fuel'] = gp['fuel']
      htd_only_group['zones'] = heated_only_zones
      final_groups << htd_only_group
    end
  end

  # Calculate the area for each of the final groups and replace the zone hashes with the zone objects
  final_groups.each do |gp|
    area_m2 = 0.0
    gp_zns = []
    gp['zones'].each do |zn|
      area_m2 += zn['area']
      gp_zns << zn['zone']
    end
    area_ft2 = OpenStudio.convert(area_m2, 'm^2', 'ft^2').get
    gp['area_ft2'] = area_ft2
    gp['zones'] = gp_zns
  end

  # @todo Remove the secondary zones before
  # determining the area used to pick the HVAC system, per PNNL PRM RM

  # If there is any district heating or district cooling in the proposed building, the heating and cooling
  # fuels in the entire baseline building are changed for the purposes of HVAC system assignment
  all_htg_fuels = []
  all_clg_fuels = []

  # error if HVACComponent heating fuels method is not available
  if model.version < OpenStudio::VersionString.new('3.6.0')
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Standards.Model', 'Required HVACComponent methods .heatingFuelTypes and .coolingFuelTypes are not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
  end

  model.getThermalZones.sort.each do |zone|
    all_htg_fuels += zone.heatingFuelTypes.map(&:valueName)
    all_clg_fuels += zone.coolingFuelTypes.map(&:valueName)
  end

  purchased_heating = false
  purchased_cooling = false

  # Purchased heating
  if all_htg_fuels.include?('DistrictHeating') || all_htg_fuels.include?('DistrictHeatingWater') || all_htg_fuels.include?('DistrictHeatingSteam')
    purchased_heating = true
  end

  # Purchased cooling
  if all_clg_fuels.include?('DistrictCooling')
    purchased_cooling = true
  end

  # Categorize
  district_fuel = nil
  if purchased_heating && purchased_cooling
    district_fuel = 'purchasedheatandcooling'
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', 'The proposed model included purchased heating and cooling.  All baseline building system selection will be based on this information.')
  elsif purchased_heating && !purchased_cooling
    district_fuel = 'purchasedheat'
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', 'The proposed model included purchased heating.  All baseline building system selection will be based on this information.')
  elsif !purchased_heating && purchased_cooling
    district_fuel = 'purchasedcooling'
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', 'The proposed model included purchased cooling.  All baseline building system selection will be based on this information.')
  end

  # Change the fuel in all final groups if district systems were found.
  if district_fuel
    final_groups.each do |gp|
      gp['fuel'] = district_fuel
    end
  end

  # Determine the number of stories spanned by each group and report out info.
  final_groups.each do |group|
    # Determine the number of stories this group spans
    group['stories'] = OpenstudioStandards::Geometry.thermal_zones_get_number_of_stories_spanned(group['zones'])
    # Report out the final grouping
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Final system type group: occ = #{group['occ']}, fuel = #{group['fuel']}, area = #{group['area_ft2'].round} ft2, num stories = #{group['stories']}, zones:")
    group['zones'].sort.each_slice(5) do |zone_list|
      zone_names = []
      zone_list.each do |zone|
        zone_names << zone.name.get.to_s
      end
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "--- #{zone_names.join(', ')}")
    end
  end

  return final_groups
end
model_prm_baseline_system_number(model, climate_zone, area_type, fuel_type, area_ft2, num_stories, custom) click to toggle source

Determines which system number is used for the baseline system. Default is 90.1-2004 approach.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param area_type [String] Valid choices are residential, nonresidential, and heatedonly @param fuel_type [String] Valid choices are electric, fossil, fossilandelectric,

purchasedheat, purchasedcooling, purchasedheatandcooling

@param area_ft2 [Double] Area in ft^2 @param num_stories [Integer] Number of stories @param custom [String] custom fuel type @return [String] the system number: 1_or_2, 3_or_4, 5_or_6, 7_or_8, 9_or_10

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1341
def model_prm_baseline_system_number(model, climate_zone, area_type, fuel_type, area_ft2, num_stories, custom)
  sys_num = nil
  # Set the area limit
  limit_ft2 = 75_000

  # Warn about heated only
  if area_type == 'heatedonly'
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Per Table G3.1.10.d, '(In the proposed building) Where no cooling system exists or no cooling system has been specified, the cooling system shall be identical to the system modeled in the baseline building design.' This requires that you go back and add a cooling system to the proposed model.  This code cannot do that for you; you must do it manually.")
  end

  case area_type
    when 'residential'
      sys_num = '1_or_2'
    when 'nonresidential', 'heatedonly'
      # nonresidential and 3 floors or less and <25,000 ft2
      if num_stories <= 3 && area_ft2 < limit_ft2
        sys_num = '3_or_4'
        # nonresidential and 4 or 5 floors or 5 floors or less and 25,000 ft2 to 150,000 ft2
      elsif ((num_stories == 4 || num_stories == 5) && area_ft2 < limit_ft2) || (num_stories <= 5 && (area_ft2 >= limit_ft2 && area_ft2 <= 150_000))
        sys_num = '5_or_6'
        # nonresidential and more than 5 floors or >150,000 ft2
      elsif num_stories >= 5 || area_ft2 > 150_000
        sys_num = '7_or_8'
      end
  end

  return sys_num
end
model_prm_baseline_system_type(model, climate_zone, sys_group, custom, hvac_building_type = nil, district_heat_zones = nil) click to toggle source

Determine the baseline system type given the inputs. Logic is different for different standards.

90.1-2007, 90.1-2010, 90.1-2013

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param sys_group [Hash] Hash defining a group of zones that have the same Appendix G system type @param custom [String] custom fuel type @return [String] The system type. Possibilities are PTHP, PTAC, PSZ_AC, PSZ_HP, PVAV_Reheat, PVAV_PFP_Boxes,

VAV_Reheat, VAV_PFP_Boxes, Gas_Furnace, Electric_Furnace

@todo add 90.1-2013 systems 11-13

# File lib/openstudio-standards/standards/Standards.Model.rb, line 1258
def model_prm_baseline_system_type(model, climate_zone, sys_group, custom, hvac_building_type = nil, district_heat_zones = nil)
  area_type = sys_group['occ']
  fuel_type = sys_group['fuel']
  area_ft2 = sys_group['area_ft2']
  num_stories = sys_group['stories']

  # [type, central_heating_fuel, zone_heating_fuel, cooling_fuel]
  system_type = [nil, nil, nil, nil]

  # Get the row from TableG3.1.1A
  sys_num = model_prm_baseline_system_number(model, climate_zone, area_type, fuel_type, area_ft2, num_stories, custom)

  # Modify the fuel type if called for by the standard
  if custom == 'Xcel Energy CO EDA'
    # fuel type remains unchanged
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', 'Custom; per Xcel EDA Program Manual 2014 Table 3.2.2 Baseline HVAC System Types, the 90.1-2010 rules for heating fuel type (based on proposed model) rules apply.')
  else
    fuel_type = model_prm_baseline_system_change_fuel_type(model, fuel_type, climate_zone)
  end

  # Define the lookup by row and by fuel type
  sys_lookup = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }

  # fossil, fossil and electric, purchased heat, purchased heat and cooling
  sys_lookup['1_or_2']['fossil'] = ['PTAC', 'NaturalGas', nil, 'Electricity']
  sys_lookup['1_or_2']['fossilandelectric'] = ['PTAC', 'NaturalGas', nil, 'Electricity']
  sys_lookup['1_or_2']['purchasedheat'] = ['PTAC', 'DistrictHeating', nil, 'Electricity']
  sys_lookup['1_or_2']['purchasedheatandcooling'] = ['Fan_Coil', 'DistrictHeating', nil, 'DistrictCooling']
  sys_lookup['3_or_4']['fossil'] = ['PSZ_AC', 'NaturalGas', nil, 'Electricity']
  sys_lookup['3_or_4']['fossilandelectric'] = ['PSZ_AC', 'NaturalGas', nil, 'Electricity']
  sys_lookup['3_or_4']['purchasedheat'] = ['PSZ_AC', 'DistrictHeating', nil, 'Electricity']
  sys_lookup['3_or_4']['purchasedheatandcooling'] = ['PSZ_AC', 'DistrictHeating', nil, 'DistrictCooling']
  sys_lookup['5_or_6']['fossil'] = ['PVAV_Reheat', 'NaturalGas', 'NaturalGas', 'Electricity']
  sys_lookup['5_or_6']['fossilandelectric'] = ['PVAV_Reheat', 'NaturalGas', 'Electricity', 'Electricity']
  sys_lookup['5_or_6']['purchasedheat'] = ['PVAV_Reheat', 'DistrictHeating', 'DistrictHeating', 'Electricity']
  sys_lookup['5_or_6']['purchasedheatandcooling'] = ['PVAV_Reheat', 'DistrictHeating', 'DistrictHeating', 'DistrictCooling']
  sys_lookup['7_or_8']['fossil'] = ['VAV_Reheat', 'NaturalGas', 'NaturalGas', 'Electricity']
  sys_lookup['7_or_8']['fossilandelectric'] = ['VAV_Reheat', 'NaturalGas', 'Electricity', 'Electricity']
  sys_lookup['7_or_8']['purchasedheat'] = ['VAV_Reheat', 'DistrictHeating', 'DistrictHeating', 'Electricity']
  sys_lookup['7_or_8']['purchasedheatandcooling'] = ['VAV_Reheat', 'DistrictHeating', 'DistrictHeating', 'DistrictCooling']
  sys_lookup['9_or_10']['fossil'] = ['Gas_Furnace', 'NaturalGas', nil, nil]
  sys_lookup['9_or_10']['fossilandelectric'] = ['Gas_Furnace', 'NaturalGas', nil, nil]
  sys_lookup['9_or_10']['purchasedheat'] = ['Gas_Furnace', 'DistrictHeating', nil, nil]
  sys_lookup['9_or_10']['purchasedheatandcooling'] = ['Gas_Furnace', 'DistrictHeating', nil, nil]
  # electric (heat), purchased cooling
  sys_lookup['1_or_2']['electric'] = ['PTHP', 'Electricity', nil, 'Electricity']
  sys_lookup['1_or_2']['purchasedcooling'] = ['Fan_Coil', 'NaturalGas', nil, 'DistrictCooling']
  sys_lookup['3_or_4']['electric'] = ['PSZ_HP', 'Electricity', nil, 'Electricity']
  sys_lookup['3_or_4']['purchasedcooling'] = ['PSZ_AC', 'NaturalGas', nil, 'DistrictCooling']
  sys_lookup['5_or_6']['electric'] = ['PVAV_PFP_Boxes', 'Electricity', 'Electricity', 'Electricity']
  sys_lookup['5_or_6']['purchasedcooling'] = ['PVAV_PFP_Boxes', 'Electricity', 'Electricity', 'DistrictCooling']
  sys_lookup['7_or_8']['electric'] = ['VAV_PFP_Boxes', 'Electricity', 'Electricity', 'Electricity']
  sys_lookup['7_or_8']['purchasedcooling'] = ['VAV_PFP_Boxes', 'Electricity', 'Electricity', 'DistrictCooling']
  sys_lookup['9_or_10']['electric'] = ['Electric_Furnace', 'Electricity', nil, nil]
  sys_lookup['9_or_10']['purchasedcooling'] = ['Electric_Furnace', 'Electricity', nil, nil]

  # Get the system type
  system_type = sys_lookup[sys_num][fuel_type]

  if system_type.nil?
    system_type = [nil, nil, nil, nil]
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Could not determine system type for #{template}, #{area_type}, #{fuel_type}, #{area_ft2.round} ft^2, #{num_stories} stories.")
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "System type is #{system_type[0]} for #{template}, #{area_type}, #{fuel_type}, #{area_ft2.round} ft^2, #{num_stories} stories.")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "--- #{system_type[1]} for main heating") unless system_type[1].nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "--- #{system_type[2]} for zone heat/reheat") unless system_type[2].nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "--- #{system_type[3]} for cooling") unless system_type[3].nil?
  end

  return system_type
end
model_prm_skylight_to_roof_ratio_limit(model) click to toggle source

Determines the skylight to roof ratio limit for a given standard

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Double] the skylight to roof ratio, as a percent: 5.0 = 5%. 5% by default.

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4713
def model_prm_skylight_to_roof_ratio_limit(model)
  srr_lim = 5.0
  return srr_lim
end
model_process_results_for_datapoint(model, climate_zone, building_type, lkp_template: nil) click to toggle source

Method to gather prototype simulation results for a specific climate zone, building type, and template

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param building_type [String] the building type @param lkp_template [String] The standards template, e.g.‘90.1-2013’ @return [Hash] Returns a hash with data presented in various bins.

Returns nil if no search results
# File lib/openstudio-standards/standards/Standards.Model.rb, line 3798
def model_process_results_for_datapoint(model, climate_zone, building_type, lkp_template: nil)
  # Hash to store the legacy results by fuel and by end use
  legacy_results_hash = {}
  legacy_results_hash['total_legacy_energy_val'] = 0
  legacy_results_hash['total_legacy_water_val'] = 0
  legacy_results_hash['total_energy_by_fuel'] = {}
  legacy_results_hash['total_energy_by_end_use'] = {}

  # Get the legacy simulation results
  legacy_values = model_legacy_results_by_end_use_and_fuel_type(model, climate_zone, building_type, 'annual', lkp_template: lkp_template)
  if legacy_values.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Could not find legacy idf results for #{search_criteria}")
    return legacy_results_hash
  end

  # List of all fuel types
  fuel_types = ['Electricity', 'Natural Gas', 'Additional Fuel', 'District Cooling', 'District Heating', 'Water']

  # List of all end uses
  end_uses = ['Heating', 'Cooling', 'Interior Lighting', 'Exterior Lighting', 'Interior Equipment', 'Exterior Equipment', 'Fans', 'Pumps', 'Heat Rejection', 'Humidification', 'Heat Recovery', 'Water Systems', 'Refrigeration', 'Generators']

  # Sum the legacy results up by fuel and by end use
  fuel_types.each do |fuel_type|
    end_uses.each do |end_use|
      next if end_use == 'Exterior Equipment'

      legacy_val = legacy_values["#{end_use}|#{fuel_type}"]

      # Combine the exterior lighting and exterior equipment
      if end_use == 'Exterior Lighting'
        legacy_exterior_equipment = legacy_values["Exterior Equipment|#{fuel_type}"]
        unless legacy_exterior_equipment.nil?
          legacy_val += legacy_exterior_equipment
        end
      end

      if legacy_val.nil?
        OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "#{fuel_type} #{end_use} legacy idf value not found")
        next
      end

      # Add the energy to the total
      if fuel_type == 'Water'
        legacy_results_hash['total_legacy_water_val'] += legacy_val
      else
        legacy_results_hash['total_legacy_energy_val'] += legacy_val

        # add to fuel specific total
        if legacy_results_hash['total_energy_by_fuel'][fuel_type]
          legacy_results_hash['total_energy_by_fuel'][fuel_type] += legacy_val # add to existing counter
        else
          legacy_results_hash['total_energy_by_fuel'][fuel_type] = legacy_val # start new counter
        end

        # add to end use specific total
        if legacy_results_hash['total_energy_by_end_use'][end_use]
          legacy_results_hash['total_energy_by_end_use'][end_use] += legacy_val # add to existing counter
        else
          legacy_results_hash['total_energy_by_end_use'][end_use] = legacy_val # start new counter
        end
      end
    end
  end

  return legacy_results_hash
end
model_remap_office(model, floor_area) click to toggle source

remap office to one of the prototype buildings

@param model [OpenStudio::Model::Model] OpenStudio model object @param floor_area [Double] floor area (m^2) @return [String] SmallOffice, MediumOffice, LargeOffice

# File lib/openstudio-standards/standards/Standards.Model.rb, line 3971
def model_remap_office(model, floor_area)
  # prototype small office approx 500 m^2
  # prototype medium office approx 5000 m^2
  # prototype large office approx 50,000 m^2
  # map office building type to small medium or large
  building_type = if floor_area < 2750
                    'SmallOffice'
                  elsif floor_area < 25_250
                    'MediumOffice'
                  else
                    'LargeOffice'
                  end
end
model_remove_external_shading_devices(model) click to toggle source

Remove external shading devices. Site shading will not be impacted.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4815
def model_remove_external_shading_devices(model)
  shading_surfaces_removed = 0
  model.getShadingSurfaceGroups.sort.each do |shade_group|
    # Skip Site shading
    next if shade_group.shadingSurfaceType == 'Site'

    # Space shading surfaces should be removed
    shading_surfaces_removed += shade_group.shadingSurfaces.size
    shade_group.remove
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Removed #{shading_surfaces_removed} external shading devices.")

  return true
end
model_remove_prm_ems_objects(model) click to toggle source

Remove EMS objects that may be orphaned from removing HVAC

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4794
def model_remove_prm_ems_objects(model)
  model.getEnergyManagementSystemActuators.each(&:remove)
  model.getEnergyManagementSystemConstructionIndexVariables.each(&:remove)
  model.getEnergyManagementSystemCurveOrTableIndexVariables.each(&:remove)
  model.getEnergyManagementSystemGlobalVariables.each(&:remove)
  model.getEnergyManagementSystemInternalVariables.each(&:remove)
  model.getEnergyManagementSystemMeteredOutputVariables.each(&:remove)
  model.getEnergyManagementSystemOutputVariables.each(&:remove)
  model.getEnergyManagementSystemPrograms.each(&:remove)
  model.getEnergyManagementSystemProgramCallingManagers.each(&:remove)
  model.getEnergyManagementSystemSensors.each(&:remove)
  model.getEnergyManagementSystemSubroutines.each(&:remove)
  model.getEnergyManagementSystemTrendVariables.each(&:remove)

  return true
end
model_remove_prm_hvac(model) click to toggle source

Remove all HVAC that will be replaced during the performance rating method baseline generation. This does not include plant loops that serve WaterUse:Equipment or Fan:ZoneExhaust

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 4738
def model_remove_prm_hvac(model)
  # Plant loops
  model.getPlantLoops.sort.each do |loop|
    # Don't remove service water heating loops
    next if plant_loop_swh_loop?(loop)

    loop.remove
  end

  # Air loops
  model.getAirLoopHVACs.each do |air_loop|
    # Don't remove airloops representing non-mechanically cooled systems
    if !air_loop.additionalProperties.hasFeature('non_mechanically_cooled')
      air_loop.remove
    else
      # Remove heating coil on
      air_loop.supplyComponents.each do |supply_comp|
        # Remove standalone heating coils
        if supply_comp.iddObjectType.valueName.to_s.include?('OS_Coil_Heating')
          supply_comp.remove
        # Remove heating coils wrapped in a unitary system
        elsif supply_comp.iddObjectType.valueName.to_s.include?('OS_AirLoopHVAC_UnitarySystem')
          unitary_system = supply_comp.to_AirLoopHVACUnitarySystem.get
          htg_coil = unitary_system.heatingCoil
          if htg_coil.is_initialized
            htg_coil = htg_coil.get
            unitary_system.resetCoolingCoil
            htg_coil.remove
          end
        end
      end
    end
  end

  # Zone equipment
  model.getThermalZones.sort.each do |zone|
    zone.equipment.each do |zone_equipment|
      next if zone_equipment.to_FanZoneExhaust.is_initialized

      zone_equipment.remove unless zone.additionalProperties.hasFeature('non_mechanically_cooled')
    end
  end

  # Outdoor VRF units (not in zone, not in loops)
  model.getAirConditionerVariableRefrigerantFlows.each(&:remove)

  # Air loop dedicated outdoor air systems
  model.getAirLoopHVACDedicatedOutdoorAirSystems.each(&:remove)

  return true
end
model_remove_unused_resource_objects(model) click to toggle source

Removes all of the unused ResourceObjects (Curves, ScheduleDay, Material, etc.) from the model.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5499
def model_remove_unused_resource_objects(model)
  start_size = model.objects.size
  model.getResourceObjects.sort.each do |obj|
    if obj.directUseCount.zero?
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "#{obj.name} is unused; it will be removed.")
      model.removeObject(obj.handle)
    end
  end
  end_size = model.objects.size
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "The model started with #{start_size} objects and finished with #{end_size} objects after removing unused resource objects.")
  return true
end
model_set_vav_terminals_to_control_for_outdoor_air(model, air_loop: nil) click to toggle source

Sets VAV reheat and VAV no reheat terminals on an air loop to control for outdoor air

@param model [OpenStudio::Model::Model] OpenStudio model object @param air_loop [<OpenStudio::Model::AirLoopHVAC>] air loop to enable DCV on.

Default is nil, which will apply to all air loops

@return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 629
def model_set_vav_terminals_to_control_for_outdoor_air(model, air_loop: nil)
  vav_reheats = model.getAirTerminalSingleDuctVAVReheats
  vav_no_reheats = model.getAirTerminalSingleDuctVAVNoReheats

  if !air_loop.nil?
    vav_reheats.each do |vav_reheat|
      next if vav_reheat.airLoopHVAC.get.name.to_s != air_loop.name.to_s

      vav_reheat.setControlForOutdoorAir(true)
    end
    vav_no_reheats.each do |vav_no_reheat|
      next if vav_no_reheat.airLoopHVAC.get.name.to_s != air_loop.name.to_s

      vav_no_reheat.setControlForOutdoorAir(true)
    end
  else # all terminals
    vav_reheats.each do |vav_reheat|
      vav_reheat.setControlForOutdoorAir(true)
    end
    vav_no_reheats.each do |vav_no_reheat|
      vav_no_reheat.setControlForOutdoorAir(true)
    end
  end
  return model
end
model_system_outdoor_air_sizing_vrp_method(air_loop_hvac) click to toggle source

adjust the outdoor air sizing to the use the ventilation rate procedure @todo this needs to be changed in both the sizing system and controller mechanical ventilation objects

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.SizingSystem.rb, line 47
def model_system_outdoor_air_sizing_vrp_method(air_loop_hvac)
  # Do not apply the adjustment to some of the system in
  # the hospital and outpatient which have their minimum
  # damper position determined based on AIA 2001 ventilation
  # requirements
  if (@instvarbuilding_type == 'Hospital' && (air_loop_hvac.name.to_s.include?('VAV_ER') || air_loop_hvac.name.to_s.include?('VAV_ICU') ||
     air_loop_hvac.name.to_s.include?('VAV_OR') || air_loop_hvac.name.to_s.include?('VAV_LABS') ||
     air_loop_hvac.name.to_s.include?('VAV_PATRMS'))) ||
     (@instvarbuilding_type == 'Outpatient' && air_loop_hvac.name.to_s.include?('Outpatient F1'))
    return true
  end

  sizing_system = air_loop_hvac.sizingSystem
  if air_loop_hvac.model.version < OpenStudio::VersionString.new('3.3.0')
    sizing_system.setSystemOutdoorAirMethod('VentilationRateProcedure')
  else
    sizing_system.setSystemOutdoorAirMethod('Standard62.1VentilationRateProcedure')
  end

  # Set the minimum zone ventilation efficiency
  min_ventilation_efficiency = air_loop_hvac_minimum_zone_ventilation_efficiency(air_loop_hvac)
  air_loop_hvac.thermalZones.sort.each do |zone|
    sizing_zone = zone.sizingZone
    if air_loop_hvac.model.version < OpenStudio::VersionString.new('3.0.0')
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.prototype.SizingSystem', "The design minimum zone ventilation efficiency cannot be set for #{sizing_system.name}. It can only be set OpenStudio 3.0.0 and later.")
    else
      sizing_zone.setDesignMinimumZoneVentilationEfficiency(min_ventilation_efficiency)
    end
  end

  return true
end
model_two_pipe_loop(model, hot_water_loop, chilled_water_loop, control_strategy: 'outdoor_air_lockout', lockout_temperature: 65.0, thermal_zones: []) click to toggle source

Model a 2-pipe plant loop, where the loop is either in heating or cooling. For sizing reasons, this method keeps separate hot water and chilled water loops, and connects them together with a common inverse schedule.

@param model [OpenStudio::Model::Model] OpenStudio model object @param hot_water_loop [OpenStudio::Model::PlantLoop] the hot water loop @param chilled_water_loop [OpenStudio::Model::PlantLoop] the chilled water loop @param control_strategy [String] Method to determine whether the loop is in heating or cooling mode

'outdoor_air_lockout' - The system will be in heating below the lockout_temperature variable,
   and cooling above the lockout_temperature. Requires the lockout_temperature variable.
'zone_demand' - Heating or cooling determined by preponderance of zone demand.
   Requires thermal_zones defined.

@param lockout_temperature [Double] lockout temperature in degrees Fahrenheit, default 65F. @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] array of zones @return [OpenStudio::Model::ScheduleRuleset]

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 1168
  def model_two_pipe_loop(model,
                          hot_water_loop,
                          chilled_water_loop,
                          control_strategy: 'outdoor_air_lockout',
                          lockout_temperature: 65.0,
                          thermal_zones: [])

    if control_strategy == 'outdoor_air_lockout'
      # get or create outdoor sensor node to be used in plant availability managers if needed
      outdoor_airnode = model.outdoorAirNode

      # create availability managers based on outdoor temperature
      # create hot water plant availability manager
      hot_water_loop_lockout_manager = OpenStudio::Model::AvailabilityManagerHighTemperatureTurnOff.new(model)
      hot_water_loop_lockout_manager.setName("#{hot_water_loop.name} Lockout Manager")
      hot_water_loop_lockout_manager.setSensorNode(outdoor_airnode)
      hot_water_loop_lockout_manager.setTemperature(OpenStudio.convert(lockout_temperature, 'F', 'C').get)

      # set availability manager to hot water plant
      hot_water_loop.addAvailabilityManager(hot_water_loop_lockout_manager)

      # create chilled water plant availability manager
      chilled_water_loop_lockout_manager = OpenStudio::Model::AvailabilityManagerLowTemperatureTurnOff.new(model)
      chilled_water_loop_lockout_manager.setName("#{chilled_water_loop.name} Lockout Manager")
      chilled_water_loop_lockout_manager.setSensorNode(outdoor_airnode)
      chilled_water_loop_lockout_manager.setTemperature(OpenStudio.convert(lockout_temperature, 'F', 'C').get)

      # set availability manager to hot water plant
      chilled_water_loop.addAvailabilityManager(chilled_water_loop_lockout_manager)
    else
      # create availability managers based on zone heating and cooling demand
      hot_water_loop_name = ems_friendly_name(hot_water_loop.name)
      chilled_water_loop_name = ems_friendly_name(chilled_water_loop.name)

      # create hot water plant availability schedule managers and create an EMS acuator
      sch_hot_water_availability = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                   0,
                                                                                                   name: "#{hot_water_loop.name} Availability Schedule",
                                                                                                   schedule_type_limit: 'OnOff')

      hot_water_loop_manager = OpenStudio::Model::AvailabilityManagerScheduled.new(model)
      hot_water_loop_manager.setName("#{hot_water_loop.name} Availability Manager")
      hot_water_loop_manager.setSchedule(sch_hot_water_availability)

      hot_water_plant_ctrl = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_hot_water_availability,
                                                                                   'Schedule:Year',
                                                                                   'Schedule Value')
      hot_water_plant_ctrl.setName("#{hot_water_loop_name}_availability_control")

      # set availability manager to hot water plant
      hot_water_loop.addAvailabilityManager(hot_water_loop_manager)

      # create chilled water plant availability schedule managers and create an EMS acuator
      sch_chilled_water_availability = OpenstudioStandards::Schedules.create_constant_schedule_ruleset(model,
                                                                                                       0,
                                                                                                       name: "#{chilled_water_loop.name} Availability Schedule",
                                                                                                       schedule_type_limit: 'OnOff')

      chilled_water_loop_manager = OpenStudio::Model::AvailabilityManagerScheduled.new(model)
      chilled_water_loop_manager.setName("#{chilled_water_loop.name} Availability Manager")
      chilled_water_loop_manager.setSchedule(sch_chilled_water_availability)

      chilled_water_plant_ctrl = OpenStudio::Model::EnergyManagementSystemActuator.new(sch_chilled_water_availability,
                                                                                       'Schedule:Year',
                                                                                       'Schedule Value')
      chilled_water_plant_ctrl.setName("#{chilled_water_loop_name}_availability_control")

      # set availability manager to chilled water plant
      chilled_water_loop.addAvailabilityManager(chilled_water_loop_manager)

      # check if zone heat and cool requests program exists, if not create it
      determine_zone_cooling_needs_prg = model.getEnergyManagementSystemProgramByName('Determine_Zone_Cooling_Needs')
      determine_zone_heating_needs_prg = model.getEnergyManagementSystemProgramByName('Determine_Zone_Heating_Needs')
      unless determine_zone_cooling_needs_prg.is_initialized && determine_zone_heating_needs_prg.is_initialized
        model_add_zone_heat_cool_request_count_program(model, thermal_zones)
      end

      # create program to determine plant heating or cooling mode
      determine_plant_mode_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
      determine_plant_mode_prg.setName('Determine_Heating_Cooling_Plant_Mode')
      determine_plant_mode_prg_body = <<-EMS
      IF Zone_Heating_Ratio > 0.5,
        SET #{hot_water_loop_name}_availability_control = 1,
        SET #{chilled_water_loop_name}_availability_control = 0,
      ELSEIF Zone_Cooling_Ratio > 0.5,
        SET #{hot_water_loop_name}_availability_control = 0,
        SET #{chilled_water_loop_name}_availability_control = 1,
      ELSE,
        SET #{hot_water_loop_name}_availability_control = #{hot_water_loop_name}_availability_control,
        SET #{chilled_water_loop_name}_availability_control = #{chilled_water_loop_name}_availability_control,
      ENDIF
      EMS
      determine_plant_mode_prg.setBody(determine_plant_mode_prg_body)

      # create EMS program manager objects
      programs_at_beginning_of_timestep = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
      programs_at_beginning_of_timestep.setName('Heating_Cooling_Demand_Based_Plant_Availability_At_Beginning_Of_Timestep')
      programs_at_beginning_of_timestep.setCallingPoint('BeginTimestepBeforePredictor')
      programs_at_beginning_of_timestep.addProgram(determine_plant_mode_prg)
    end
  end
model_typical_display_case_zone(model) click to toggle source

Find the thermal zone that is best for adding refrigerated display cases into. First, check for space types that typically have refrigeration. Fall back to largest zone in the model if no typical space types are found.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::ThermalZone] returns a thermal zone if found, nil if not.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.refrigeration.rb, line 388
def model_typical_display_case_zone(model)
  # Ideally, look for one of the space types
  # that would typically have refrigeration.
  display_case_zone = nil
  display_case_zone_area_m2 = 0
  model.getThermalZones.each do |zone|
    space_type = OpenstudioStandards::ThermalZone.thermal_zone_get_space_type(zone)
    next if space_type.empty?

    space_type = space_type.get
    next if space_type.standardsSpaceType.empty?
    next if space_type.standardsBuildingType.empty?

    stds_spc_type = space_type.standardsSpaceType.get
    stds_bldg_type = space_type.standardsBuildingType.get
    case "#{stds_bldg_type} #{stds_spc_type}"
    when 'PrimarySchool Kitchen',
        'SecondarySchool Kitchen',
        'SuperMarket Sales',
        'QuickServiceRestaurant Kitchen',
        'FullServiceRestaurant Kitchen',
        'LargeHotel Kitchen',
        'Hospital Kitchen',
        'EPr Kitchen',
        'ESe Kitchen',
        'Gro GrocSales',
        'RFF StockRoom',
        'RSD StockRoom',
        'Htl Kitchen',
        'Hsp Kitchen'
      if zone.floorArea > display_case_zone_area_m2
        display_case_zone = zone
        display_case_zone_area_m2 = zone.floorArea
      end
    end
  end

  unless display_case_zone.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Display case zone is #{display_case_zone.name}, the largest zone with a space type typical for display cases.")
    return display_case_zone
  end

  # If no typical space type was found,
  # choose the largest zone in the model.
  display_case_zone = nil
  display_case_zone_area_m2 = 0
  model.getThermalZones.each do |zone|
    if zone.floorArea > display_case_zone_area_m2
      display_case_zone = zone
      display_case_zone_area_m2 = zone.floorArea
    end
  end

  unless display_case_zone.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "No space types typical for display cases were found, so the display cases will be placed in #{display_case_zone.name}, the largest zone.")
    return display_case_zone
  end

  return display_case_zone
end
model_typical_hvac_system_type(model, climate_zone, area_type, delivery_type, heating_source, cooling_source, area_m2, num_stories) click to toggle source

Determine the typical system type given the inputs

@param model [OpenStudio::Model::Model] OpenStudio model object @param area_type [String] Valid choices are residential and nonresidential @param delivery_type [String] Conditioning delivery type. Valid choices are air and hydronic @param heating_source [String] Valid choices are Electricity, NaturalGas, DistrictHeating, DistrictHeatingWater, DistrictHeatingSteam, DistrictAmbient @param cooling_source [String] Valid choices are Electricity, DistrictCooling, DistrictAmbient @param area_m2 [Double] Area in m^2 @param num_stories [Integer] Number of stories @return [Array] An array containing the system type, central heating fuel, zone heating fuel, and cooling fuel

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.hvac.rb, line 506
def model_typical_hvac_system_type(model,
                                   climate_zone,
                                   area_type,
                                   delivery_type,
                                   heating_source,
                                   cooling_source,
                                   area_m2,
                                   num_stories)

  # Convert area to ft^2
  area_ft2 = OpenStudio.convert(area_m2, 'm^2', 'ft^2').get

  case area_type
  when 'residential'
    area_type = 'Residential'
  when 'nonresidential', 'retail', 'publicassembly', 'heatedonly'
    area_type = 'Nonresidential'
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "area_type '#{area_type}' invalid or missing.")
    return nil
  end

  # lookup size category
  search_criteria = {}
  search_criteria['template'] = template
  search_criteria['building_category'] = area_type
  size_data = model_find_object(standards_data['size_category'], search_criteria, nil, nil, area_ft2, num_stories)
  if size_data.nil?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Model.Model', "Unable to find size category for #{search_criteria}.")
    return nil
  end

  # lookup infered HVAC system type
  search_criteria = {}
  search_criteria['template'] = template
  search_criteria['size_category'] = size_data['size_category']
  search_criteria['heating_source'] = heating_source
  search_criteria['cooling_source'] = cooling_source
  search_criteria['delivery_type'] = delivery_type
  hvac_data = model_find_object(standards_data['hvac_inference'], search_criteria)

  # return system type inputs with format [type, central_heating_fuel, zone_heating_fuel, cooling_fuel]
  if hvac_data.nil? || hvac_data.empty?
    system_type_inputs = [nil, nil, nil, nil]
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Could not determine system type for #{area_type} building of size #{area_ft2.round} ft^2 and #{num_stories} stories, and lookups #{search_criteria}.")
  else
    system_type_inputs = [hvac_data['hvac_system_type'], hvac_data['central_heating_fuel'], hvac_data['zone_heating_fuel'], hvac_data['cooling_fuel']]
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "System type is #{system_type_inputs[0]} for #{area_type} building of size #{area_ft2.round} ft^2 and #{num_stories} stories, and lookups #{search_criteria}.")
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "--- #{system_type_inputs[1]} for main heating") unless system_type_inputs[1].nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "--- #{system_type_inputs[2]} for zone heat/reheat") unless system_type_inputs[2].nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "--- #{system_type_inputs[3]} for cooling") unless system_type_inputs[3].nil?
  end

  return system_type_inputs
end
model_typical_walkin_zone(model) click to toggle source

Find the thermal zone that is best for adding refrigerated walkins into. First, check for space types that typically have refrigeration. Fall back to largest zone in the model if no typical space types are found.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::ThermalZone] returns a thermal zone if found, nil if not.

# File lib/openstudio-standards/prototypes/common/objects/Prototype.refrigeration.rb, line 455
def model_typical_walkin_zone(model)
  # Ideally, look for one of the space types
  # that would typically have refrigeration walkins.
  walkin_zone = nil
  walkin_zone_area_m2 = 0
  model.getThermalZones.each do |zone|
    space_type = OpenstudioStandards::ThermalZone.thermal_zone_get_space_type(zone)
    next if space_type.empty?

    space_type = space_type.get
    next if space_type.standardsSpaceType.empty?
    next if space_type.standardsBuildingType.empty?

    stds_spc_type = space_type.standardsSpaceType.get
    stds_bldg_type = space_type.standardsBuildingType.get
    case "#{stds_bldg_type} #{stds_spc_type}"
    when 'PrimarySchool Kitchen',
        'SecondarySchool Kitchen',
        'SuperMarket DryStorage',
        'QuickServiceRestaurant       Kitchen',
        'FullServiceRestaurant Kitchen',
        'LargeHotel Kitchen',
        'Hospital Kitchen',
        'EPr Kitchen',
        'ESe Kitchen',
        'Gro RefWalkInCool',
        'Gro RefWalkInFreeze',
        'RFF StockRoom',
        'RSD StockRoom',
        'Htl Kitchen',
        'Hsp Kitchen'
      if zone.floorArea > walkin_zone_area_m2
        walkin_zone = zone
        walkin_zone_area_m2 = zone.floorArea
      end
    end
  end

  unless walkin_zone.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Walkin zone is #{walkin_zone.name}, the largest zone with a space type typical for walkins.")
    return walkin_zone
  end

  # If no typical space type was found,
  # choose the largest zone in the model.
  walkin_zone = nil
  walkin_zone_area_m2 = 0
  model.getThermalZones.each do |zone|
    if zone.floorArea > walkin_zone_area_m2
      walkin_zone = zone
      walkin_zone_area_m2 = zone.floorArea
    end
  end

  unless walkin_zone.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "No space types typical for walkins were found, so the walkins will be placed in #{walkin_zone.name}, the largest zone.")
    return walkin_zone
  end

  return walkin_zone
end
model_validate_standards_spacetypes_in_model(model) click to toggle source

This method ensures that all spaces with spacetypes defined contain at least a standardSpaceType appropriate for the template. So, if any space with a space type defined does not have a Stnadard spacetype, or is undefined, an error will stop with information that the spacetype needs to be defined.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5088
def model_validate_standards_spacetypes_in_model(model)
  error_string = ''
  # populate search hash
  model.getSpaces.sort.each do |space|
    unless space.spaceType.empty?
      if space.spaceType.get.standardsSpaceType.empty? || space.spaceType.get.standardsBuildingType.empty?
        error_string << "Space: #{space.name} has SpaceType of #{space.spaceType.get.name} but the standardSpaceType or standardBuildingType  is undefined. Please use an appropriate standardSpaceType for #{template}\n"
        next
      else
        search_criteria = {
          'template' => template,
          'building_type' => space.spaceType.get.standardsBuildingType.get,
          'space_type' => space.spaceType.get.standardsSpaceType.get
        }
        # lookup space type properties
        space_type_properties = model_find_object(standards_data['space_types'], search_criteria)
        if space_type_properties.nil?
          error_string << "Could not find spacetype of criteria : #{search_criteria}. Please ensure you have a valid standardSpaceType and stantdardBuildingType defined.\n"
          space_type_properties = {}
        end
      end
    end
  end
  return true if error_string == ''

  # else
  OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', error_string)
  return false
end
model_ventilation_method(model) click to toggle source

Determines how ventilation for the standard is specified. When ‘Sum’, all min OA flow rates are added up. Commonly used by 90.1. When ‘Maximum’, only the biggest OA flow rate. Used by T24.

@param model [OpenStudio::Model::Model] OpenStudio model object @return [String] the ventilation method, either Sum or Maximum

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5482
def model_ventilation_method(model)
  building_data = model_get_building_properties(model)
  building_type = building_data['building_type']
  if building_type != 'Laboratory' # Laboratory has multiple criteria on ventilation, pick the greatest
    ventilation_method = 'Sum'
  else
    ventilation_method = 'Maximum'
  end

  return ventilation_method
end
model_walkin_freezer_latent_case_credit_curve(model) click to toggle source

Determine the latent case credit curve to use for walkins. Defaults to values after 90.1-2007. @todo Should probably use the model_add_refrigeration_walkin and lookups from the spreadsheet instead of hard-coded values

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.refrigeration.rb, line 843
def model_walkin_freezer_latent_case_credit_curve(model)
  latent_case_credit_curve_name = 'Single Shelf Horizontal Latent Energy Multiplier_After2004'
  return latent_case_credit_curve_name
end
model_zones_with_occ_and_fuel_type(model, custom, applicable_zones = nil) click to toggle source

Categorize zones by occupancy type and fuel type, where the types depend on the standard.

@param model [OpenStudio::Model::Model] OpenStudio model object @param custom [String] custom fuel type @param applicable_zones [list of zone objects] @return [Array<Hash>] an array of hashes, one for each zone,

with the keys 'zone', 'type' (occ type), 'fuel', and 'area'
# File lib/openstudio-standards/standards/Standards.Model.rb, line 743
def model_zones_with_occ_and_fuel_type(model, custom, applicable_zones = nil)
  zones = []

  model.getThermalZones.sort.each do |zone|
    # Skip plenums
    if OpenstudioStandards::ThermalZone.thermal_zone_plenum?(zone)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Zone #{zone.name} is a plenum.  It will not be assigned a baseline system.")
      next
    end

    if !applicable_zones.nil?
      # This is only used for the stable baseline (2016 and later)
      if !applicable_zones.include?(zone)
        # This zone is not part of the current hvac_building_type
        next
      end
    end

    # Skip unconditioned zones
    heated = OpenstudioStandards::ThermalZone.thermal_zone_heated?(zone)
    cooled = OpenstudioStandards::ThermalZone.thermal_zone_cooled?(zone)
    if !heated && !cooled
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Model', "Zone #{zone.name} is unconditioned.  It will not be assigned a baseline system.")
      next
    end

    zn_hash = {}

    # The zone object
    zn_hash['zone'] = zone

    # Floor area
    zn_hash['area'] = zone.floorArea

    # Occupancy type
    zn_hash['occ'] = thermal_zone_occupancy_type(zone)

    # Building type
    zn_hash['bldg_type'] = OpenstudioStandards::ThermalZone.thermal_zone_get_building_type(zone)

    # Fuel type
    # for 2013 and prior, baseline fuel = proposed fuel
    # for 2016 and later, use fuel to identify zones with district energy
    zn_hash['fuel'] = thermal_zone_get_zone_fuels_for_occ_and_fuel_type(zone)

    zones << zn_hash
  end

  return zones
end
planar_surface_apply_standard_construction(planar_surface, climate_zone, previous_construction_map = {}, wwr_building_type = nil, wwr_info = {}, surface_category) click to toggle source

If construction properties can be found based on the template, the standards intended surface type, the standards construction type, the climate zone, and the occupancy type, create a construction that meets those properties and assign it to this surface. 90.1-2007, 90.1-2010, 90.1-2013

@param planar_surface [OpenStudio::Model:PlanarSurface] surface object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @param previous_construction_map [Hash] a hash where the keys are an array of inputs

[template, climate_zone, intended_surface_type, standards_construction_type, occ_type]
and the values are the constructions.  If supplied, constructions will be pulled
from this hash if already created to avoid creating duplicate constructions.

@return [Hash] returns a hash where the key is an array of inputs

[template, climate_zone, intended_surface_type, standards_construction_type, occ_type]
and the value is the newly created construction.
This can be used to avoid creating duplicate constructions.

@todo Align the standard construction enumerations in the spreadsheet with the enumerations in OpenStudio (follow CBECC-Com).

# File lib/openstudio-standards/standards/Standards.PlanarSurface.rb, line 22
def planar_surface_apply_standard_construction(planar_surface, climate_zone, previous_construction_map = {}, wwr_building_type = nil, wwr_info = {}, surface_category)
  # Skip surfaces not in a space
  return previous_construction_map if planar_surface.space.empty?

  space = planar_surface.space.get
  if surface_category == 'ExteriorSubSurface'
    surface_type = planar_surface.subSurfaceType
  else
    surface_type = planar_surface.surfaceType
  end

  # Skip surfaces that don't have a construction
  # return previous_construction_map if planar_surface.construction.empty?
  if !planar_surface.construction.empty?
    construction = planar_surface.construction.get
  else
    # Get appropriate default construction if not defined inside surface object
    construction = nil
    space_type = space.spaceType.get
    if space.defaultConstructionSet.is_initialized
      cons_set = space.defaultConstructionSet.get
      construction = get_default_surface_cons_from_surface_type(surface_category, surface_type, cons_set)
    end
    if construction.nil? && space_type.defaultConstructionSet.is_initialized
      cons_set = space_type.defaultConstructionSet.get
      construction = get_default_surface_cons_from_surface_type(surface_category, surface_type, cons_set)
    end
    if construction.nil? && space.buildingStory.get.defaultConstructionSet.is_initialized
      cons_set = space.buildingStory.get.defaultConstructionSet.get
      construction = get_default_surface_cons_from_surface_type(surface_category, surface_type, cons_set)
    end
    if construction.nil? && space.model.building.get.defaultConstructionSet.is_initialized
      cons_set = space.model.building.get.defaultConstructionSet.get
      construction = get_default_surface_cons_from_surface_type(surface_category, surface_type, cons_set)
    end

    return previous_construction_map if construction.nil?
  end

  # Determine if residential or nonresidential
  # based on the space type.
  occ_type = 'Nonresidential'
  if OpenstudioStandards::Space.space_residential?(space)
    occ_type = 'Residential'
  end

  # Get the climate zone set
  climate_zone_set = model_find_climate_zone_set(planar_surface.model, climate_zone)

  # Get the intended surface type
  standards_info = construction.standardsInformation
  surf_type = standards_info.intendedSurfaceType

  if surf_type.empty?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlanarSurface', "Could not determine the intended surface type for #{planar_surface.name} from #{construction.name}.  This surface will not have the standard applied.")
    return previous_construction_map
  end
  surf_type = surf_type.get

  # Get the standards type, which is based on different fields
  # if is intended for a window, a skylight, or something else.
  # Mapping is between standards-defined enumerations and the
  # enumerations available in OpenStudio.
  stds_type = nil
  # Windows and Glass Doors
  if surf_type == 'ExteriorWindow' || surf_type == 'GlassDoor'
    stds_type = standards_info.fenestrationFrameType
    if stds_type.is_initialized
      stds_type = stds_type.get
      if !wwr_building_type.nil?
        stds_type = 'Any Vertical Glazing'
      end
      case stds_type
      when 'Metal Framing', 'Metal Framing with Thermal Break'
        stds_type = 'Metal framing (all other)'
      when 'Non-Metal Framing'
        stds_type = 'Nonmetal framing (all)'
      when 'Any Vertical Glazing'
        stds_type = 'Any Vertical Glazing'
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlanarSurface', "The standards fenestration frame type #{stds_type} cannot be used on #{surf_type} in #{planar_surface.name}.  This surface will not have the standard applied.")
        return previous_construction_map
      end
    else
      if !wwr_building_type.nil?
        stds_type = 'Any Vertical Glazing'
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlanarSurface', "Could not determine the standards fenestration frame type for #{planar_surface.name} from #{construction.name}.  This surface will not have the standard applied.")
        return previous_construction_map
      end
    end
  # Skylights
  elsif surf_type == 'Skylight'
    stds_type = standards_info.fenestrationType
    if stds_type.is_initialized
      stds_type = stds_type.get
      case stds_type
      when 'Glass Skylight with Curb'
        stds_type = 'Glass with Curb'
      when 'Plastic Skylight with Curb'
        stds_type = 'Plastic with Curb'
      when 'Plastic Skylight without Curb', 'Glass Skylight without Curb'
        stds_type = 'Without Curb'
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlanarSurface', "The standards fenestration type #{stds_type} cannot be used on #{surf_type} in #{planar_surface.name}.  This surface will not have the standard applied.")
        return previous_construction_map
      end
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlanarSurface', "Could not determine the standards fenestration type for #{planar_surface.name} from #{construction.name}.  This surface will not have the standard applied.")
      return previous_construction_map
    end
  # Exterior Doors
  elsif surf_type == 'ExteriorDoor'
    stds_type = standards_info.standardsConstructionType
    if stds_type.is_initialized
      stds_type = stds_type.get
      case stds_type
      when 'RollUp', 'Rollup', 'NonSwinging', 'Nonswinging'
        stds_type = 'NonSwinging'
      else
        stds_type = 'Swinging'
      end
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlanarSurface', "Could not determine the standards construction type for exterior door #{planar_surface.name}.  This door will not have the standard applied.")
      return previous_construction_map
    end
  # All other surface types
  else
    stds_type = standards_info.standardsConstructionType
    if stds_type.is_initialized
      stds_type = stds_type.get
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlanarSurface', "Could not determine the standards construction type for #{planar_surface.name}.  This surface will not have the standard applied.")
      return previous_construction_map
    end
  end

  # Check if the construction type was already created.
  # If yes, use that construction.  If no, make a new one.

  # for multi-building type - search for the surface wwr type
  surface_std_wwr_type = wwr_building_type
  new_construction = nil
  type = [template, climate_zone, surf_type, stds_type, occ_type]
  # Only apply the surface_std_wwr_type update when wwr_building_type has Truthy values
  if !wwr_building_type.nil? && (surf_type == 'ExteriorWindow' || surf_type == 'GlassDoor')
    space = planar_surface.space.get
    if space.hasAdditionalProperties && space.additionalProperties.hasFeature('building_type_for_wwr')
      surface_std_wwr_type = space.additionalProperties.getFeatureAsString('building_type_for_wwr').get
    end
    type.push(surface_std_wwr_type)
  end

  if previous_construction_map[type]
    new_construction = previous_construction_map[type]
  else
    new_construction = model_find_and_add_construction(planar_surface.model,
                                                       climate_zone_set,
                                                       surf_type,
                                                       stds_type,
                                                       occ_type,
                                                       wwr_building_type: surface_std_wwr_type,
                                                       wwr_info: wwr_info)
    if !new_construction == false
      previous_construction_map[type] = new_construction
    end
  end

  # Assign the new construction to the surface
  if new_construction
    planar_surface.setConstruction(new_construction)
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.PlanarSurface', "Set the construction for #{planar_surface.name} to #{new_construction.name}.")
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlanarSurface', "Could not generate a standard construction for #{planar_surface.name}.")
    return previous_construction_map
  end

  return previous_construction_map
end
plant_loop_adiabatic_pipes_only(plant_loop) click to toggle source

This methods replaces all indoor or outdoor pipes which model the heat transfer between the pipe and the environement by adiabatic pipes.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if successful

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 1520
def plant_loop_adiabatic_pipes_only(plant_loop)
  supply_side_components = plant_loop.supplyComponents
  demand_side_components = plant_loop.demandComponents
  plant_loop_components = supply_side_components += demand_side_components
  plant_loop_components.each do |component|
    # Get the object type
    obj_type = component.iddObjectType.valueName.to_s
    next unless ['OS_Pipe_Indoor', 'OS_Pipe_Outdoor'].include?(obj_type)

    # Get pipe object
    pipe = nil
    case obj_type
    when 'OS_Pipe_Indoor'
      pipe = component.to_PipeIndoor.get
    when 'OS_Pipe_Outdoor'
      pipe = component.to_PipeOutdoor.get
    end

    # Get pipe node
    node = prm_get_optional_handler(pipe, @sizing_run_dir, 'to_StraightComponent', 'outletModelObject', 'to_Node')

    # Get pipe and node names
    node_name = node.name.get
    pipe_name = pipe.name.get

    # Replace indoor or outdoor pipe by an adiabatic pipe
    new_pipe = OpenStudio::Model::PipeAdiabatic.new(plant_loop.model)
    new_pipe.setName(pipe_name)
    new_pipe.addToNode(node)
    component.remove
  end
  return true
end
plant_loop_apply_prm_baseline_chilled_water_pumping_type(plant_loop) click to toggle source

Applies the chilled water pumping controls to the loop based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] chilled water loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 783
def plant_loop_apply_prm_baseline_chilled_water_pumping_type(plant_loop)
  # Determine the pumping type.
  minimum_cap_tons = 300.0

  # Determine the capacity
  cap_w = plant_loop_total_cooling_capacity(plant_loop)
  cap_tons = OpenStudio.convert(cap_w, 'W', 'ton').get

  # Determine if it a district cooling system
  has_district_cooling = false
  plant_loop.supplyComponents.each do |sc|
    if sc.to_DistrictCooling.is_initialized
      has_district_cooling = true
    end
  end

  # Determine the primary and secondary pumping types
  pri_control_type = nil
  sec_control_type = nil
  if has_district_cooling
    pri_control_type = if cap_tons > minimum_cap_tons
                         'VSD No Reset'
                       else
                         'Riding Curve'
                       end
  else
    pri_control_type = 'Constant Flow'
    sec_control_type = if cap_tons > minimum_cap_tons
                         'VSD No Reset'
                       else
                         'Riding Curve'
                       end
  end

  # Report out the pumping type
  unless pri_control_type.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, primary pump type is #{pri_control_type}.")
  end

  unless sec_control_type.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, secondary pump type is #{sec_control_type}.")
  end

  # Modify all the primary pumps
  plant_loop.supplyComponents.each do |sc|
    if sc.to_PumpVariableSpeed.is_initialized
      pump = sc.to_PumpVariableSpeed.get
      pump_variable_speed_set_control_type(pump, pri_control_type)
    elsif sc.to_HeaderedPumpsVariableSpeed.is_initialized
      pump = sc.to_HeaderedPumpsVariableSpeed.get
      headered_pump_variable_speed_set_control_type(pump, control_type)
    end
  end

  # Modify all the secondary pumps besides constant pumps
  plant_loop.demandComponents.each do |sc|
    if sc.to_PumpVariableSpeed.is_initialized
      pump = sc.to_PumpVariableSpeed.get
      pump_variable_speed_set_control_type(pump, sec_control_type)
    elsif sc.to_HeaderedPumpsVariableSpeed.is_initialized
      pump = sc.to_HeaderedPumpsVariableSpeed.get
      headered_pump_variable_speed_set_control_type(pump, control_type)
    end
  end

  return true
end
plant_loop_apply_prm_baseline_chilled_water_temperatures(plant_loop) click to toggle source

Applies the chilled water temperatures to the plant loop based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 248
def plant_loop_apply_prm_baseline_chilled_water_temperatures(plant_loop)
  sizing_plant = plant_loop.sizingPlant

  # Loop properties
  # G3.1.3.8 - LWT 44 / EWT 56
  chw_temp_f = 44
  chw_delta_t_r = 12
  min_temp_f = 34
  max_temp_f = 200
  # For water-cooled chillers this is the water temperature entering the condenser (e.g., leaving the cooling tower).
  ref_cond_wtr_temp_f = 85

  chw_temp_c = OpenStudio.convert(chw_temp_f, 'F', 'C').get
  chw_delta_t_k = OpenStudio.convert(chw_delta_t_r, 'R', 'K').get
  min_temp_c = OpenStudio.convert(min_temp_f, 'F', 'C').get
  max_temp_c = OpenStudio.convert(max_temp_f, 'F', 'C').get
  ref_cond_wtr_temp_c = OpenStudio.convert(ref_cond_wtr_temp_f, 'F', 'C').get

  sizing_plant.setDesignLoopExitTemperature(chw_temp_c)
  sizing_plant.setLoopDesignTemperatureDifference(chw_delta_t_k)
  plant_loop.setMinimumLoopTemperature(min_temp_c)
  plant_loop.setMaximumLoopTemperature(max_temp_c)

  # ASHRAE Appendix G - G3.1.3.9 (for ASHRAE 90.1-2004, 2007 and 2010)
  # ChW reset: 44F at 80F and above, 54F at 60F and below
  plant_loop_enable_supply_water_temperature_reset(plant_loop)

  # Chiller properties
  plant_loop.supplyComponents.each do |sc|
    if sc.to_ChillerElectricEIR.is_initialized
      chiller = sc.to_ChillerElectricEIR.get
      chiller.setReferenceLeavingChilledWaterTemperature(chw_temp_c)
      chiller.setReferenceEnteringCondenserFluidTemperature(ref_cond_wtr_temp_c)
    end
  end

  return true
end
plant_loop_apply_prm_baseline_condenser_water_pumping_type(plant_loop) click to toggle source

Applies the condenser water pumping controls to the loop based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] condenser water loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 890
def plant_loop_apply_prm_baseline_condenser_water_pumping_type(plant_loop)
  # All condenser water loops are constant flow
  control_type = 'Constant Flow'

  # Report out the pumping type
  unless control_type.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, pump type is #{control_type}.")
  end

  # Modify all primary pumps
  plant_loop.supplyComponents.each do |sc|
    if sc.to_PumpVariableSpeed.is_initialized
      pump = sc.to_PumpVariableSpeed.get
      pump_variable_speed_set_control_type(pump, control_type)
    elsif sc.to_HeaderedPumpsVariableSpeed.is_initialized
      pump = sc.to_HeaderedPumpsVariableSpeed.get
      headered_pump_variable_speed_set_control_type(pump, control_type)
    end
  end

  return true
end
plant_loop_apply_prm_baseline_condenser_water_temperatures(plant_loop) click to toggle source

Applies the condenser water temperatures to the plant loop based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 291
def plant_loop_apply_prm_baseline_condenser_water_temperatures(plant_loop)
  sizing_plant = plant_loop.sizingPlant
  loop_type = sizing_plant.loopType
  return true unless loop_type == 'Condenser'

  # Much of the thought in this section came from @jmarrec

  # Determine the design OATwb from the design days.
  # Per https://unmethours.com/question/16698/which-cooling-design-day-is-most-common-for-sizing-rooftop-units/
  # the WB=>MDB day is used to size cooling towers.
  summer_oat_wbs_f = []
  plant_loop.model.getDesignDays.sort.each do |dd|
    next unless dd.dayType == 'SummerDesignDay'
    next unless dd.name.get.to_s.include?('WB=>MDB')

    if plant_loop.model.version < OpenStudio::VersionString.new('3.3.0')
      if dd.humidityIndicatingType == 'Wetbulb'
        summer_oat_wb_c = dd.humidityIndicatingConditionsAtMaximumDryBulb
        summer_oat_wbs_f << OpenStudio.convert(summer_oat_wb_c, 'C', 'F').get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{dd.name}, humidity is specified as #{dd.humidityIndicatingType}; cannot determine Twb.")
      end
    else
      if dd.humidityConditionType == 'Wetbulb' && dd.wetBulbOrDewPointAtMaximumDryBulb.is_initialized
        summer_oat_wbs_f << OpenStudio.convert(dd.wetBulbOrDewPointAtMaximumDryBulb.get, 'C', 'F').get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{dd.name}, humidity is specified as #{dd.humidityConditionType}; cannot determine Twb.")
      end
    end
  end

  # Use the value from the design days or 78F, the CTI rating condition, if no design day information is available.
  design_oat_wb_f = nil
  if summer_oat_wbs_f.size.zero?
    design_oat_wb_f = 78
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, no design day OATwb conditions were found.  CTI rating condition of 78F OATwb will be used for sizing cooling towers.")
  else
    # Take worst case condition
    design_oat_wb_f = summer_oat_wbs_f.max
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "The maximum design wet bulb temperature from the Summer Design Day WB=>MDB is #{design_oat_wb_f} F")
  end

  # There is an EnergyPlus model limitation that the design_oat_wb_f < 80F for cooling towers
  ep_max_design_oat_wb_f = 80
  if design_oat_wb_f > ep_max_design_oat_wb_f
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, reduced design OATwb from #{design_oat_wb_f.round(1)} F to E+ model max input of #{ep_max_design_oat_wb_f} F.")
    design_oat_wb_f = ep_max_design_oat_wb_f
  end

  # Determine the design CW temperature, approach, and range
  design_oat_wb_c = OpenStudio.convert(design_oat_wb_f, 'F', 'C').get
  leaving_cw_t_c, approach_k, range_k = plant_loop_prm_baseline_condenser_water_temperatures(plant_loop, design_oat_wb_c)

  # Convert to IP units
  leaving_cw_t_f = OpenStudio.convert(leaving_cw_t_c, 'C', 'F').get
  approach_r = OpenStudio.convert(approach_k, 'K', 'R').get
  range_r = OpenStudio.convert(range_k, 'K', 'R').get

  # Report out design conditions
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, design OATwb = #{design_oat_wb_f.round(1)} F, approach = #{approach_r.round(1)} deltaF, range = #{range_r.round(1)} deltaF, leaving condenser water temperature = #{leaving_cw_t_f.round(1)} F.")

  # Set the CW sizing parameters
  sizing_plant.setDesignLoopExitTemperature(leaving_cw_t_c)
  sizing_plant.setLoopDesignTemperatureDifference(range_k)

  # Set Cooling Tower sizing parameters.
  # Only the variable speed cooling tower in E+ allows you to set the design temperatures.
  #
  # Per the documentation
  # http://bigladdersoftware.com/epx/docs/8-4/input-output-reference/group-condenser-equipment.html#field-design-u-factor-times-area-value
  # for CoolingTowerSingleSpeed and CoolingTowerTwoSpeed
  # E+ uses the following values during sizing:
  # 95F entering water temp
  # 95F OATdb
  # 78F OATwb
  # range = loop design delta-T aka range (specified above)
  plant_loop.supplyComponents.each do |sc|
    if sc.to_CoolingTowerVariableSpeed.is_initialized
      ct = sc.to_CoolingTowerVariableSpeed.get
      # E+ has a minimum limit of 68F (20C) for this field.
      # Check against limit before attempting to set value.
      eplus_design_oat_wb_c_lim = 20
      if design_oat_wb_c < eplus_design_oat_wb_c_lim
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, a design OATwb of 68F will be used for sizing the cooling towers because the actual design value is below the limit EnergyPlus accepts for this input.")
        design_oat_wb_c = eplus_design_oat_wb_c_lim
      end
      ct.setDesignInletAirWetBulbTemperature(design_oat_wb_c)
      ct.setDesignApproachTemperature(approach_k)
      ct.setDesignRangeTemperature(range_k)
    end
  end

  # Set the min and max CW temps
  # Typical design of min temp is really around 40F
  # (that's what basin heaters, when used, are sized for usually)
  min_temp_f = 34
  max_temp_f = 200
  min_temp_c = OpenStudio.convert(min_temp_f, 'F', 'C').get
  max_temp_c = OpenStudio.convert(max_temp_f, 'F', 'C').get
  plant_loop.setMinimumLoopTemperature(min_temp_c)
  plant_loop.setMaximumLoopTemperature(max_temp_c)

  # Cooling Tower operational controls
  # G3.1.3.11 - Tower shall be controlled to maintain a 70F LCnWT where weather permits,
  # floating up to leaving water at design conditions.
  float_down_to_f = 70
  float_down_to_c = OpenStudio.convert(float_down_to_f, 'F', 'C').get

  cw_t_stpt_manager = nil
  plant_loop.supplyOutletNode.setpointManagers.each do |spm|
    if spm.to_SetpointManagerFollowOutdoorAirTemperature.is_initialized
      if spm.name.get.include? 'Setpoint Manager Follow OATwb'
        cw_t_stpt_manager = spm.to_SetpointManagerFollowOutdoorAirTemperature.get
      end
    end
  end
  if cw_t_stpt_manager.nil?
    cw_t_stpt_manager = OpenStudio::Model::SetpointManagerFollowOutdoorAirTemperature.new(plant_loop.model)
    cw_t_stpt_manager.addToNode(plant_loop.supplyOutletNode)
  end
  cw_t_stpt_manager.setName("#{plant_loop.name} Setpoint Manager Follow OATwb with #{approach_r.round(1)}F Approach")
  cw_t_stpt_manager.setReferenceTemperatureType('OutdoorAirWetBulb')
  # At low design OATwb, it is possible to calculate
  # a maximum temperature below the minimum.  In this case,
  # make the maximum and minimum the same.
  if leaving_cw_t_c < float_down_to_c
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, the maximum leaving temperature of #{leaving_cw_t_f.round(1)} F is below the minimum of #{float_down_to_f.round(1)} F.  The maximum will be set to the same value as the minimum.")
    leaving_cw_t_c = float_down_to_c
  end
  cw_t_stpt_manager.setMaximumSetpointTemperature(leaving_cw_t_c)
  cw_t_stpt_manager.setMinimumSetpointTemperature(float_down_to_c)
  cw_t_stpt_manager.setOffsetTemperatureDifference(approach_k)
  return true
end
plant_loop_apply_prm_baseline_hot_water_pumping_type(plant_loop) click to toggle source

Applies the hot water pumping controls to the loop based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] hot water loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 855
def plant_loop_apply_prm_baseline_hot_water_pumping_type(plant_loop)
  # Determine the minimum area to determine
  # pumping type.
  minimum_area_ft2 = 120_000

  # Determine the area served
  area_served_m2 = plant_loop_total_floor_area_served(plant_loop)
  area_served_ft2 = OpenStudio.convert(area_served_m2, 'm^2', 'ft^2').get

  # Determine the pump type
  control_type = 'Riding Curve'
  if area_served_ft2 > minimum_area_ft2
    control_type = 'VSD No Reset'
  end

  # Modify all the primary pumps
  plant_loop.supplyComponents.each do |sc|
    if sc.to_PumpVariableSpeed.is_initialized
      pump = sc.to_PumpVariableSpeed.get
      pump_variable_speed_set_control_type(pump, control_type)
    end
  end

  # Report out the pumping type
  unless control_type.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, pump type is #{control_type}.")
  end

  return true
end
plant_loop_apply_prm_baseline_hot_water_temperatures(plant_loop) click to toggle source

Applies the hot water temperatures to the plant loop based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 211
def plant_loop_apply_prm_baseline_hot_water_temperatures(plant_loop)
  sizing_plant = plant_loop.sizingPlant

  # Loop properties
  # G3.1.3.3 - HW Supply at 180F, return at 130F
  hw_temp_f = 180
  hw_delta_t_r = 50
  min_temp_f = 50

  hw_temp_c = OpenStudio.convert(hw_temp_f, 'F', 'C').get
  hw_delta_t_k = OpenStudio.convert(hw_delta_t_r, 'R', 'K').get
  min_temp_c = OpenStudio.convert(min_temp_f, 'F', 'C').get

  sizing_plant.setDesignLoopExitTemperature(hw_temp_c)
  sizing_plant.setLoopDesignTemperatureDifference(hw_delta_t_k)
  plant_loop.setMinimumLoopTemperature(min_temp_c)

  # ASHRAE Appendix G - G3.1.3.4 (for ASHRAE 90.1-2004, 2007 and 2010)
  # HW reset: 180F at 20F and below, 150F at 50F and above
  plant_loop_enable_supply_water_temperature_reset(plant_loop)

  # Boiler properties
  if plant_loop.model.version < OpenStudio::VersionString.new('3.0.0')
    plant_loop.supplyComponents.each do |sc|
      if sc.to_BoilerHotWater.is_initialized
        boiler = sc.to_BoilerHotWater.get
        boiler.setDesignWaterOutletTemperature(hw_temp_c)
      end
    end
  end
  return true
end
plant_loop_apply_prm_baseline_pump_power(plant_loop) click to toggle source

apply prm baseline pump power @note I think it makes more sense to sense the motor efficiency right there…

But actually it's completely irrelevant...
you could set at 0.9 and just calculate the pressure rise to have your 19 W/GPM or whatever

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 94
def plant_loop_apply_prm_baseline_pump_power(plant_loop)
  # Determine the pumping power per
  # flow based on loop type.
  pri_w_per_gpm = nil
  sec_w_per_gpm = nil

  sizing_plant = plant_loop.sizingPlant
  loop_type = sizing_plant.loopType

  case loop_type
    when 'Heating'

      has_district_heating = false
      plant_loop.supplyComponents.each do |sc|
        if sc.iddObjectType.valueName.to_s.include?('DistrictHeating')
          has_district_heating = true
        end
      end

      pri_w_per_gpm = if has_district_heating # District HW
                        14.0
                      else # HW
                        19.0
                      end

    when 'Cooling'

      has_district_cooling = false
      plant_loop.supplyComponents.each do |sc|
        if sc.to_DistrictCooling.is_initialized
          has_district_cooling = true
        end
      end

      has_secondary_pump = false
      plant_loop.demandComponents.each do |sc|
        if sc.to_PumpConstantSpeed.is_initialized || sc.to_PumpVariableSpeed.is_initialized
          has_secondary_pump = true
        end
      end

      if has_district_cooling # District CHW
        pri_w_per_gpm = 16.0
      elsif has_secondary_pump # Primary/secondary CHW
        pri_w_per_gpm = 9.0
        sec_w_per_gpm = 13.0
      else # Primary only CHW
        pri_w_per_gpm = 22.0
      end

    when 'Condenser'

      # @todo prm condenser loop pump power
      pri_w_per_gpm = 19.0

  end

  # Modify all the primary pumps
  plant_loop.supplyComponents.each do |sc|
    if sc.to_PumpConstantSpeed.is_initialized
      pump = sc.to_PumpConstantSpeed.get
      pump_apply_prm_pressure_rise_and_motor_efficiency(pump, pri_w_per_gpm)
    elsif sc.to_PumpVariableSpeed.is_initialized
      pump = sc.to_PumpVariableSpeed.get
      pump_apply_prm_pressure_rise_and_motor_efficiency(pump, pri_w_per_gpm)
    elsif sc.to_HeaderedPumpsConstantSpeed.is_initialized
      pump = sc.to_HeaderedPumpsConstantSpeed.get
      pump_apply_prm_pressure_rise_and_motor_efficiency(pump, pri_w_per_gpm)
    elsif sc.to_HeaderedPumpsVariableSpeed.is_initialized
      pump = sc.to_HeaderedPumpsVariableSpeed.get
      pump_apply_prm_pressure_rise_and_motor_efficiency(pump, pri_w_per_gpm)
    end
  end

  # Modify all the secondary pumps
  plant_loop.demandComponents.each do |sc|
    if sc.to_PumpConstantSpeed.is_initialized
      pump = sc.to_PumpConstantSpeed.get
      pump_apply_prm_pressure_rise_and_motor_efficiency(pump, sec_w_per_gpm)
    elsif sc.to_PumpVariableSpeed.is_initialized
      pump = sc.to_PumpVariableSpeed.get
      pump_apply_prm_pressure_rise_and_motor_efficiency(pump, sec_w_per_gpm)
    elsif sc.to_HeaderedPumpsConstantSpeed.is_initialized
      pump = sc.to_HeaderedPumpsConstantSpeed.get
      pump_apply_prm_pressure_rise_and_motor_efficiency(pump, pri_w_per_gpm)
    elsif sc.to_HeaderedPumpsVariableSpeed.is_initialized
      pump = sc.to_HeaderedPumpsVariableSpeed.get
      pump_apply_prm_pressure_rise_and_motor_efficiency(pump, pri_w_per_gpm)
    end
  end

  return true
end
plant_loop_apply_prm_baseline_pumping_type(plant_loop) click to toggle source

Applies the pumping controls to the loop based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 763
def plant_loop_apply_prm_baseline_pumping_type(plant_loop)
  sizing_plant = plant_loop.sizingPlant
  loop_type = sizing_plant.loopType

  case loop_type
    when 'Heating'
      plant_loop_apply_prm_baseline_hot_water_pumping_type(plant_loop)
    when 'Cooling'
      plant_loop_apply_prm_baseline_chilled_water_pumping_type(plant_loop)
    when 'Condenser'
      plant_loop_apply_prm_baseline_condenser_water_pumping_type(plant_loop)
  end

  return true
end
plant_loop_apply_prm_baseline_temperatures(plant_loop) click to toggle source

Applies the temperatures to the plant loop based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 192
def plant_loop_apply_prm_baseline_temperatures(plant_loop)
  sizing_plant = plant_loop.sizingPlant
  loop_type = sizing_plant.loopType
  case loop_type
    when 'Heating'
      plant_loop_apply_prm_baseline_hot_water_temperatures(plant_loop)
    when 'Cooling'
      plant_loop_apply_prm_baseline_chilled_water_temperatures(plant_loop)
    when 'Condenser'
      plant_loop_apply_prm_baseline_condenser_water_temperatures(plant_loop)
  end

  return true
end
plant_loop_apply_prm_number_of_boilers(plant_loop) click to toggle source

Splits the single boiler used for the initial sizing run into multiple separate boilers based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] hot water loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 918
def plant_loop_apply_prm_number_of_boilers(plant_loop)
  # Skip non-heating plants
  return true unless plant_loop.sizingPlant.loopType == 'Heating'

  # Determine the minimum area to determine
  # number of boilers.
  minimum_area_ft2 = 15_000

  # Determine the area served
  area_served_m2 = plant_loop_total_floor_area_served(plant_loop)
  area_served_ft2 = OpenStudio.convert(area_served_m2, 'm^2', 'ft^2').get

  # Do nothing if only one boiler is required
  return true if area_served_ft2 < minimum_area_ft2

  # Get all existing boilers
  boilers = []
  plant_loop.supplyComponents.each do |sc|
    if sc.to_BoilerHotWater.is_initialized
      boilers << sc.to_BoilerHotWater.get
    end
  end

  # Ensure there is only 1 boiler to start
  first_boiler = nil
  return true if boilers.size.zero?

  if boilers.size > 1
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, found #{boilers.size}, cannot split up per performance rating method baseline requirements.")
  else
    first_boiler = boilers[0]
  end

  # Clone the existing boiler and create
  # a new branch for it
  second_boiler = first_boiler.clone(plant_loop.model)
  if second_boiler.to_BoilerHotWater.is_initialized
    second_boiler = second_boiler.to_BoilerHotWater.get
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, could not clone boiler #{first_boiler.name}, cannot apply the performance rating method number of boilers.")
    return false
  end
  plant_loop.addSupplyBranchForComponent(second_boiler)
  final_boilers = [first_boiler, second_boiler]
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, added a second boiler.")

  # Rename boilers and set the sizing factor
  sizing_factor = (1.0 / final_boilers.size).round(2)
  final_boilers.each_with_index do |boiler, i|
    boiler.setName("#{plant_loop.name} Boiler #{i + 1} of #{final_boilers.size}")
    boiler.setSizingFactor(sizing_factor)
  end

  # Set the equipment to stage sequentially
  plant_loop.setLoadDistributionScheme('SequentialLoad')

  return true
end
plant_loop_apply_prm_number_of_chillers(plant_loop, sizing_run_dir = nil) click to toggle source

Splits the single chiller used for the initial sizing run into multiple separate chillers based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] chilled water loop @param sizing_run_dir [String] sizing run directory @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 983
def plant_loop_apply_prm_number_of_chillers(plant_loop, sizing_run_dir = nil)
  # Skip non-cooling plants
  return true unless plant_loop.sizingPlant.loopType == 'Cooling'

  # Determine the number and type of chillers
  num_chillers = nil
  chiller_cooling_type = nil
  chiller_compressor_type = nil

  # Determine the capacity of the loop
  cap_w = plant_loop_total_cooling_capacity(plant_loop)
  cap_tons = OpenStudio.convert(cap_w, 'W', 'ton').get
  if cap_tons <= 300
    num_chillers = 1
    chiller_cooling_type = 'WaterCooled'
    chiller_compressor_type = 'Rotary Screw'
  elsif cap_tons > 300 && cap_tons < 600
    num_chillers = 2
    chiller_cooling_type = 'WaterCooled'
    chiller_compressor_type = 'Rotary Screw'
  else
    # Max capacity of a single chiller
    max_cap_ton = 800.0
    num_chillers = (cap_tons / max_cap_ton).floor + 1
    # Must be at least 2 chillers
    num_chillers += 1 if num_chillers == 1
    chiller_cooling_type = 'WaterCooled'
    chiller_compressor_type = 'Centrifugal'
  end

  # Get all existing chillers and pumps
  chillers = []
  pumps = []
  plant_loop.supplyComponents.each do |sc|
    if sc.to_ChillerElectricEIR.is_initialized
      chillers << sc.to_ChillerElectricEIR.get
    elsif sc.to_PumpConstantSpeed.is_initialized
      pumps << sc.to_PumpConstantSpeed.get
    elsif sc.to_PumpVariableSpeed.is_initialized
      pumps << sc.to_PumpVariableSpeed.get
    end
  end

  # Ensure there is only 1 chiller to start
  first_chiller = nil
  return true if chillers.size.zero?

  if chillers.size > 1
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, found #{chillers.size} chillers, cannot split up per performance rating method baseline requirements.")
  else
    first_chiller = chillers[0]
  end

  # Ensure there is only 1 pump to start
  orig_pump = nil
  if pumps.size.zero?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, found #{pumps.size} pumps.  A loop must have at least one pump.")
    return false
  elsif pumps.size > 1
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, found #{pumps.size} pumps, cannot split up per performance rating method baseline requirements.")
    return false
  else
    orig_pump = pumps[0]
  end

  # Determine the per-chiller capacity
  # and sizing factor
  per_chiller_sizing_factor = (1.0 / num_chillers).round(2)
  # This is unused
  per_chiller_cap_tons = cap_tons / num_chillers

  # Set the sizing factor and the chiller type: could do it on the first chiller before cloning it, but renaming warrants looping on chillers anyways

  # Add any new chillers
  final_chillers = [first_chiller]
  (num_chillers - 1).times do
    new_chiller = first_chiller.clone(plant_loop.model)
    if new_chiller.to_ChillerElectricEIR.is_initialized
      new_chiller = new_chiller.to_ChillerElectricEIR.get
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, could not clone chiller #{first_chiller.name}, cannot apply the performance rating method number of chillers.")
      return false
    end
    # Connect the new chiller to the same CHW loop
    # as the old chiller.
    plant_loop.addSupplyBranchForComponent(new_chiller)
    # Connect the new chiller to the same CW loop
    # as the old chiller, if it was water-cooled.
    cw_loop = first_chiller.secondaryPlantLoop
    if cw_loop.is_initialized
      cw_loop.get.addDemandBranchForComponent(new_chiller)
    end

    final_chillers << new_chiller
  end

  # If there is more than one cooling tower,
  # replace the original pump with a headered pump
  # of the same type and properties.
  if final_chillers.size > 1
    num_pumps = final_chillers.size
    new_pump = nil
    if orig_pump.to_PumpConstantSpeed.is_initialized
      new_pump = OpenStudio::Model::HeaderedPumpsConstantSpeed.new(plant_loop.model)
      new_pump.setNumberofPumpsinBank(num_pumps)
      new_pump.setName("#{orig_pump.name} Bank of #{num_pumps}")
      new_pump.setRatedPumpHead(orig_pump.ratedPumpHead)
      new_pump.setMotorEfficiency(orig_pump.motorEfficiency)
      new_pump.setFractionofMotorInefficienciestoFluidStream(orig_pump.fractionofMotorInefficienciestoFluidStream)
      new_pump.setPumpControlType(orig_pump.pumpControlType)
    elsif orig_pump.to_PumpVariableSpeed.is_initialized
      new_pump = OpenStudio::Model::HeaderedPumpsVariableSpeed.new(plant_loop.model)
      new_pump.setNumberofPumpsinBank(num_pumps)
      new_pump.setName("#{orig_pump.name} Bank of #{num_pumps}")
      new_pump.setRatedPumpHead(orig_pump.ratedPumpHead)
      new_pump.setMotorEfficiency(orig_pump.motorEfficiency)
      new_pump.setFractionofMotorInefficienciestoFluidStream(orig_pump.fractionofMotorInefficienciestoFluidStream)
      new_pump.setPumpControlType(orig_pump.pumpControlType)
      new_pump.setCoefficient1ofthePartLoadPerformanceCurve(orig_pump.coefficient1ofthePartLoadPerformanceCurve)
      new_pump.setCoefficient2ofthePartLoadPerformanceCurve(orig_pump.coefficient2ofthePartLoadPerformanceCurve)
      new_pump.setCoefficient3ofthePartLoadPerformanceCurve(orig_pump.coefficient3ofthePartLoadPerformanceCurve)
      new_pump.setCoefficient4ofthePartLoadPerformanceCurve(orig_pump.coefficient4ofthePartLoadPerformanceCurve)
    end
    # Remove the old pump
    orig_pump.remove
    # Attach the new headered pumps
    new_pump.addToNode(plant_loop.supplyInletNode)
  end

  # Set the sizing factor and the chiller types
  final_chillers.each_with_index do |final_chiller, i|
    final_chiller.setName("#{template} #{chiller_cooling_type} #{chiller_compressor_type} Chiller #{i + 1} of #{final_chillers.size}")
    final_chiller.setSizingFactor(per_chiller_sizing_factor)
    final_chiller.setCondenserType(chiller_cooling_type)
  end
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, there are #{final_chillers.size} #{chiller_cooling_type} #{chiller_compressor_type} chillers.")

  # Set the equipment to stage sequentially
  plant_loop.setLoadDistributionScheme('SequentialLoad')

  return true
end
plant_loop_apply_prm_number_of_cooling_towers(plant_loop) click to toggle source

Splits the single cooling tower used for the initial sizing run into multiple separate cooling towers based on Appendix G.

@param plant_loop [OpenStudio::Model::PlantLoop] condenser water loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 1131
def plant_loop_apply_prm_number_of_cooling_towers(plant_loop)
  # Skip non-cooling plants
  return true unless plant_loop.sizingPlant.loopType == 'Condenser'

  # Determine the number of chillers
  # already in the model
  num_chillers = plant_loop.model.getChillerElectricEIRs.size

  # Get all existing cooling towers and pumps
  clg_twrs = []
  pumps = []
  plant_loop.supplyComponents.each do |sc|
    if sc.to_CoolingTowerSingleSpeed.is_initialized
      clg_twrs << sc.to_CoolingTowerSingleSpeed.get
    elsif sc.to_CoolingTowerTwoSpeed.is_initialized
      clg_twrs << sc.to_CoolingTowerTwoSpeed.get
    elsif sc.to_CoolingTowerVariableSpeed.is_initialized
      clg_twrs << sc.to_CoolingTowerVariableSpeed.get
    elsif sc.to_PumpConstantSpeed.is_initialized
      pumps << sc.to_PumpConstantSpeed.get
    elsif sc.to_PumpVariableSpeed.is_initialized
      pumps << sc.to_PumpVariableSpeed.get
    end
  end

  # Ensure there is only 1 cooling tower to start
  orig_twr = nil
  return true if clg_twrs.size.zero?

  if clg_twrs.size > 1
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, found #{clg_twrs.size} cooling towers, cannot split up per performance rating method baseline requirements.")
    return false
  else
    orig_twr = clg_twrs[0]
  end

  # Ensure there is only 1 pump to start
  orig_pump = nil
  if pumps.size.zero?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, found #{pumps.size} pumps.  A loop must have at least one pump.")
    return false
  elsif pumps.size > 1
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, found #{pumps.size} pumps, cannot split up per performance rating method baseline requirements.")
    return false
  else
    orig_pump = pumps[0]
  end

  # Determine the per-cooling_tower sizing factor
  clg_twr_sizing_factor = (1.0 / num_chillers).round(2)

  # Add a cooling tower for each chiller.
  # Add an accompanying CW pump for each cooling tower.
  final_twrs = [orig_twr]
  new_twr = nil
  (num_chillers - 1).times do
    if orig_twr.to_CoolingTowerSingleSpeed.is_initialized
      new_twr = orig_twr.clone(plant_loop.model)
      new_twr = new_twr.to_CoolingTowerSingleSpeed.get
    elsif orig_twr.to_CoolingTowerTwoSpeed.is_initialized
      new_twr = orig_twr.clone(plant_loop.model)
      new_twr = new_twr.to_CoolingTowerTwoSpeed.get
    elsif orig_twr.to_CoolingTowerVariableSpeed.is_initialized
      # @todo remove workaround after resolving
      # https://github.com/NREL/OpenStudio/issues/2212
      # Workaround is to create a new tower
      # and replicate all the properties of the first tower.
      new_twr = OpenStudio::Model::CoolingTowerVariableSpeed.new(plant_loop.model)
      new_twr.setName(orig_twr.name.get.to_s)
      new_twr.setDesignInletAirWetBulbTemperature(orig_twr.designInletAirWetBulbTemperature.get)
      new_twr.setDesignApproachTemperature(orig_twr.designApproachTemperature.get)
      new_twr.setDesignRangeTemperature(orig_twr.designRangeTemperature.get)
      new_twr.setFractionofTowerCapacityinFreeConvectionRegime(orig_twr.fractionofTowerCapacityinFreeConvectionRegime.get)
      if orig_twr.fanPowerRatioFunctionofAirFlowRateRatioCurve.is_initialized
        new_twr.setFanPowerRatioFunctionofAirFlowRateRatioCurve(orig_twr.fanPowerRatioFunctionofAirFlowRateRatioCurve.get)
      end
    else
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, could not clone cooling tower #{orig_twr.name}, cannot apply the performance rating method number of cooling towers.")
      return false
    end

    # Connect the new cooling tower to the CW loop
    plant_loop.addSupplyBranchForComponent(new_twr)
    new_twr_inlet = new_twr.inletModelObject.get.to_Node.get

    final_twrs << new_twr
  end

  # If there is more than one cooling tower,
  # replace the original pump with a headered pump
  # of the same type and properties.
  if final_twrs.size > 1
    num_pumps = final_twrs.size
    new_pump = nil
    if orig_pump.to_PumpConstantSpeed.is_initialized
      new_pump = OpenStudio::Model::HeaderedPumpsConstantSpeed.new(plant_loop.model)
      new_pump.setNumberofPumpsinBank(num_pumps)
      new_pump.setName("#{orig_pump.name} Bank of #{num_pumps}")
      new_pump.setRatedPumpHead(orig_pump.ratedPumpHead)
      new_pump.setMotorEfficiency(orig_pump.motorEfficiency)
      new_pump.setFractionofMotorInefficienciestoFluidStream(orig_pump.fractionofMotorInefficienciestoFluidStream)
      new_pump.setPumpControlType(orig_pump.pumpControlType)
    elsif orig_pump.to_PumpVariableSpeed.is_initialized
      new_pump = OpenStudio::Model::HeaderedPumpsVariableSpeed.new(plant_loop.model)
      new_pump.setNumberofPumpsinBank(num_pumps)
      new_pump.setName("#{orig_pump.name} Bank of #{num_pumps}")
      new_pump.setRatedPumpHead(orig_pump.ratedPumpHead)
      new_pump.setMotorEfficiency(orig_pump.motorEfficiency)
      new_pump.setFractionofMotorInefficienciestoFluidStream(orig_pump.fractionofMotorInefficienciestoFluidStream)
      new_pump.setPumpControlType(orig_pump.pumpControlType)
      new_pump.setCoefficient1ofthePartLoadPerformanceCurve(orig_pump.coefficient1ofthePartLoadPerformanceCurve)
      new_pump.setCoefficient2ofthePartLoadPerformanceCurve(orig_pump.coefficient2ofthePartLoadPerformanceCurve)
      new_pump.setCoefficient3ofthePartLoadPerformanceCurve(orig_pump.coefficient3ofthePartLoadPerformanceCurve)
      new_pump.setCoefficient4ofthePartLoadPerformanceCurve(orig_pump.coefficient4ofthePartLoadPerformanceCurve)
    end
    # Remove the old pump
    orig_pump.remove
    # Attach the new headered pumps
    new_pump.addToNode(plant_loop.supplyInletNode)
  end

  # Set the sizing factors
  final_twrs.each_with_index do |final_cooling_tower, i|
    final_cooling_tower.setName("#{final_cooling_tower.name} #{i + 1} of #{final_twrs.size}")
    final_cooling_tower.setSizingFactor(clg_twr_sizing_factor)
  end
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, there are #{final_twrs.size} cooling towers, one for each chiller.")

  # Set the equipment to stage sequentially
  plant_loop.setLoadDistributionScheme('SequentialLoad')
  return true
end
plant_loop_apply_standard_controls(plant_loop, climate_zone) click to toggle source

Apply all standard required controls to the plant loop

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 9
def plant_loop_apply_standard_controls(plant_loop, climate_zone)
  # Supply water temperature reset
  # plant_loop_enable_supply_water_temperature_reset(plant_loop) if plant_loop_supply_water_temperature_reset_required?(plant_loop)
end
plant_loop_capacity_w_by_maxflow_and_delta_t_forwater(plant_loop) click to toggle source

This method calculates the capacity of a plant loop by multiplying the temp difference across the loop, the maximum flow rate, the fluid density, and the fluid heat capacity (currently only works with water). This may be a little more approximate than the heating and cooling capacity methods described above however is not limited to certain types of equipment and can be used for condensing plant loops too.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Double] capacity of plant loop in watts

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 1502
def plant_loop_capacity_w_by_maxflow_and_delta_t_forwater(plant_loop)
  plantloop_maxflowrate = nil
  if plant_loop.fluidType != 'Water'
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "The fluid used in the plant loop named #{plant_loop.name} is not water.  The current version of this method only calculates the capacity of plant loops that use water.")
  end
  plantloop_maxflowrate = plant_loop_find_maximum_loop_flow_rate(plant_loop)
  plantloop_dt = plant_loop.sizingPlant.loopDesignTemperatureDifference.to_f
  # Plant loop capacity = temperature difference across plant loop * maximum plant loop flow rate * density of water (1000 kg/m^3) * see next line
  # Heat capacity of water (4180 J/(kg*K))
  plantloop_capacity = plantloop_dt * plantloop_maxflowrate * 1000.0 * 4180.0
  return plantloop_capacity
end
plant_loop_enable_supply_water_temperature_reset(plant_loop) click to toggle source

Enable reset of hot or chilled water temperature based on outdoor air temperature.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 501
def plant_loop_enable_supply_water_temperature_reset(plant_loop)
  # Get the current setpoint manager on the outlet node
  # and determine if already has temperature reset
  spms = plant_loop.supplyOutletNode.setpointManagers
  spms.each do |spm|
    if spm.to_SetpointManagerOutdoorAirReset.is_initialized
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}: supply water temperature reset is already enabled.")
      return false
    end
  end

  # Get the design water temperature
  sizing_plant = plant_loop.sizingPlant
  design_temp_c = sizing_plant.designLoopExitTemperature
  design_temp_f = OpenStudio.convert(design_temp_c, 'C', 'F').get
  loop_type = sizing_plant.loopType

  # Apply the reset, depending on the type of loop.
  case loop_type
    when 'Heating'

      # Hot water as-designed when cold outside
      hwt_at_lo_oat_f = design_temp_f
      hwt_at_lo_oat_c = OpenStudio.convert(hwt_at_lo_oat_f, 'F', 'C').get
      # 30F decrease when it's hot outside,
      # and therefore less heating capacity is likely required.
      decrease_f = 30.0
      hwt_at_hi_oat_f = hwt_at_lo_oat_f - decrease_f
      hwt_at_hi_oat_c = OpenStudio.convert(hwt_at_hi_oat_f, 'F', 'C').get

      # Define the high and low outdoor air temperatures
      lo_oat_f = 20
      lo_oat_c = OpenStudio.convert(lo_oat_f, 'F', 'C').get
      hi_oat_f = 50
      hi_oat_c = OpenStudio.convert(hi_oat_f, 'F', 'C').get

      # Create a setpoint manager
      hwt_oa_reset = OpenStudio::Model::SetpointManagerOutdoorAirReset.new(plant_loop.model)
      hwt_oa_reset.setName("#{plant_loop.name} HW Temp Reset")
      hwt_oa_reset.setControlVariable('Temperature')
      hwt_oa_reset.setSetpointatOutdoorLowTemperature(hwt_at_lo_oat_c)
      hwt_oa_reset.setOutdoorLowTemperature(lo_oat_c)
      hwt_oa_reset.setSetpointatOutdoorHighTemperature(hwt_at_hi_oat_c)
      hwt_oa_reset.setOutdoorHighTemperature(hi_oat_c)
      hwt_oa_reset.addToNode(plant_loop.supplyOutletNode)

      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}: hot water temperature reset from #{hwt_at_lo_oat_f.round}F to #{hwt_at_hi_oat_f.round}F between outdoor air temps of #{lo_oat_f.round}F and #{hi_oat_f.round}F.")

    when 'Cooling'

      # Chilled water as-designed when hot outside
      chwt_at_hi_oat_f = design_temp_f
      chwt_at_hi_oat_c = OpenStudio.convert(chwt_at_hi_oat_f, 'F', 'C').get
      # 10F increase when it's cold outside,
      # and therefore less cooling capacity is likely required.
      increase_f = 10.0
      chwt_at_lo_oat_f = chwt_at_hi_oat_f + increase_f
      chwt_at_lo_oat_c = OpenStudio.convert(chwt_at_lo_oat_f, 'F', 'C').get

      # Define the high and low outdoor air temperatures
      lo_oat_f = 60
      lo_oat_c = OpenStudio.convert(lo_oat_f, 'F', 'C').get
      hi_oat_f = 80
      hi_oat_c = OpenStudio.convert(hi_oat_f, 'F', 'C').get

      # Create a setpoint manager
      chwt_oa_reset = OpenStudio::Model::SetpointManagerOutdoorAirReset.new(plant_loop.model)
      chwt_oa_reset.setName("#{plant_loop.name} CHW Temp Reset")
      chwt_oa_reset.setControlVariable('Temperature')
      chwt_oa_reset.setSetpointatOutdoorLowTemperature(chwt_at_lo_oat_c)
      chwt_oa_reset.setOutdoorLowTemperature(lo_oat_c)
      chwt_oa_reset.setSetpointatOutdoorHighTemperature(chwt_at_hi_oat_c)
      chwt_oa_reset.setOutdoorHighTemperature(hi_oat_c)
      chwt_oa_reset.addToNode(plant_loop.supplyOutletNode)

      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}: chilled water temperature reset from #{chwt_at_hi_oat_f.round}F to #{chwt_at_lo_oat_f.round}F between outdoor air temps of #{hi_oat_f.round}F and #{lo_oat_f.round}F.")

    else

      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}: cannot enable supply water temperature reset for a #{loop_type} loop.")
      return false
  end
  return true
end
plant_loop_find_maximum_loop_flow_rate(plant_loop) click to toggle source

find maximum_loop_flow_rate

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Double] maximum loop flow rate in m^3/s

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 1318
def plant_loop_find_maximum_loop_flow_rate(plant_loop)
  # Get the maximum_loop_flow_rate
  maximum_loop_flow_rate = nil
  if plant_loop.maximumLoopFlowRate.is_initialized
    maximum_loop_flow_rate = plant_loop.maximumLoopFlowRate.get
  elsif plant_loop.autosizedMaximumLoopFlowRate.is_initialized
    maximum_loop_flow_rate = plant_loop.autosizedMaximumLoopFlowRate.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{plant_loop.name} maximum loop flow rate is not available.")
  end

  return maximum_loop_flow_rate
end
plant_loop_prm_baseline_condenser_water_temperatures(plant_loop, design_oat_wb_c) click to toggle source

Determine the performance rating method specified design condenser water temperature, approach, and range

@param plant_loop [OpenStudio::Model::PlantLoop] the condenser water loop @param design_oat_wb_c [Double] the design OA wetbulb temperature © @return [Array<Double>] [leaving_cw_t_c, approach_k, range_k]

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 431
def plant_loop_prm_baseline_condenser_water_temperatures(plant_loop, design_oat_wb_c)
  design_oat_wb_f = OpenStudio.convert(design_oat_wb_c, 'C', 'F').get

  # G3.1.3.11 - CW supply temp = 85F or 10F approaching design wet bulb temperature,
  # whichever is lower.  Design range = 10F
  # Design Temperature rise of 10F => Range: 10F
  range_r = 10

  # Determine the leaving CW temp
  max_leaving_cw_t_f = 85
  leaving_cw_t_10f_approach_f = design_oat_wb_f + 10
  leaving_cw_t_f = [max_leaving_cw_t_f, leaving_cw_t_10f_approach_f].min

  # Calculate the approach
  approach_r = leaving_cw_t_f - design_oat_wb_f

  # Convert to SI units
  leaving_cw_t_c = OpenStudio.convert(leaving_cw_t_f, 'F', 'C').get
  approach_k = OpenStudio.convert(approach_r, 'R', 'K').get
  range_k = OpenStudio.convert(range_r, 'R', 'K').get

  return [leaving_cw_t_c, approach_k, range_k]
end
plant_loop_set_chw_pri_sec_configuration(model) click to toggle source

Set configuration in model for chilled water primary/secondary loop interface

@param model [OpenStudio::Model::Model] OpenStudio model object @return [String] common_pipe or heat_exchanger

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 57
def plant_loop_set_chw_pri_sec_configuration(model)
  pri_sec_config = 'common_pipe'
  return pri_sec_config
end
plant_loop_supply_water_temperature_reset_required?(plant_loop) click to toggle source

Determine if temperature reset is required. Required if heating or cooling capacity is greater than 300,000 Btu/hr.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if required, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 460
def plant_loop_supply_water_temperature_reset_required?(plant_loop)
  reset_required = false

  # Not required for service water heating systems
  if plant_loop_swh_loop?(plant_loop)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}: supply water temperature reset not required for service water heating systems.")
    return reset_required
  end

  # Not required for variable flow systems
  if plant_loop_variable_flow_system?(plant_loop)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}: supply water temperature reset not required for variable flow systems per 6.5.4.3 Exception b.")
    return reset_required
  end

  # Determine the capacity of the system
  heating_capacity_w = plant_loop_total_heating_capacity(plant_loop)
  cooling_capacity_w = plant_loop_total_cooling_capacity(plant_loop)

  heating_capacity_btu_per_hr = OpenStudio.convert(heating_capacity_w, 'W', 'Btu/hr').get
  cooling_capacity_btu_per_hr = OpenStudio.convert(cooling_capacity_w, 'W', 'Btu/hr').get

  # Compare against capacity minimum requirement
  min_cap_btu_per_hr = 300_000
  if heating_capacity_btu_per_hr > min_cap_btu_per_hr
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}: supply water temperature reset is required because heating capacity of #{heating_capacity_btu_per_hr.round} Btu/hr exceeds the minimum threshold of #{min_cap_btu_per_hr.round} Btu/hr.")
    reset_required = true
  elsif cooling_capacity_btu_per_hr > min_cap_btu_per_hr
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}: supply water temperature reset is required because cooling capacity of #{cooling_capacity_btu_per_hr.round} Btu/hr exceeds the minimum threshold of #{min_cap_btu_per_hr.round} Btu/hr.")
    reset_required = true
  else
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}: supply water temperature reset is not required because capacity is less than minimum of #{min_cap_btu_per_hr.round} Btu/hr.")
  end

  return reset_required
end
plant_loop_swh_loop?(plant_loop) click to toggle source

Determines if the loop is a Service Water Heating loop by checking if there is a WaterUseConnection on the demand side or a WaterHeaterMixed on the supply side

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if it is a service water heating loop, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 1337
def plant_loop_swh_loop?(plant_loop)
  serves_swh = false
  plant_loop.demandComponents.each do |comp|
    if comp.to_WaterUseConnections.is_initialized
      serves_swh = true
      break
    end
  end
  plant_loop.supplyComponents.each do |comp|
    if comp.to_WaterHeaterMixed.is_initialized
      serves_swh = true
      break
    end
  end

  # If there is a waterheater on the demand side,
  # check if the loop connected to that waterheater's
  # demand side is an swh loop itself
  plant_loop.demandComponents.each do |comp|
    if comp.to_WaterHeaterMixed.is_initialized
      comp = comp.to_WaterHeaterMixed.get
      if comp.plantLoop.is_initialized
        if plant_loop_swh_loop?(comp.plantLoop.get)
          serves_swh = true
          break
        end
      end
    end
  end

  return serves_swh
end
plant_loop_swh_system_type(plant_loop) click to toggle source

Classifies the service water system and returns information about fuel types, whether it serves both heating and service water heating, the water storage volume, and the total heating capacity.

@param plant_loop [OpenStudio::Model::PlantLoop] service water heating loop @return [Array<Array<String>, Bool, Double, Double>] An array of:

fuel types, combination_system (true/false), storage_capacity (m^3), plant_loop_total_heating_capacity(plant_loop)  (W)
# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 1377
def plant_loop_swh_system_type(plant_loop)
  combination_system = true
  storage_capacity = 0
  primary_fuels = []
  secondary_fuels = []

  # @todo to work correctly, plant_loop_total_heating_capacity(plantloop)  requires to have either hardsized capacities or a sizing run.
  primary_heating_capacity = plant_loop_total_heating_capacity(plant_loop)
  secondary_heating_capacity = 0

  plant_loop.supplyComponents.each do |component|
    # Get the object type
    obj_type = component.iddObjectType.valueName.to_s

    case obj_type
      when 'OS_DistrictHeating', 'OS_DistrictHeating_Water', 'OS_DistrictHeating_Steam'
        primary_fuels << 'DistrictHeating'
        combination_system = false
      when 'OS_HeatPump_WaterToWater_EquationFit_Heating'
        primary_fuels << 'Electricity'
      when 'OS_SolarCollector_FlatPlate_PhotovoltaicThermal'
        primary_fuels << 'SolarEnergy'
      when 'OS_SolarCollector_FlatPlate_Water'
        primary_fuels << 'SolarEnergy'
      when 'OS_SolarCollector_IntegralCollectorStorage'
        primary_fuels << 'SolarEnergy'
      when 'OS_WaterHeater_HeatPump'
        primary_fuels << 'Electricity'
      when 'OS_WaterHeater_Mixed'
        component = component.to_WaterHeaterMixed.get
        # Check it it's actually a heater, not just a storage tank
        if component.heaterMaximumCapacity.empty? || component.heaterMaximumCapacity.get != 0
          # If it does, we add the heater Fuel Type
          primary_fuels << component.heaterFuelType
          # And in this case we'll reuse this object
          combination_system = false
        end
        # @todo not sure about whether it should be an elsif or not
        # Check the plant loop connection on the source side
        if component.secondaryPlantLoop.is_initialized
          source_plant_loop = component.secondaryPlantLoop.get

          # error if Loop heating fuels method is not available
          if component.model.version < OpenStudio::VersionString.new('3.6.0')
            OpenStudio.logFree(OpenStudio::Error, 'openstudio.Standards.PlantLoop', 'Required Loop method .heatingFuelTypes is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
          end

          secondary_fuels += source_plant_loop.heatingFuelTypes.map(&:valueName)
          secondary_heating_capacity += plant_loop_total_heating_capacity(source_plant_loop)
        end

        # Storage capacity
        if component.tankVolume.is_initialized
          storage_capacity = component.tankVolume.get
        end

      when 'OS_WaterHeater_Stratified'
        component = component.to_WaterHeaterStratified.get

        # Check if the heater actually has a capacity (otherwise it's simply a Storage Tank)
        if component.heaterMaximumCapacity.empty? || component.heaterMaximumCapacity.get != 0
          # If it does, we add the heater Fuel Type
          primary_fuels << component.heaterFuelType
          # And in this case we'll reuse this object
          combination_system = false
        end
        # @todo not sure about whether it should be an elsif or not
        # Check the plant loop connection on the source side
        if component.secondaryPlantLoop.is_initialized
          source_plant_loop = component.secondaryPlantLoop.get

          # error if Loop heating fuels method is not available
          if component.model.version < OpenStudio::VersionString.new('3.6.0')
            OpenStudio.logFree(OpenStudio::Error, 'openstudio.Standards.PlantLoop', 'Required Loop method .heatingFuelTypes is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
          end

          secondary_fuels += source_plant_loop.heatingFuelTypes.map(&:valueName)
          secondary_heating_capacity += plant_loop_total_heating_capacity(source_plant_loop)
        end

        # Storage capacity
        if component.tankVolume.is_initialized
          storage_capacity = component.tankVolume.get
        end

      when 'OS_HeatExchanger_FluidToFluid'
        hx = component.to_HeatExchangerFluidToFluid.get
        cooling_hx_control_types = ['CoolingSetpointModulated', 'CoolingSetpointOnOff', 'CoolingDifferentialOnOff', 'CoolingSetpointOnOffWithComponentOverride']
        cooling_hx_control_types.each(&:downcase!)
        if !cooling_hx_control_types.include?(hx.controlType.downcase) && hx.secondaryPlantLoop.is_initialized
          source_plant_loop = hx.secondaryPlantLoop.get

          # error if Loop heating fuels method is not available
          if component.model.version < OpenStudio::VersionString.new('3.6.0')
            OpenStudio.logFree(OpenStudio::Error, 'openstudio.Standards.PlantLoop', 'Required Loop method .heatingFuelTypes is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
          end

          secondary_fuels += source_plant_loop.heatingFuelTypes.map(&:valueName)
          secondary_heating_capacity += plant_loop_total_heating_capacity(source_plant_loop)
        end

      when 'OS_Node', 'OS_Pump_ConstantSpeed', 'OS_Pump_VariableSpeed', 'OS_Connector_Splitter', 'OS_Connector_Mixer', 'OS_Pipe_Adiabatic'
      # To avoid extraneous debug messages
    end
  end

  # @todo decide how to handle primary and secondary stuff
  fuels = primary_fuels + secondary_fuels
  total_heating_capacity = primary_heating_capacity + secondary_heating_capacity
  # If the primary heating capacity is bigger than secondary, assume the secondary is just a backup and disregard it?
  # if primary_heating_capacity > secondary_heating_capacity
  #   plant_loop_total_heating_capacity(plant_loop)  = primary_heating_capacity
  #   fuels = primary_fuels
  # end

  return fuels.uniq.sort, combination_system, storage_capacity, total_heating_capacity
end
plant_loop_total_cooling_capacity(plant_loop) click to toggle source

Get the total cooling capacity for the plant loop

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Double] total cooling capacity in watts

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 590
def plant_loop_total_cooling_capacity(plant_loop)
  # Sum the cooling capacity for all cooling components
  # on the plant loop.
  total_cooling_capacity_w = 0
  plant_loop.supplyComponents.each do |sc|
    # ChillerElectricEIR
    if sc.to_ChillerElectricEIR.is_initialized
      chiller = sc.to_ChillerElectricEIR.get
      if chiller.referenceCapacity.is_initialized
        total_cooling_capacity_w += chiller.referenceCapacity.get
      elsif chiller.autosizedReferenceCapacity.is_initialized
        total_cooling_capacity_w += chiller.autosizedReferenceCapacity.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{plant_loop.name} capacity of #{chiller.name} is not available, total cooling capacity of plant loop will be incorrect when applying standard.")
      end
    # DistrictCooling
    elsif sc.to_DistrictCooling.is_initialized
      dist_clg = sc.to_DistrictCooling.get
      if dist_clg.nominalCapacity.is_initialized
        total_cooling_capacity_w += dist_clg.nominalCapacity.get
      elsif dist_clg.autosizedNominalCapacity.is_initialized
        total_cooling_capacity_w += dist_clg.autosizedNominalCapacity.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{plant_loop.name} capacity of DistrictCooling #{dist_clg.name} is not available, total heating capacity of plant loop will be incorrect when applying standard.")
      end
    end
  end

  total_cooling_capacity_tons = OpenStudio.convert(total_cooling_capacity_w, 'W', 'ton').get
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, cooling capacity is #{total_cooling_capacity_tons.round} tons of refrigeration.")

  return total_cooling_capacity_w
end
plant_loop_total_floor_area_served(plant_loop) click to toggle source

Determine the total floor area served by this loop. If the loop serves a coil attached to an AirLoopHVAC, count the area of all zones served by that loop. If the loop serves coils inside of zone equipment, count the area of the zones containing the zone equipment.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Double] floor area served in m^2

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 698
def plant_loop_total_floor_area_served(plant_loop)
  sizing_plant = plant_loop.sizingPlant
  loop_type = sizing_plant.loopType

  # Get all the coils served by this loop
  coils = []
  case loop_type
    when 'Heating'
      plant_loop.demandComponents.each do |dc|
        if dc.to_CoilHeatingWater.is_initialized
          coils << dc.to_CoilHeatingWater.get
        end
      end
    when 'Cooling'
      plant_loop.demandComponents.each do |dc|
        if dc.to_CoilCoolingWater.is_initialized
          coils << dc.to_CoilCoolingWater.get
        end
      end
    else
      return 0.0
  end

  # The coil can either be on an airloop (as a main heating coil)
  # in an HVAC Component (like a unitary system on an airloop),
  # or in a Zone HVAC Component (like a fan coil).
  zones_served = []
  coils.each do |coil|
    if coil.airLoopHVAC.is_initialized
      air_loop = coil.airLoopHVAC.get
      zones_served += air_loop.thermalZones
    elsif coil.containingHVACComponent.is_initialized
      containing_comp = coil.containingHVACComponent.get
      if containing_comp.airLoopHVAC.is_initialized
        air_loop = containing_comp.airLoopHVAC.get
        zones_served += air_loop.thermalZones
      end
    elsif coil.containingZoneHVACComponent.is_initialized
      zone_hvac = coil.containingZoneHVACComponent.get
      if zone_hvac.thermalZone.is_initialized
        zones_served << zone_hvac.thermalZone.get
      end
    end
  end

  # Add up the area of all zones served.
  # Make sure to only add unique zones in
  # case the same zone is served by multiple
  # coils served by the same loop.  For example,
  # a HW and Reheat
  area_served_m2 = 0.0
  zones_served.uniq.each do |zone|
    area_served_m2 += zone.floorArea
  end
  area_served_ft2 = OpenStudio.convert(area_served_m2, 'm^2', 'ft^2').get

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, serves #{area_served_ft2.round} ft^2.")

  return area_served_m2
end
plant_loop_total_heating_capacity(plant_loop) click to toggle source

Get the total heating capacity for the plant loop

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Double] total heating capacity in watts @todo Add district heating to plant loop heating capacity

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 630
def plant_loop_total_heating_capacity(plant_loop)
  # Sum the heating capacity for all heating components
  # on the plant loop.
  total_heating_capacity_w = 0
  plant_loop.supplyComponents.each do |sc|
    if sc.to_BoilerHotWater.is_initialized
      # BoilerHotWater
      boiler = sc.to_BoilerHotWater.get
      if boiler.nominalCapacity.is_initialized
        total_heating_capacity_w += boiler.nominalCapacity.get
      elsif boiler.autosizedNominalCapacity.is_initialized
        total_heating_capacity_w += boiler.autosizedNominalCapacity.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{plant_loop.name} capacity of Boiler:HotWater ' #{boiler.name} is not available, total heating capacity of plant loop will be incorrect when applying standard.")
      end
    elsif sc.to_WaterHeaterMixed.is_initialized
      # WaterHeater:Mixed
      water_heater = sc.to_WaterHeaterMixed.get
      if water_heater.heaterMaximumCapacity.is_initialized
        total_heating_capacity_w += water_heater.heaterMaximumCapacity.get
      elsif water_heater.autosizedHeaterMaximumCapacity.is_initialized
        total_heating_capacity_w += water_heater.autosizedHeaterMaximumCapacity.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{plant_loop.name} capacity of WaterHeater:Mixed #{water_heater.name} is not available, total heating capacity of plant loop will be incorrect when applying standard.")
      end
    elsif sc.to_WaterHeaterStratified.is_initialized
      # WaterHeater:Stratified
      water_heater = sc.to_WaterHeaterStratified.get
      if water_heater.heater1Capacity.is_initialized
        total_heating_capacity_w += water_heater.heater1Capacity.get
      end
      if water_heater.heater2Capacity.is_initialized
        total_heating_capacity_w += water_heater.heater2Capacity.get
      end
    elsif sc.iddObjectType.valueName.to_s.include?('DistrictHeating')
      # DistrictHeating
      case sc.iddObjectType.valueName.to_s
      when 'OS_DistrictHeating'
        dist_htg = sc.to_DistrictHeating.get
      when 'OS_DistrictHeating_Water'
        dist_htg = sc.to_DistrictHeatingWater.get
      when 'OS_DistrictHeating_Steam'
        dist_htg = sc.to_DistrictHeatingSteam.get
      end
      if dist_htg.nominalCapacity.is_initialized
        total_heating_capacity_w += dist_htg.nominalCapacity.get
      elsif dist_htg.autosizedNominalCapacity.is_initialized
        total_heating_capacity_w += dist_htg.autosizedNominalCapacity.get
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{plant_loop.name} capacity of DistrictHeating #{dist_htg.name} is not available, total heating capacity of plant loop will be incorrect when applying standard.")
      end
    end
  end

  total_heating_capacity_kbtu_per_hr = OpenStudio.convert(total_heating_capacity_w, 'W', 'kBtu/hr').get
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "For #{plant_loop.name}, heating capacity is #{total_heating_capacity_kbtu_per_hr.round} kBtu/hr.")

  return total_heating_capacity_w
end
plant_loop_total_rated_w_per_gpm(plant_loop) click to toggle source

Determines the total rated watts per GPM of the loop

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Double] rated power consumption per flow in watts per gpm, W*s/m^3

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 1268
def plant_loop_total_rated_w_per_gpm(plant_loop)
  sizing_plant = plant_loop.sizingPlant
  loop_type = sizing_plant.loopType

  # Supply W/GPM
  supply_w_per_gpm = 0
  demand_w_per_gpm = 0

  plant_loop.supplyComponents.each do |component|
    if component.to_PumpConstantSpeed.is_initialized
      pump = component.to_PumpConstantSpeed.get
      pump_rated_w_per_gpm = pump_rated_w_per_gpm(pump)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "'#{loop_type}' Loop #{plant_loop.name} - Primary (Supply) Constant Speed Pump '#{pump.name}' - pump_rated_w_per_gpm #{pump_rated_w_per_gpm} W/GPM")
      supply_w_per_gpm += pump_rated_w_per_gpm
    elsif component.to_PumpVariableSpeed.is_initialized
      pump = component.to_PumpVariableSpeed.get
      pump_rated_w_per_gpm = pump_rated_w_per_gpm(pump)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "'#{loop_type}' Loop #{plant_loop.name} - Primary (Supply) VSD Pump '#{pump.name}' - pump_rated_w_per_gpm #{pump_rated_w_per_gpm} W/GPM")
      supply_w_per_gpm += pump_rated_w_per_gpm
    end
  end

  # Determine if primary only or primary-secondary
  # IF there's a pump on the demand side it's primary-secondary
  demand_pumps = plant_loop.demandComponents('OS:Pump:VariableSpeed'.to_IddObjectType) + plant_loop.demandComponents('OS:Pump:ConstantSpeed'.to_IddObjectType)
  demand_pumps.each do |component|
    if component.to_PumpConstantSpeed.is_initialized
      pump = component.to_PumpConstantSpeed.get
      pump_rated_w_per_gpm = pump_rated_w_per_gpm(pump)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "'#{loop_type}' Loop #{plant_loop.name} - Secondary (Demand) Constant Speed Pump '#{pump.name}' - pump_rated_w_per_gpm #{pump_rated_w_per_gpm} W/GPM")
      demand_w_per_gpm += pump_rated_w_per_gpm
    elsif component.to_PumpVariableSpeed.is_initialized
      pump = component.to_PumpVariableSpeed.get
      pump_rated_w_per_gpm = pump_rated_w_per_gpm(pump)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "'#{loop_type}' Loop #{plant_loop.name} - Secondary (Demand) VSD Pump '#{pump.name}' - pump_rated_w_per_gpm #{pump_rated_w_per_gpm} W/GPM")
      demand_w_per_gpm += pump_rated_w_per_gpm
    end
  end

  total_rated_w_per_gpm = supply_w_per_gpm + demand_w_per_gpm

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.PlantLoop', "'#{loop_type}' Loop #{plant_loop.name} - Total #{total_rated_w_per_gpm} W/GPM - Supply #{supply_w_per_gpm} W/GPM - Demand #{demand_w_per_gpm} W/GPM")

  return total_rated_w_per_gpm
end
plant_loop_variable_flow_system?(plant_loop) click to toggle source

Determine if the plant loop is variable flow. Returns true if primary and/or secondary pumps are variable speed.

@param plant_loop [OpenStudio::Model::PlantLoop] plant loop @return [Boolean] returns true if variable flow, false if not

# File lib/openstudio-standards/standards/Standards.PlantLoop.rb, line 67
def plant_loop_variable_flow_system?(plant_loop)
  variable_flow = false

  # Check all the primary pumps
  plant_loop.supplyComponents.each do |sc|
    if sc.to_PumpVariableSpeed.is_initialized
      variable_flow = true
    end
  end

  # Check all the secondary pumps
  plant_loop.demandComponents.each do |sc|
    if sc.to_PumpVariableSpeed.is_initialized
      variable_flow = true
    end
  end

  return variable_flow
end
prototype_apply_condenser_water_temperatures(condenser_loop, design_wet_bulb_c: nil) click to toggle source

Apply approach temperature sizing criteria to a condenser water loop

@param condenser_loop [<OpenStudio::Model::PlantLoop>] a condenser loop served by a cooling tower @param design_wet_bulb_c [Double] the outdoor design wetbulb conditions in degrees Celsius @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoolingTower.rb, line 9
def prototype_apply_condenser_water_temperatures(condenser_loop,
                                                 design_wet_bulb_c: nil)
  sizing_plant = condenser_loop.sizingPlant
  loop_type = sizing_plant.loopType
  return false unless loop_type == 'Condenser'

  # if values are absent, use the CTI rating condition 78F
  if design_wet_bulb_c.nil?
    design_wet_bulb_c = OpenStudio.convert(78.0, 'F', 'C').get
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.hvac_systems', "For condenser loop #{condenser_loop.name}, no design day OATwb conditions given.  CTI rating condition of 78F OATwb will be used for sizing cooling towers.")
  end

  # EnergyPlus has a minimum limit of 68F and maximum limit of 80F for cooling towers
  design_wet_bulb_f = OpenStudio.convert(design_wet_bulb_c, 'C', 'F').get
  eplus_min_design_wet_bulb_f = 68.0
  eplus_max_design_wet_bulb_f = 80.0
  if design_wet_bulb_f < eplus_min_design_wet_bulb_f
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.CoolingTower', "For condenser loop #{condenser_loop.name}, increased design OATwb from #{design_wet_bulb_f.round(1)} F to EneryPlus model minimum limit of #{eplus_min_design_wet_bulb_f} F.")
    design_wet_bulb_f = eplus_min_design_wet_bulb_f
  elsif design_wet_bulb_f > eplus_max_design_wet_bulb_f
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Prototype.CoolingTower', "For condenser loop #{condenser_loop.name}, reduced design OATwb from #{design_wet_bulb_f.round(1)} F to EneryPlus model maximum limit of #{eplus_max_design_wet_bulb_f} F.")
    design_wet_bulb_f = eplus_max_design_wet_bulb_f
  end
  design_wet_bulb_c = OpenStudio.convert(design_wet_bulb_f, 'F', 'C').get

  # Determine the design CW temperature, approach, and range
  leaving_cw_t_c, approach_k, range_k = prototype_condenser_water_temperatures(design_wet_bulb_c)

  # Convert to IP units
  leaving_cw_t_f = OpenStudio.convert(leaving_cw_t_c, 'C', 'F').get
  approach_r = OpenStudio.convert(approach_k, 'K', 'R').get
  range_r = OpenStudio.convert(range_k, 'K', 'R').get

  # Report out design conditions
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Prototype.CoolingTower', "For condenser loop #{condenser_loop.name}, design OATwb = #{design_wet_bulb_f.round(1)} F, approach = #{approach_r.round(1)} deltaF, range = #{range_r.round(1)} deltaF, leaving condenser water temperature = #{leaving_cw_t_f.round(1)} F.")

  # Set Cooling Tower sizing parameters.
  # Only the variable speed cooling tower in E+ allows you to set the design temperatures.
  #
  # Per the documentation
  # http://bigladdersoftware.com/epx/docs/8-4/input-output-reference/group-condenser-equipment.html#field-design-u-factor-times-area-value
  # for CoolingTowerSingleSpeed and CoolingTowerTwoSpeed
  # E+ uses the following values during sizing:
  # 95F entering water temp
  # 95F OATdb
  # 78F OATwb
  # range = loop design delta-T aka range (specified above)
  condenser_loop.supplyComponents.each do |sc|
    if sc.to_CoolingTowerVariableSpeed.is_initialized
      ct = sc.to_CoolingTowerVariableSpeed.get
      ct.setDesignInletAirWetBulbTemperature(design_wet_bulb_c)
      ct.setDesignApproachTemperature(approach_k)
      ct.setDesignRangeTemperature(range_k)
    end
  end

  # Set the CW sizing parameters
  # EnergyPlus autosizing routine assumes 85F and 10F temperature difference
  energyplus_design_loop_exit_temperature_c = OpenStudio.convert(85.0, 'F', 'C').get
  sizing_plant.setDesignLoopExitTemperature(energyplus_design_loop_exit_temperature_c)
  sizing_plant.setLoopDesignTemperatureDifference(OpenStudio.convert(10.0, 'R', 'K').get)

  # Cooling Tower operational controls
  # G3.1.3.11 - Tower shall be controlled to maintain a 70F LCnWT where weather permits,
  # floating up to leaving water at design conditions.
  float_down_to_f = 70.0
  float_down_to_c = OpenStudio.convert(float_down_to_f, 'F', 'C').get

  # get or create a setpoint manager
  cw_t_stpt_manager = nil
  condenser_loop.supplyOutletNode.setpointManagers.each do |spm|
    if spm.to_SetpointManagerFollowOutdoorAirTemperature.is_initialized
      if spm.name.get.include? 'Setpoint Manager Follow OATwb'
        cw_t_stpt_manager = spm.to_SetpointManagerFollowOutdoorAirTemperature.get
      end
    end
  end
  if cw_t_stpt_manager.nil?
    cw_t_stpt_manager = OpenStudio::Model::SetpointManagerFollowOutdoorAirTemperature.new(condenser_loop.model)
    cw_t_stpt_manager.addToNode(condenser_loop.supplyOutletNode)
  end

  cw_t_stpt_manager.setName("#{condenser_loop.name} Setpoint Manager Follow OATwb with #{approach_r.round(1)}F Approach")
  cw_t_stpt_manager.setReferenceTemperatureType('OutdoorAirWetBulb')
  # At low design OATwb, it is possible to calculate
  # a maximum temperature below the minimum.  In this case,
  # make the maximum and minimum the same.
  if leaving_cw_t_c < float_down_to_c
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PlantLoop', "For #{condenser_loop.name}, the maximum leaving temperature of #{leaving_cw_t_f.round(1)} F is below the minimum of #{float_down_to_f.round(1)} F.  The maximum will be set to the same value as the minimum.")
    leaving_cw_t_c = float_down_to_c
  end
  cw_t_stpt_manager.setMaximumSetpointTemperature(leaving_cw_t_c)
  cw_t_stpt_manager.setMinimumSetpointTemperature(float_down_to_c)
  cw_t_stpt_manager.setOffsetTemperatureDifference(approach_k)

  return true
end
prototype_condenser_water_temperatures(design_oat_wb_c) click to toggle source

Determine the performance rating method specified design condenser water temperature, approach, and range

@param design_oat_wb_c [Double] the design OA wetbulb temperature © @return [Array<Double>] [leaving_cw_t_c, approach_k, range_k]

# File lib/openstudio-standards/prototypes/common/objects/Prototype.CoolingTower.rb, line 111
def prototype_condenser_water_temperatures(design_oat_wb_c)
  design_oat_wb_f = OpenStudio.convert(design_oat_wb_c, 'C', 'F').get

  # 90.1-2010 G3.1.3.11 - CW supply temp = 85F or 10F approaching design wet bulb temperature, whichever is lower.
  # Design range = 10F
  # Design Temperature rise of 10F => Range: 10F
  range_r = 10.0

  # Determine the leaving CW temp
  max_leaving_cw_t_f = 85.0
  leaving_cw_t_10f_approach_f = design_oat_wb_f + 10.0
  leaving_cw_t_f = [max_leaving_cw_t_f, leaving_cw_t_10f_approach_f].min

  # Calculate the approach
  approach_r = leaving_cw_t_f - design_oat_wb_f

  # Convert to SI units
  leaving_cw_t_c = OpenStudio.convert(leaving_cw_t_f, 'F', 'C').get
  approach_k = OpenStudio.convert(approach_r, 'R', 'K').get
  range_k = OpenStudio.convert(range_r, 'R', 'K').get

  return [leaving_cw_t_c, approach_k, range_k]
end
pump_variable_speed_control_type(pump) click to toggle source

Determine and set type of part load control type for heating and chilled water variable speed pumps

@param pump [OpenStudio::Model::PumpVariableSpeed] OpenStudio pump object @return [Boolean] Returns true if applicable, false otherwise

# File lib/openstudio-standards/prototypes/common/objects/Prototype.PumpVariableSpeed.rb, line 9
def pump_variable_speed_control_type(pump)
  # Get plant loop
  plant_loop = pump.plantLoop.get

  # Get plant loop type
  plant_loop_type = plant_loop.sizingPlant.loopType
  return false unless plant_loop_type == 'Heating' || plant_loop_type == 'Cooling'

  # Get rated pump power
  if pump.ratedPowerConsumption.is_initialized
    pump_rated_power_w = pump.ratedPowerConsumption.get
  elsif pump.autosizedRatedPowerConsumption.is_initialized
    pump_rated_power_w = pump.autosizedRatedPowerConsumption.get
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Pump', "For #{pump.name}, could not find rated pump power consumption, cannot determine w per gpm correctly.")
    return false
  end

  # Get nominal nameplate HP
  pump_nominal_hp = pump_rated_power_w * pump.motorEfficiency / 745.7

  # Assign peformance curves
  control_type = pump_variable_speed_get_control_type(pump, plant_loop_type, pump_nominal_hp)

  # Set pump part load performance curve coefficients
  pump_variable_speed_set_control_type(pump, control_type) unless !control_type

  return true
end
pump_variable_speed_get_control_type(pump, plant_loop_type, pump_nominal_hp) click to toggle source

Determine type of pump part load control type

@param pump [OpenStudio::Model::PumpVariableSpeed] OpenStudio pump object @param plant_loop_type [String] Type of plant loop @param pump_nominal_hp [Float] Pump nominal horsepower @return [String] Pump part load control type

# File lib/openstudio-standards/prototypes/common/objects/Prototype.PumpVariableSpeed.rb, line 45
def pump_variable_speed_get_control_type(pump, plant_loop_type, pump_nominal_hp)
  # Get plant loop
  plant_loop = pump.plantLoop.get

  # Default assumptions are based on ASHRAE 90.1-2010 Appendix G (G3.1.3.5 and G3.1.3.10)
  case plant_loop_type
    when 'Heating'
      # Determine the area served by the plant loop
      area_served_m2 = plant_loop_total_floor_area_served(plant_loop)
      area_served_ft2 = OpenStudio.convert(area_served_m2, 'm^2', 'ft^2').get

      return 'VSD No Reset' if area_served_ft2 > 120_000

      # else
      return 'Riding Curve'
    when 'Cooling'
      # Get plant loop capacity capacity
      cooling_capacity_w = plant_loop_total_cooling_capacity(plant_loop)

      return 'VSD No Reset' if cooling_capacity_w >= 300

      # else
      return 'Riding Curve'
  end
end
pump_variable_speed_set_control_type(pump_variable_speed, control_type) click to toggle source

Set the pump curve coefficients based on the specified control type.

@param pump_variable_speed [OpenStudio::Model::PumpVariableSpeed] variable speed pump @param control_type [String] valid choices are Riding Curve, VSD No Reset, VSD DP Reset

# File lib/openstudio-standards/standards/Standards.PumpVariableSpeed.rb, line 10
def pump_variable_speed_set_control_type(pump_variable_speed, control_type)
  # Determine the coefficients
  coeff_a = nil
  coeff_b = nil
  coeff_c = nil
  coeff_d = nil
  case control_type
  when 'Constant Flow'
    coeff_a = 0.0
    coeff_b = 1.0
    coeff_c = 0.0
    coeff_d = 0.0
  when 'Riding Curve'
    coeff_a = 0.0
    coeff_b = 3.2485
    coeff_c = -4.7443
    coeff_d = 2.5294
  when 'VSD No Reset'
    coeff_a = 0.0
    coeff_b = 0.5726
    coeff_c = -0.301
    coeff_d = 0.7347
  when 'VSD DP Reset'
    coeff_a = 0.0
    coeff_b = 0.0205
    coeff_c = 0.4101
    coeff_d = 0.5753
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.PumpVariableSpeed', "Pump control type '#{control_type}' not recognized, pump coefficients will not be changed.")
    return false
  end

  # Set the coefficients
  pump_variable_speed.setCoefficient1ofthePartLoadPerformanceCurve(coeff_a)
  pump_variable_speed.setCoefficient2ofthePartLoadPerformanceCurve(coeff_b)
  pump_variable_speed.setCoefficient3ofthePartLoadPerformanceCurve(coeff_c)
  pump_variable_speed.setCoefficient4ofthePartLoadPerformanceCurve(coeff_d)
  pump_variable_speed.setPumpControlType('Intermittent')

  # Append the control type to the pump name
  # self.setName("#{self.name} #{control_type}")

  return true
end
remove_air_loops(model) click to toggle source

Remove all air loops in model

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 106
def remove_air_loops(model)
  model.getAirLoopHVACs.each(&:remove)
  return model
end
remove_all_hvac(model) click to toggle source

Remove all HVAC equipment including service hot water loops and zone exhaust fans

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 208
def remove_all_hvac(model)
  remove_air_loops(model)
  remove_all_plant_loops(model)
  remove_vrf(model)
  remove_all_zone_equipment(model)
  remove_unused_curves(model)
  return model
end
remove_all_plant_loops(model) click to toggle source

Remove all plant loops in model including those used for service hot water

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 135
def remove_all_plant_loops(model)
  model.getPlantLoops.each(&:remove)
  return model
end
remove_all_zone_equipment(model) click to toggle source

Remove all zone equipment including exhaust fans

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 171
def remove_all_zone_equipment(model)
  model.getThermalZones.each do |zone|
    zone.equipment.each(&:remove)
  end
  return model
end
remove_hvac(model) click to toggle source

Remove HVAC equipment except for service hot water loops and zone exhaust fans

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 195
def remove_hvac(model)
  remove_air_loops(model)
  remove_plant_loops(model)
  remove_vrf(model)
  remove_zone_equipment(model)
  remove_unused_curves(model)
  return model
end
remove_plant_loops(model) click to toggle source

Remove plant loops in model except those used for service hot water

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 115
def remove_plant_loops(model)
  plant_loops = model.getPlantLoops
  plant_loops.each do |plant_loop|
    shw_use = false
    plant_loop.demandComponents.each do |component|
      if component.to_WaterUseConnections.is_initialized || component.to_CoilWaterHeatingDesuperheater.is_initialized
        shw_use = true
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "#{plant_loop.name} is used for SHW or refrigeration heat reclaim and will not be removed.")
        break
      end
    end
    plant_loop.remove unless shw_use
  end
  return model
end
remove_unused_curves(model) click to toggle source

Remove unused performance curves

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 182
def remove_unused_curves(model)
  model.getCurves.each do |curve|
    if curve.directUseCount == 0
      model.removeObject(curve.handle)
    end
  end
  return model
end
remove_vrf(model) click to toggle source

Remove VRF units

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 144
def remove_vrf(model)
  model.getAirConditionerVariableRefrigerantFlows.each(&:remove)
  model.getZoneHVACTerminalUnitVariableRefrigerantFlows.each(&:remove)
  return model
end
remove_zone_equipment(model) click to toggle source

Remove zone equipment except for exhaust fans

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 154
def remove_zone_equipment(model)
  model.getThermalZones.each do |zone|
    zone.equipment.each do |equipment|
      if equipment.to_FanZoneExhaust.is_initialized
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "#{equipment.name} is a zone exhaust fan and will not be removed.")
      else
        equipment.remove
      end
    end
  end
  return model
end
rename_air_loop_nodes(model) click to toggle source

renames air loop nodes to readable values

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 659
def rename_air_loop_nodes(model)
  # rename all hvac components on air loops
  model.getHVACComponents.sort.each do |component|
    next if component.to_Node.is_initialized # skip nodes

    unless component.airLoopHVAC.empty?
      # rename water to air component outlet nodes
      if component.to_WaterToAirComponent.is_initialized
        component = component.to_WaterToAirComponent.get
        unless component.airOutletModelObject.empty?
          component_outlet_object = component.airOutletModelObject.get
          next unless component_outlet_object.to_Node.is_initialized

          component_outlet_object.setName("#{component.name} Outlet Air Node")
        end
      end

      # rename air to air component nodes
      if component.to_AirToAirComponent.is_initialized
        component = component.to_AirToAirComponent.get
        unless component.primaryAirOutletModelObject.empty?
          component_outlet_object = component.primaryAirOutletModelObject.get
          next unless component_outlet_object.to_Node.is_initialized

          component_outlet_object.setName("#{component.name} Primary Outlet Air Node")
        end
        unless component.secondaryAirInletModelObject.empty?
          component_inlet_object = component.secondaryAirInletModelObject.get
          next unless component_inlet_object.to_Node.is_initialized

          component_inlet_object.setName("#{component.name} Secondary Inlet Air Node")
        end
      end

      # rename straight component outlet nodes
      if component.to_StraightComponent.is_initialized
        unless component.to_StraightComponent.get.outletModelObject.empty?
          component_outlet_object = component.to_StraightComponent.get.outletModelObject.get
          next unless component_outlet_object.to_Node.is_initialized

          component_outlet_object.setName("#{component.name} Outlet Air Node")
        end
      end
    end

    # rename zone hvac component nodes
    if component.to_ZoneHVACComponent.is_initialized
      component = component.to_ZoneHVACComponent.get
      unless component.airInletModelObject.empty?
        component_inlet_object = component.airInletModelObject.get
        next unless component_inlet_object.to_Node.is_initialized

        component_inlet_object.setName("#{component.name} Inlet Air Node")
      end
      unless component.airOutletModelObject.empty?
        component_outlet_object = component.airOutletModelObject.get
        next unless component_outlet_object.to_Node.is_initialized

        component_outlet_object.setName("#{component.name} Outlet Air Node")
      end
    end
  end

  # rename supply side nodes
  model.getAirLoopHVACs.sort.each do |air_loop|
    air_loop_name = air_loop.name.to_s
    air_loop.demandInletNode.setName("#{air_loop_name} Demand Inlet Node")
    air_loop.demandOutletNode.setName("#{air_loop_name} Demand Outlet Node")
    air_loop.supplyInletNode.setName("#{air_loop_name} Supply Inlet Node")
    air_loop.supplyOutletNode.setName("#{air_loop_name} Supply Outlet Node")

    unless air_loop.reliefAirNode.empty?
      relief_node = air_loop.reliefAirNode.get
      relief_node.setName("#{air_loop_name} Relief Air Node")
    end

    unless air_loop.mixedAirNode.empty?
      mixed_node = air_loop.mixedAirNode.get
      mixed_node.setName("#{air_loop_name} Mixed Air Node")
    end

    # rename outdoor air system and nodes
    unless air_loop.airLoopHVACOutdoorAirSystem.empty?
      oa_system = air_loop.airLoopHVACOutdoorAirSystem.get
      unless oa_system.outboardOANode.empty?
        oa_node = oa_system.outboardOANode.get
        oa_node.setName("#{air_loop_name} Outdoor Air Node")
      end
    end
  end

  # rename zone air and terminal nodes
  model.getThermalZones.sort.each do |zone|
    zone.zoneAirNode.setName("#{zone.name} Zone Air Node")

    unless zone.returnAirModelObject.empty?
      zone.returnAirModelObject.get.setName("#{zone.name} Return Air Node")
    end

    unless zone.airLoopHVACTerminal.empty?
      terminal_unit = zone.airLoopHVACTerminal.get
      if terminal_unit.to_StraightComponent.is_initialized
        component = terminal_unit.to_StraightComponent.get
        component.inletModelObject.get.setName("#{terminal_unit.name} Inlet Air Node")
      end
    end
  end

  # rename zone equipment list objects
  model.getZoneHVACEquipmentLists.sort.each do |obj|
    begin
      zone = obj.thermalZone
      obj.setName("#{zone.name} Zone HVAC Equipment List")
    rescue StandardError => e
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "Removing ZoneHVACEquipmentList #{obj.name}; missing thermal zone.")
      obj.remove
    end
  end

  return model
end
rename_plant_loop_nodes(model) click to toggle source

renames plant loop nodes to readable values

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 785
def rename_plant_loop_nodes(model)
  # rename all hvac components on plant loops
  model.getHVACComponents.sort.each do |component|
    next if component.to_Node.is_initialized # skip nodes

    unless component.plantLoop.empty?
      # rename straight component nodes
      # some inlet or outlet nodes may get renamed again
      if component.to_StraightComponent.is_initialized
        unless component.to_StraightComponent.get.inletModelObject.empty?
          component_inlet_object = component.to_StraightComponent.get.inletModelObject.get
          next unless component_inlet_object.to_Node.is_initialized

          component_inlet_object.setName("#{component.name} Inlet Water Node")
        end
        unless component.to_StraightComponent.get.outletModelObject.empty?
          component_outlet_object = component.to_StraightComponent.get.outletModelObject.get
          next unless component_outlet_object.to_Node.is_initialized

          component_outlet_object.setName("#{component.name} Outlet Water Node")
        end
      end

      # rename water to air component nodes
      if component.to_WaterToAirComponent.is_initialized
        component = component.to_WaterToAirComponent.get
        unless component.waterInletModelObject.empty?
          component_inlet_object = component.waterInletModelObject.get
          next unless component_inlet_object.to_Node.is_initialized

          component_inlet_object.setName("#{component.name} Inlet Water Node")
        end
        unless component.waterOutletModelObject.empty?
          component_outlet_object = component.waterOutletModelObject.get
          next unless component_outlet_object.to_Node.is_initialized

          component_outlet_object.setName("#{component.name} Outlet Water Node")
        end
      end

      # rename water to water component nodes
      if component.to_WaterToWaterComponent.is_initialized
        component = component.to_WaterToWaterComponent.get
        unless component.demandInletModelObject.empty?
          demand_inlet_object = component.demandInletModelObject.get
          next unless demand_inlet_object.to_Node.is_initialized

          demand_inlet_object.setName("#{component.name} Demand Inlet Water Node")
        end
        unless component.demandOutletModelObject.empty?
          demand_outlet_object = component.demandOutletModelObject.get
          next unless demand_outlet_object.to_Node.is_initialized

          demand_outlet_object.setName("#{component.name} Demand Outlet Water Node")
        end
        unless component.supplyInletModelObject.empty?
          supply_inlet_object = component.supplyInletModelObject.get
          next unless supply_inlet_object.to_Node.is_initialized

          supply_inlet_object.setName("#{component.name} Supply Inlet Water Node")
        end
        unless component.supplyOutletModelObject .empty?
          supply_outlet_object = component.supplyOutletModelObject .get
          next unless supply_outlet_object.to_Node.is_initialized

          supply_outlet_object.setName("#{component.name} Supply Outlet Water Node")
        end
      end
    end
  end

  # rename plant nodes
  model.getPlantLoops.sort.each do |plant_loop|
    plant_loop_name = plant_loop.name.to_s
    plant_loop.demandInletNode.setName("#{plant_loop_name} Demand Inlet Node")
    plant_loop.demandOutletNode.setName("#{plant_loop_name} Demand Outlet Node")
    plant_loop.supplyInletNode.setName("#{plant_loop_name} Supply Inlet Node")
    plant_loop.supplyOutletNode.setName("#{plant_loop_name} Supply Outlet Node")
  end

  return model
end
safe_load_model(model_path_string) click to toggle source

load a model into OS & version translates, exiting and erroring if a problem is found

@param model_path_string [String] file path to OpenStudio model file @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 8
def safe_load_model(model_path_string)
  model_path = OpenStudio::Path.new(model_path_string)
  if OpenStudio.exists(model_path)
    version_translator = OpenStudio::OSVersion::VersionTranslator.new
    model = version_translator.loadModel(model_path)
    if model.empty?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Version translation failed for #{model_path_string}")
      return false
    else
      model = model.get
    end
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "#{model_path_string} couldn't be found")
    return false
  end
  return model
end
seer_to_cop(seer) click to toggle source

Convert from SEER to COP (with fan) for cooling coils per the method specified in Thornton et al. 2011

@param seer [Double] seasonal energy efficiency ratio (SEER) @return [Double] Coefficient of Performance (COP)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 267
def seer_to_cop(seer)
  eer = -0.0182 * seer * seer + 1.1088 * seer
  cop = eer_to_cop(eer)

  return cop
end
seer_to_cop_no_fan(seer) click to toggle source

Convert from SEER to COP (no fan) for cooling coils @ref [References::ASHRAE9012013] Appendix G

@param seer [Double] seasonal energy efficiency ratio (SEER) @return [Double] Coefficient of Performance (COP)

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 244
def seer_to_cop_no_fan(seer)
  cop = -0.0076 * seer * seer + 0.3796 * seer

  return cop
end
set_maximum_fraction_outdoor_air_schedule(air_loop_hvac, oa_control, snc) click to toggle source

Create an economizer maximum OA fraction schedule with For ASHRAE 90.1 2019, a maximum of 75% to reflect damper leakage per PNNL

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] HVAC air loop object @param oa_control [OpenStudio::Model::ControllerOutdoorAir] Outdoor air controller object to have this maximum OA fraction schedule @param snc [String] System name @return [OpenStudio::Model::ScheduleRuleset] Generated maximum outdoor air fraction schedule for later use

# File lib/openstudio-standards/standards/Standards.AirLoopHVAC.rb, line 3874
def set_maximum_fraction_outdoor_air_schedule(air_loop_hvac, oa_control, snc)
  max_oa_sch_name = "#{snc}maxOASch"
  max_oa_sch = OpenStudio::Model::ScheduleRuleset.new(air_loop_hvac.model)
  max_oa_sch.setName(max_oa_sch_name)
  max_oa_sch.defaultDaySchedule.setName("#{max_oa_sch_name}Default")
  max_oa_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0.7)
  oa_control.setMaximumFractionofOutdoorAirSchedule(max_oa_sch)
  return max_oa_sch
end
space_add_daylighting_controls(space, remove_existing_controls, draw_daylight_areas_for_debugging = false) click to toggle source

Adds daylighting controls (sidelighting and toplighting) per the template @note This method is super complicated because of all the polygon/geometry math required.

and therefore may not return perfect results.  However, it works well in most tested
situations.  When it fails, it will log warnings/errors for users to see.

@param space [OpenStudio::Model::Space] the space with daylighting @param remove_existing_controls [Boolean] if true, will remove existing controls then add new ones @param draw_daylight_areas_for_debugging [Boolean] If this argument is set to true,

daylight areas will be added to the model as surfaces for visual debugging.
Yellow = toplighted area, Red = primary sidelighted area,
Blue = secondary sidelighted area, Light Blue = floor

@return [Boolean] returns true if successful, false if not @todo add a list of valid choices for template argument @todo add exception for retail spaces @todo add exception 2 for skylights with VT < 0.4 @todo add exception 3 for CZ 8 where lighting < 200W @todo stop skipping non-vertical walls @todo stop skipping non-horizontal roofs @todo Determine the illuminance setpoint for the controls based on space type @todo rotate sensor to face window (only needed for glare calcs)

# File lib/openstudio-standards/standards/Standards.Space.rb, line 835
def space_add_daylighting_controls(space, remove_existing_controls, draw_daylight_areas_for_debugging = false)
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "******For #{space.name}, adding daylight controls.")

  # Get the space thermal zone
  zone = space.thermalZone
  if zone.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Space', "Space #{space.name} has no thermal zone; cannot set daylighting controls for zone.")
  else
    zone = zone.get
  end

  # Check for existing daylighting controls
  # and remove if specified in the input
  existing_daylighting_controls = space.daylightingControls
  unless existing_daylighting_controls.empty?
    if remove_existing_controls
      space_remove_daylighting_controls(space)
      zone.resetFractionofZoneControlledbyPrimaryDaylightingControl
      zone.resetFractionofZoneControlledbySecondaryDaylightingControl
    else
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}, daylight controls were already present, no additional controls added.")
      return false
    end
  end

  # Skip this space if it has no exterior windows or skylights
  ext_fen_area_m2 = 0
  space.surfaces.each do |surface|
    next unless surface.outsideBoundaryCondition == 'Outdoors'

    surface.subSurfaces.each do |sub_surface|
      next unless sub_surface.subSurfaceType == 'FixedWindow' || sub_surface.subSurfaceType == 'OperableWindow' || sub_surface.subSurfaceType == 'Skylight' || sub_surface.subSurfaceType == 'GlassDoor'

      ext_fen_area_m2 += sub_surface.netArea
    end
  end
  if ext_fen_area_m2.zero?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}, daylighting control not applicable because no exterior fenestration is present.")
    return false
  end

  areas = nil

  # Get the daylighting areas
  areas = space_daylighted_areas(space, draw_daylight_areas_for_debugging)

  # Determine the type of daylighting controls required
  req_top_ctrl, req_pri_ctrl, req_sec_ctrl = space_daylighting_control_required?(space, areas)

  # Stop here if no controls are required
  if !req_top_ctrl && !req_pri_ctrl && !req_sec_ctrl
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, no daylighting control is required.")
    return false
  end

  # Output the daylight control requirements
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, toplighting control required = #{req_top_ctrl}")
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, primary sidelighting control required = #{req_pri_ctrl}")
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, secondary sidelighting control required = #{req_sec_ctrl}")

  # Record a floor in the space for later use
  floor_surface = nil
  space.surfaces.sort.each do |surface|
    if surface.surfaceType == 'Floor'
      floor_surface = surface
      break
    end
  end

  # Find all exterior windows/skylights in the space and record their azimuths and areas
  windows = {}
  skylights = {}
  space.surfaces.sort.each do |surface|
    next unless surface.outsideBoundaryCondition == 'Outdoors' && (surface.surfaceType == 'Wall' || surface.surfaceType == 'RoofCeiling')

    # Skip non-vertical walls and non-horizontal roofs
    straight_upward = OpenStudio::Vector3d.new(0, 0, 1)
    surface_normal = surface.outwardNormal
    if surface.surfaceType == 'Wall'
      # @todo stop skipping non-vertical walls
      unless surface_normal.z.abs < 0.001
        unless surface.subSurfaces.empty?
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Cannot currently handle non-vertical walls; skipping windows on #{surface.name} in #{space.name} for daylight sensor positioning.")
          next
        end
      end
    elsif surface.surfaceType == 'RoofCeiling'
      # @todo stop skipping non-horizontal roofs
      unless surface_normal.to_s == straight_upward.to_s
        unless surface.subSurfaces.empty?
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Cannot currently handle non-horizontal roofs; skipping skylights on #{surface.name} in #{space.name} for daylight sensor positioning.")
          OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---Surface #{surface.name} has outward normal of #{surface_normal.to_s.gsub(/\[|\]/, '|')}; up is #{straight_upward.to_s.gsub(/\[|\]/, '|')}.")
          next
        end
      end
    end

    # Find the azimuth of the facade
    facade = nil
    group = surface.planarSurfaceGroup
    # The surface is not in a group; should not hit, since called from Space.surfaces
    next unless group.is_initialized

    group = group.get
    site_transformation = group.buildingTransformation
    site_vertices = site_transformation * surface.vertices
    site_outward_normal = OpenStudio.getOutwardNormal(site_vertices)
    if site_outward_normal.empty?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Space', "Could not compute outward normal for #{surface.name.get}")
      next
    end
    site_outward_normal = site_outward_normal.get
    north = OpenStudio::Vector3d.new(0.0, 1.0, 0.0)
    azimuth = if site_outward_normal.x < 0.0
                360.0 - OpenStudio.radToDeg(OpenStudio.getAngle(site_outward_normal, north))
              else
                OpenStudio.radToDeg(OpenStudio.getAngle(site_outward_normal, north))
              end

    # @todo modify to work for buildings in the southern hemisphere?
    if azimuth >= 315.0 || azimuth < 45.0
      facade = '4-North'
    elsif azimuth >= 45.0 && azimuth < 135.0
      facade = '3-East'
    elsif azimuth >= 135.0 && azimuth < 225.0
      facade = '1-South'
    elsif azimuth >= 225.0 && azimuth < 315.0
      facade = '2-West'
    end

    # Label the facade as "Up" if it is a skylight
    if surface_normal.to_s == straight_upward.to_s
      facade = '0-Up'
    end

    # Loop through all subsurfaces and
    surface.subSurfaces.sort.each do |sub_surface|
      next unless sub_surface.outsideBoundaryCondition == 'Outdoors' && (sub_surface.subSurfaceType == 'FixedWindow' || sub_surface.subSurfaceType == 'OperableWindow' || sub_surface.subSurfaceType == 'Skylight')

      # Find the area
      net_area_m2 = sub_surface.netArea

      # Find the head height and sill height of the window
      vertex_heights_above_floor = []
      sub_surface.vertices.each do |vertex|
        vertex_on_floorplane = floor_surface.plane.project(vertex)
        vertex_heights_above_floor << (vertex - vertex_on_floorplane).length
      end
      head_height_m = vertex_heights_above_floor.max
      # OpenStudio::logFree(OpenStudio::Info, "openstudio.standards.Space", "---head height = #{head_height_m}m, sill height = #{sill_height_m}m")

      # Log the window properties to use when creating daylight sensors
      properties = { facade: facade, area_m2: net_area_m2, handle: sub_surface.handle, head_height_m: head_height_m, name: sub_surface.name.get.to_s }
      if facade == '0-Up'
        skylights[sub_surface] = properties
      else
        windows[sub_surface] = properties
      end
    end
  end

  # Determine the illuminance setpoint for the controls based on space type
  daylight_stpt_lux = 375

  # find the specific space_type properties
  space_type = space.spaceType
  if space_type.empty?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Space #{space_type} is an unknown space type, assuming #{daylight_stpt_lux} Lux daylight setpoint")
  else
    space_type = space_type.get
    standards_building_type = nil
    standards_space_type = nil
    data = nil
    if space_type.standardsBuildingType.is_initialized
      standards_building_type = space_type.standardsBuildingType.get
    end
    if space_type.standardsSpaceType.is_initialized
      standards_space_type = space_type.standardsSpaceType.get
    end

    unless standards_building_type.nil? || standards_space_type.nil?
      # use the building type (standards_building_type) and space type (standards_space_type)
      # as well as template to locate the space type data
      search_criteria = {
        'template' => template,
        'building_type' => standards_building_type,
        'space_type' => standards_space_type
      }
      data = model_find_object(standards_data['space_types'], search_criteria)
    end

    if standards_building_type.nil? || standards_space_type.nil?
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Unable to determine standards building type and standards space type for space '#{space.name}' with space type '#{space_type.name}'. Assign a standards building type and standards space type to the space type object. Defaulting to a #{daylight_stpt_lux} Lux daylight setpoint.")
    elsif data.nil?
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Unable to find target illuminance setpoint data for space type '#{space_type.name}' with #{template} space type '#{standards_space_type}' in building type '#{standards_building_type}'. Defaulting to a #{daylight_stpt_lux} Lux daylight setpoint.")
    else
      # Read the illuminance setpoint value
      # If 'na', daylighting is not appropriate for this space type for some reason
      daylight_stpt_lux = data['target_illuminance_setpoint']
      if daylight_stpt_lux == 'na'
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}: daylighting is not appropriate for #{template} #{standards_building_type} #{standards_space_type}.")
        return true
      end
      # If a setpoint is specified, use that.  Otherwise use a default.
      daylight_stpt_lux = daylight_stpt_lux.to_f
      if daylight_stpt_lux.zero?
        daylight_stpt_lux = 375
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}: no specific illuminance setpoint defined for #{template} #{standards_building_type} #{standards_space_type}, assuming #{daylight_stpt_lux} Lux.")
      else
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}: illuminance setpoint = #{daylight_stpt_lux} Lux")
      end
      # for the office prototypes where core and perimeter zoning is used,
      # there are additional assumptions about how much of the daylit area can be used.
      if standards_building_type == 'Office' && standards_space_type.include?('WholeBuilding')
        psa_nongeo_frac = data['psa_nongeometry_fraction'].to_f
        ssa_nongeo_frac = data['ssa_nongeometry_fraction'].to_f
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}: assuming only #{(psa_nongeo_frac * 100).round}% of the primary sidelit area is daylightable based on typical design practice.")
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}: assuming only #{(ssa_nongeo_frac * 100).round}% of the secondary sidelit area is daylightable based on typical design practice.")
      end
    end
  end

  # Sort by priority; first by facade, then by area,
  # then by name to ensure deterministic in case identical in other ways
  sorted_windows = windows.sort_by { |_window, vals| [vals[:facade], vals[:area], vals[:name]] }
  sorted_skylights = skylights.sort_by { |_skylight, vals| [vals[:facade], vals[:area], vals[:name]] }

  # Report out the sorted skylights for debugging
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, Skylights:")
  sorted_skylights.each do |sky, p|
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---#{sky.name} #{p[:facade]}, area = #{p[:area_m2].round(2)} m^2")
  end

  # Report out the sorted windows for debugging
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, Windows:")
  sorted_windows.each do |win, p|
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---#{win.name} #{p[:facade]}, area = #{p[:area_m2].round(2)} m^2")
  end

  # Determine the sensor fractions and the attached windows
  sensor_1_frac, sensor_2_frac, sensor_1_window, sensor_2_window = space_daylighting_fractions_and_windows(space,
                                                                                                           areas,
                                                                                                           sorted_windows,
                                                                                                           sorted_skylights,
                                                                                                           req_top_ctrl,
                                                                                                           req_pri_ctrl,
                                                                                                           req_sec_ctrl)

  # Further adjust the sensor controlled fraction for the three
  # office prototypes based on assumptions about geometry that is not explicitly
  # defined in the model.
  if standards_building_type == 'Office' && standards_space_type.include?('WholeBuilding')
    sensor_1_frac *= psa_nongeo_frac unless psa_nongeo_frac.nil?
    sensor_2_frac *= ssa_nongeo_frac unless ssa_nongeo_frac.nil?
  end

  # Ensure that total controlled fraction
  # is never set above 1 (100%)
  sensor_1_frac = sensor_1_frac.round(3)
  sensor_2_frac = sensor_2_frac.round(3)
  if sensor_1_frac >= 1.0
    sensor_1_frac = 1.0 - 0.001
  end
  if sensor_1_frac + sensor_2_frac >= 1.0
    # Lower sensor_2_frac so that the total
    # is just slightly lower than 1.0
    sensor_2_frac = 1.0 - sensor_1_frac - 0.001
  end

  # Sensors
  if sensor_1_frac > 0.0
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}: sensor 1 controls #{(sensor_1_frac * 100).round}% of the zone lighting.")
  end
  if sensor_2_frac > 0.0
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}: sensor 2 controls #{(sensor_2_frac * 100).round}% of the zone lighting.")
  end

  # First sensor
  if sensor_1_window
    # OpenStudio::logFree(OpenStudio::Info, "openstudio.standards.Space", "For #{self.name}, calculating daylighted areas.")
    # runner.registerInfo("Daylight sensor 1 inside of #{sensor_1_frac.name}")
    sensor_1 = OpenStudio::Model::DaylightingControl.new(space.model)
    sensor_1.setName("#{space.name} Daylt Sensor 1")
    sensor_1.setSpace(space)
    sensor_1.setIlluminanceSetpoint(daylight_stpt_lux)
    sensor_1.setLightingControlType(space_daylighting_control_type(space))
    sensor_1.setNumberofSteppedControlSteps(3) unless space_daylighting_control_type(space) != 'Stepped' # all sensors 3-step per design
    sensor_1.setMinimumInputPowerFractionforContinuousDimmingControl(space_daylighting_minimum_input_power_fraction(space))
    sensor_1.setMinimumLightOutputFractionforContinuousDimmingControl(0.2)
    sensor_1.setProbabilityLightingwillbeResetWhenNeededinManualSteppedControl(1.0)
    sensor_1.setMaximumAllowableDiscomfortGlareIndex(22.0)

    # Place sensor depending on skylight or window
    sensor_vertex = nil
    if sensor_1_window[1][:facade] == '0-Up'
      sub_surface = sensor_1_window[0]
      outward_normal = sub_surface.outwardNormal
      centroid = OpenStudio.getCentroid(sub_surface.vertices).get
      ht_above_flr = OpenStudio.convert(2.5, 'ft', 'm').get
      outward_normal.setLength(sensor_1_window[1][:head_height_m] - ht_above_flr)
      sensor_vertex = centroid + outward_normal.reverseVector
    else
      sub_surface = sensor_1_window[0]
      window_outward_normal = sub_surface.outwardNormal
      window_centroid = OpenStudio.getCentroid(sub_surface.vertices).get
      window_outward_normal.setLength(sensor_1_window[1][:head_height_m] * 0.66)
      vertex = window_centroid + window_outward_normal.reverseVector
      vertex_on_floorplane = floor_surface.plane.project(vertex)
      floor_outward_normal = floor_surface.outwardNormal
      floor_outward_normal.setLength(OpenStudio.convert(2.5, 'ft', 'm').get)
      sensor_vertex = vertex_on_floorplane + floor_outward_normal.reverseVector
    end
    sensor_1.setPosition(sensor_vertex)

    # @todo rotate sensor to face window (only needed for glare calcs)
    zone.setPrimaryDaylightingControl(sensor_1)
    if zone.fractionofZoneControlledbyPrimaryDaylightingControl + sensor_1_frac > 1
      zone.resetFractionofZoneControlledbySecondaryDaylightingControl
    end
    zone.setFractionofZoneControlledbyPrimaryDaylightingControl(sensor_1_frac)
  end

  # Second sensor
  if sensor_2_window
    # OpenStudio::logFree(OpenStudio::Info, "openstudio.standards.Space", "For #{self.name}, calculating daylighted areas.")
    # runner.registerInfo("Daylight sensor 2 inside of #{sensor_2_frac.name}")
    sensor_2 = OpenStudio::Model::DaylightingControl.new(space.model)
    sensor_2.setName("#{space.name} Daylt Sensor 2")
    sensor_2.setSpace(space)
    sensor_2.setIlluminanceSetpoint(daylight_stpt_lux)
    sensor_2.setLightingControlType(space_daylighting_control_type(space))
    sensor_2.setNumberofSteppedControlSteps(3) unless space_daylighting_control_type(space) != 'Stepped' # all sensors 3-step per design
    sensor_2.setMinimumInputPowerFractionforContinuousDimmingControl(space_daylighting_minimum_input_power_fraction(space))
    sensor_2.setMinimumLightOutputFractionforContinuousDimmingControl(0.2)
    sensor_2.setProbabilityLightingwillbeResetWhenNeededinManualSteppedControl(1.0)
    sensor_2.setMaximumAllowableDiscomfortGlareIndex(22.0)

    # Place sensor depending on skylight or window
    sensor_vertex = nil
    if sensor_2_window[1][:facade] == '0-Up'
      sub_surface = sensor_2_window[0]
      outward_normal = sub_surface.outwardNormal
      centroid = OpenStudio.getCentroid(sub_surface.vertices).get
      ht_above_flr = OpenStudio.convert(2.5, 'ft', 'm').get
      outward_normal.setLength(sensor_2_window[1][:head_height_m] - ht_above_flr)
      sensor_vertex = centroid + outward_normal.reverseVector
    else
      sub_surface = sensor_2_window[0]
      window_outward_normal = sub_surface.outwardNormal
      window_centroid = OpenStudio.getCentroid(sub_surface.vertices).get
      window_outward_normal.setLength(sensor_2_window[1][:head_height_m] * 1.33)
      vertex = window_centroid + window_outward_normal.reverseVector
      vertex_on_floorplane = floor_surface.plane.project(vertex)
      floor_outward_normal = floor_surface.outwardNormal
      floor_outward_normal.setLength(OpenStudio.convert(2.5, 'ft', 'm').get)
      sensor_vertex = vertex_on_floorplane + floor_outward_normal.reverseVector
    end
    sensor_2.setPosition(sensor_vertex)

    # @todo rotate sensor to face window (only needed for glare calcs)
    zone.setSecondaryDaylightingControl(sensor_2)
    if zone.fractionofZoneControlledbySecondaryDaylightingControl + sensor_2_frac > 1
      zone.resetFractionofZoneControlledbyPrimaryDaylightingControl
    end
    zone.setFractionofZoneControlledbySecondaryDaylightingControl(sensor_2_frac)
  end

  return true
end
space_apply_infiltration_rate(space) click to toggle source

Set the infiltration rate for this space to include the impact of air leakage requirements in the standard.

@param space [OpenStudio::Model::Space] space object @return [Double] true if successful, false if not @todo handle doors and vestibules

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1251
def space_apply_infiltration_rate(space)
  # data center keeps positive pressure all the time, so no infiltration
  if space.spaceType.is_initialized && space.spaceType.get.standardsSpaceType.is_initialized
    std_space_type = space.spaceType.get.standardsSpaceType.get
    if std_space_type.downcase.include?('data center') || std_space_type.downcase.include?('datacenter')
      return true
    end

    if space.spaceType.get.standardsBuildingType.is_initialized
      std_bldg_type = space.spaceType.get.standardsBuildingType.get
      if std_bldg_type.downcase.include?('datacenter') && std_space_type.downcase.include?('computerroom')
        return true
      end
    end
  end

  # Determine the total building baseline infiltration rate in cfm per ft2 of exterior above grade wall area at 75 Pa
  # exterior above grade envelope area includes any surface with boundary condition 'Outdoors' in OpenStudio/EnergyPlus
  basic_infil_rate_cfm_per_ft2 = space_infiltration_rate_75_pa(space)

  # Do nothing if no infiltration
  return true if basic_infil_rate_cfm_per_ft2.zero?

  # Conversion factor
  # 1 m^3/s*m^2 = 196.85 cfm/ft2
  conv_fact = 196.85

  # Adjust the infiltration rate to the average pressure for the prototype buildings.
  adj_infil_rate_cfm_per_ft2 = OpenstudioStandards::Infiltration.adjust_infiltration_to_prototype_building_conditions(basic_infil_rate_cfm_per_ft2)
  adj_infil_rate_m3_per_s_per_m2 = adj_infil_rate_cfm_per_ft2 / conv_fact
  # Get the exterior wall area
  exterior_wall_and_window_area_m2 =  OpenstudioStandards::Geometry.space_get_exterior_wall_and_subsurface_area(space)

  # Don't create an object if there is no exterior wall area
  if exterior_wall_and_window_area_m2 <= 0.0
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}, no exterior wall area was found, no infiltration will be added.")
    return true
  end
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}, set infiltration rate to #{adj_infil_rate_cfm_per_ft2.round(3)} cfm/ft2 exterior wall area (aka #{basic_infil_rate_cfm_per_ft2} cfm/ft2 @75Pa).")

  # Calculate the total infiltration, assuming
  # that it only occurs through exterior walls
  tot_infil_m3_per_s = adj_infil_rate_m3_per_s_per_m2 * exterior_wall_and_window_area_m2

  # Now spread the total infiltration rate over all
  # exterior surface areas (for the E+ input field)
  all_ext_infil_m3_per_s_per_m2 = tot_infil_m3_per_s / space.exteriorArea

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, adj infil = #{all_ext_infil_m3_per_s_per_m2.round(8)} m^3/s*m^2.")

  # Get any infiltration schedule already assigned to this space or its space type
  # If not, the always on schedule will be applied.
  infil_sch = nil
  unless space.spaceInfiltrationDesignFlowRates.empty?
    old_infil = space.spaceInfiltrationDesignFlowRates[0]
    if old_infil.schedule.is_initialized
      infil_sch = old_infil.schedule.get
    end
  end

  if infil_sch.nil? && space.spaceType.is_initialized
    space_type = space.spaceType.get
    unless space_type.spaceInfiltrationDesignFlowRates.empty?
      old_infil = space_type.spaceInfiltrationDesignFlowRates[0]
      if old_infil.schedule.is_initialized
        infil_sch = old_infil.schedule.get
      end
    end
  end

  if infil_sch.nil?
    infil_sch = space.model.alwaysOnDiscreteSchedule
  end

  # Create an infiltration rate object for this space
  infiltration = OpenStudio::Model::SpaceInfiltrationDesignFlowRate.new(space.model)
  infiltration.setName("#{space.name} Infiltration")
  # infiltration.setFlowperExteriorWallArea(adj_infil_rate_m3_per_s_per_m2)
  infiltration.setFlowperExteriorSurfaceArea(all_ext_infil_m3_per_s_per_m2.round(13))
  infiltration.setSchedule(infil_sch)
  infiltration.setConstantTermCoefficient(0.0)
  infiltration.setTemperatureTermCoefficient 0.0
  infiltration.setVelocityTermCoefficient(0.224)
  infiltration.setVelocitySquaredTermCoefficient(0.0)

  infiltration.setSpace(space)

  return true
end
space_conditioning_category(space) click to toggle source

Determines whether the space is conditioned per 90.1, which is based on heating and cooling loads.

@param space [OpenStudio::Model::Space] space object @return [String] NonResConditioned, ResConditioned, Semiheated, Unconditioned @todo add logic to detect indirectly-conditioned spaces based on air transfer

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1355
def space_conditioning_category(space)
  # Return space conditioning category if already assigned as an additional properties
  return space.additionalProperties.getFeatureAsString('space_conditioning_category').get if space.additionalProperties.hasFeature('space_conditioning_category')

  # Get climate zone
  climate_zone = OpenstudioStandards::Weather.model_get_climate_zone(space.model)

  # Get the zone this space is inside
  zone = space.thermalZone

  # Assume unconditioned if not assigned to a zone
  if zone.empty?
    return 'Unconditioned'
  end

  # Return air plenums are indirectly conditioned spaces according to the
  # 90.1-2019 Performance Rating Method Reference Manual
  # #
  # Additionally, Section 2 of ASHRAE 90.1 states that indirectly
  # conditioned spaces are unconditioned spaces that are adjacent to
  # heated or cooled spaced and provided that air from these spaces is
  # intentionally transferred into the space at a rate exceeding 3 ach
  # which most if not all return air plenum do.
  space.model.getAirLoopHVACReturnPlenums.each do |return_air_plenum|
    if return_air_plenum.thermalZone.get.name.to_s == zone.get.name.to_s
      # Determine if residential
      res = OpenstudioStandards::ThermalZone.thermal_zone_residential?(zone.get) ? true : false

      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "Zone #{zone.get.name} is (indirectly) conditioned (return air plenum).")
      cond_cat = res ? 'ResConditioned' : 'NonResConditioned'

      return cond_cat
    end
  end
  # Following the same assumptions,  we designate supply air plenums
  # as indirectly conditioned as well
  space.model.getAirLoopHVACSupplyPlenums.each do |supply_air_plenum|
    if supply_air_plenum.thermalZone.get.name.to_s == zone.get.name.to_s
      # Determine if residential
      res = OpenstudioStandards::ThermalZone.thermal_zone_residential?(zone.get) ? true : false

      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "Zone #{zone.get.name} is (indirectly) conditioned (supply air plenum).")
      cond_cat = res ? 'ResConditioned' : 'NonResConditioned'

      return cond_cat
    end
  end

  # Get the category from the zone, this methods does NOT detect indirectly
  # conditioned spaces
  cond_cat = thermal_zone_conditioning_category(zone.get, climate_zone)

  # Detect indirectly conditioned spaces based on UA sum product comparison
  if cond_cat == 'Unconditioned'

    # Initialize UA sum product for surfaces adjacent to conditioned spaces
    cond_ua = 0

    # Initialize UA sum product for surfaces adjacent to unconditoned spaces,
    # semi-heated spaces and outdoors
    otr_ua = 0

    space.surfaces.sort.each do |surface|
      # Surfaces adjacent to other surfaces can be next to conditioned,
      # unconditioned or semi-heated spaces
      if surface.outsideBoundaryCondition == 'Surface'

        # Retrieve adjacent space conditioning category
        adj_space = surface.adjacentSurface.get.space.get
        adj_zone = adj_space.thermalZone.get
        adj_space_cond_type = thermal_zone_conditioning_category(adj_zone, climate_zone)

        # adj_zone == zone.get means that the surface is adjacent to its zone
        # This is translated by an adiabtic outside boundary condition, which are
        # assumed to be used only if the surface is adjacent to a conditioned space
        if adj_space_cond_type == 'ResConditioned' || adj_space_cond_type == 'NonResConditioned' || adj_zone == zone.get
          cond_ua += surface_subsurface_ua(surface)
        else
          otr_ua += surface_subsurface_ua(surface)
        end

      # Adiabtic outside boundary condition are assumed to be used only if the
      # surface is adjacent to a conditioned space
      elsif surface.outsideBoundaryCondition == 'Adiabatic'

        # If the surface is a floor and is located at the lowest floor of the
        # building it is assumed to be adjacent to an unconditioned space
        # (i.e. ground)
        if surface.surfaceType == 'Floor' && surface.space.get.buildingStory == find_lowest_story(surface.model)
          otr_ua += surface_subsurface_ua(surface)
        else
          cond_ua += surface_subsurface_ua(surface)
        end

      # All other outside boundary conditions are assumed to be adjacent to either:
      # outdoors or ground and hence count towards the unconditioned UA product
      else
        otr_ua += surface_subsurface_ua(surface)
      end
    end

    # Determine if residential
    res = OpenstudioStandards::ThermalZone.thermal_zone_residential?(zone.get) ? true : false

    return cond_cat unless cond_ua > otr_ua

    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "Zone #{zone.get.name} is (indirectly) conditioned because its conditioned UA product (#{cond_ua.round} W/K) exceeds its non-conditioned UA product (#{otr_ua.round} W/K).")
    cond_cat = res ? 'ResConditioned' : 'NonResConditioned'
  end

  return cond_cat
end
space_daylighted_area_window_width(space) click to toggle source

Determines the method used to extend the daylighted area horizontally next to a window. If the method is ‘fixed’, 2 ft is added to the width of each window. If the method is ‘proportional’, a distance equal to half of the head height of the window is added. If the method is ‘none’, no additional width is added. Default is none.

@param space [OpenStudio::Model::Space] space object @return [String] returns ‘fixed’ or ‘proportional’

# File lib/openstudio-standards/standards/Standards.Space.rb, line 553
def space_daylighted_area_window_width(space)
  method = 'none'
  return method
end
space_daylighted_areas(space, draw_daylight_areas_for_debugging = false) click to toggle source

Returns values for the different types of daylighted areas in the space. Definitions for each type of area follow the respective template. @note This method is super complicated because of all the polygon/geometry math required.

and therefore may not return perfect results.  However, it works well in most tested
situations.  When it fails, it will log warnings/errors for users to see.

@param space [OpenStudio::Model::Space] space object @param draw_daylight_areas_for_debugging [Boolean] If this argument is set to true,

daylight areas will be added to the model as surfaces for visual debugging.
Yellow = toplighted area, Red = primary sidelighted area,
Blue = secondary sidelighted area, Light Blue = floor

@return [Hash] returns a hash of resulting areas (m^2).

Hash keys are: 'toplighted_area', 'primary_sidelighted_area',
'secondary_sidelighted_area', 'total_window_area', 'total_skylight_area'

@todo add a list of valid choices for template argument @todo stop skipping non-vertical walls

# File lib/openstudio-standards/standards/Standards.Space.rb, line 20
def space_daylighted_areas(space, draw_daylight_areas_for_debugging = false)
  ### Begin the actual daylight area calculations ###

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, calculating daylighted areas.")

  result = { 'toplighted_area' => 0.0,
             'primary_sidelighted_area' => 0.0,
             'secondary_sidelighted_area' => 0.0,
             'total_window_area' => 0.0,
             'total_skylight_area' => 0.0 }

  total_window_area = 0
  total_skylight_area = 0

  # Make rendering colors to help debug visually
  if draw_daylight_areas_for_debugging
    # Yellow
    toplit_construction = OpenStudio::Model::Construction.new(space.model)
    toplit_color = OpenStudio::Model::RenderingColor.new(space.model)
    toplit_color.setRenderingRedValue(255)
    toplit_color.setRenderingGreenValue(255)
    toplit_color.setRenderingBlueValue(0)
    toplit_construction.setRenderingColor(toplit_color)

    # Red
    pri_sidelit_construction = OpenStudio::Model::Construction.new(space.model)
    pri_sidelit_color = OpenStudio::Model::RenderingColor.new(space.model)
    pri_sidelit_color.setRenderingRedValue(255)
    pri_sidelit_color.setRenderingGreenValue(0)
    pri_sidelit_color.setRenderingBlueValue(0)
    pri_sidelit_construction.setRenderingColor(pri_sidelit_color)

    # Blue
    sec_sidelit_construction = OpenStudio::Model::Construction.new(space.model)
    sec_sidelit_color = OpenStudio::Model::RenderingColor.new(space.model)
    sec_sidelit_color.setRenderingRedValue(0)
    sec_sidelit_color.setRenderingGreenValue(0)
    sec_sidelit_color.setRenderingBlueValue(255)
    sec_sidelit_construction.setRenderingColor(sec_sidelit_color)

    # Light Blue
    flr_construction = OpenStudio::Model::Construction.new(space.model)
    flr_color = OpenStudio::Model::RenderingColor.new(space.model)
    flr_color.setRenderingRedValue(0)
    flr_color.setRenderingGreenValue(255)
    flr_color.setRenderingBlueValue(255)
    flr_construction.setRenderingColor(flr_color)
  end

  # Move the polygon up slightly for viewability in sketchup
  up_translation_flr = OpenStudio.createTranslation(OpenStudio::Vector3d.new(0, 0, 0.05))
  up_translation_top = OpenStudio.createTranslation(OpenStudio::Vector3d.new(0, 0, 0.1))
  up_translation_pri = OpenStudio.createTranslation(OpenStudio::Vector3d.new(0, 0, 0.1))
  up_translation_sec = OpenStudio.createTranslation(OpenStudio::Vector3d.new(0, 0, 0.1))

  # Get the space's surface group's transformation
  @space_transformation = space.transformation

  # Record a floor in the space for later use
  floor_surface = nil

  # Record all floor polygons
  floor_polygons = []
  floor_z = 0.0
  space.surfaces.sort.each do |surface|
    if surface.surfaceType == 'Floor'
      floor_surface = surface
      floor_z = surface.vertices[0].z
      # floor_polygons << surface.vertices
      # Hard-set the z for the floor to zero
      new_floor_polygon = []
      surface.vertices.each do |vertex|
        new_floor_polygon << OpenStudio::Point3d.new(vertex.x, vertex.y, 0.0)
      end
      floor_polygons << new_floor_polygon
    end
  end

  # Make sure there is one floor surface
  if floor_surface.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Could not find a floor in space #{space.name}, cannot determine daylighted areas.")
    return result
  end

  # Make a set of vertices representing each subsurfaces sidelighteding area
  # and fold them all down onto the floor of the self.
  toplit_polygons = []
  pri_sidelit_polygons = []
  sec_sidelit_polygons = []
  space.surfaces.sort.each do |surface|
    if surface.outsideBoundaryCondition == 'Outdoors' && surface.surfaceType == 'Wall'

      # @todo stop skipping non-vertical walls
      surface_normal = surface.outwardNormal
      surface_normal_z = surface_normal.z
      unless surface_normal_z.abs < 0.001
        unless surface.subSurfaces.empty?
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Cannot currently handle non-vertical walls; skipping windows on #{surface.name} in #{space.name}.")
          next
        end
      end

      surface.subSurfaces.sort.each do |sub_surface|
        next unless sub_surface.outsideBoundaryCondition == 'Outdoors' && (sub_surface.subSurfaceType == 'FixedWindow' || sub_surface.subSurfaceType == 'OperableWindow' || sub_surface.subSurfaceType == 'GlassDoor')

        # OpenStudio::logFree(OpenStudio::Debug, "openstudio.standards.Space", "***#{sub_surface.name}***"
        total_window_area += sub_surface.netArea

        # Find the head height and sill height of the window
        vertex_heights_above_floor = []
        sub_surface.vertices.each do |vertex|
          vertex_on_floorplane = floor_surface.plane.project(vertex)
          vertex_heights_above_floor << (vertex - vertex_on_floorplane).length
        end
        sill_height_m = vertex_heights_above_floor.min
        head_height_m = vertex_heights_above_floor.max
        # OpenStudio::logFree(OpenStudio::Debug, "openstudio.standards.Space", "head height = #{head_height_m.round(2)}m, sill height = #{sill_height_m.round(2)}m")

        # Find the width of the window
        rot_origin = nil
        unless sub_surface.vertices.size == 4
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "A sub-surface in space #{space.name} has other than 4 vertices; this sub-surface will not be included in the daylighted area calculation.")
          next
        end
        prev_vertex_on_floorplane = nil
        max_window_width_m = 0
        sub_surface.vertices.each do |vertex|
          vertex_on_floorplane = floor_surface.plane.project(vertex)
          unless prev_vertex_on_floorplane
            prev_vertex_on_floorplane = vertex_on_floorplane
            next
          end
          width_m = (prev_vertex_on_floorplane - vertex_on_floorplane).length
          if width_m > max_window_width_m
            max_window_width_m = width_m
            rot_origin = vertex_on_floorplane
          end
        end

        # Determine the extra width to add to the sidelighted area
        extra_width_m = 0
        width_method = space_daylighted_area_window_width(space)
        if width_method == 'proportional'
          extra_width_m = head_height_m / 2
        elsif width_method == 'fixed'
          extra_width_m = OpenStudio.convert(2, 'ft', 'm').get
        end
        # OpenStudio::logFree(OpenStudio::Debug, "openstudio.standards.Space", "Adding #{extra_width_m.round(2)}m to the width for the sidelighted area.")

        # Align the vertices with face coordinate system
        face_transform = OpenStudio::Transformation.alignFace(sub_surface.vertices)
        aligned_vertices = face_transform.inverse * sub_surface.vertices

        # Find the min and max x values
        min_x_val = 99_999
        max_x_val = -99_999
        aligned_vertices.each do |vertex|
          # Min x value
          if vertex.x < min_x_val
            min_x_val = vertex.x
          end
          # Max x value
          if vertex.x > max_x_val
            max_x_val = vertex.x
          end
        end
        # OpenStudio::logFree(OpenStudio::Debug, "openstudio.standards.Space", "min_x_val = #{min_x_val.round(2)}, max_x_val = #{max_x_val.round(2)}")

        # Create polygons that are adjusted
        # to expand from the window shape to the sidelighteded areas.
        pri_sidelit_sub_polygon = []
        sec_sidelit_sub_polygon = []
        aligned_vertices.each do |vertex|
          # Primary sidelighted area
          # Move the x vertices outward by the specified amount.
          if (vertex.x - min_x_val).abs < 0.01
            new_x = vertex.x - extra_width_m
          elsif (vertex.x - max_x_val).abs < 0.01
            new_x = vertex.x + extra_width_m
          else
            new_x = 99.9
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "A window in space #{space.name} is non-rectangular; this sub-surface will not be included in the primary daylighted area calculation. #{vertex.x} != #{min_x_val} or #{max_x_val}")
          end

          # Zero-out the y for the bottom edge because the
          # sidelighteding area extends down to the floor.
          new_y = if vertex.y.zero?
                    vertex.y - sill_height_m
                  else
                    vertex.y
                  end

          # Set z = 0 so that intersection works.
          new_z = 0.0

          # Make the new vertex
          new_vertex = OpenStudio::Point3d.new(new_x, new_y, new_z)
          pri_sidelit_sub_polygon << new_vertex
          # OpenStudio::logFree(OpenStudio::Info, "openstudio.standards.Space", "#{vertex.x.round(2)}, #{vertex.y.round(2)}, #{vertex.z.round(2)} to #{new_vertex.x.round(2)}, #{new_vertex.y.round(2)}, #{new_vertex.z.round(2)}")

          # Secondary sidelighted area
          # Move the x vertices outward by the specified amount.
          if (vertex.x - min_x_val).abs < 0.01
            new_x = vertex.x - extra_width_m
          elsif (vertex.x - max_x_val).abs < 0.01
            new_x = vertex.x + extra_width_m
          else
            new_x = 99.9
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "A window in space #{space.name} is non-rectangular; this sub-surface will not be included in the secondary daylighted area calculation.")
          end

          # Add the head height of the window to all points
          # sidelighteding area extends down to the floor.
          new_y = if vertex.y.zero?
                    vertex.y - sill_height_m + head_height_m
                  else
                    vertex.y + head_height_m
                  end

          # Set z = 0 so that intersection works.
          new_z = 0.0

          # Make the new vertex
          new_vertex = OpenStudio::Point3d.new(new_x, new_y, new_z)
          sec_sidelit_sub_polygon << new_vertex
        end

        # Realign the vertices with space coordinate system
        pri_sidelit_sub_polygon = face_transform * pri_sidelit_sub_polygon
        sec_sidelit_sub_polygon = face_transform * sec_sidelit_sub_polygon

        # Rotate the sidelighteded areas down onto the floor
        down_vector = OpenStudio::Vector3d.new(0, 0, -1)
        outward_normal_vector = sub_surface.outwardNormal
        rot_vector = down_vector.cross(outward_normal_vector)
        ninety_deg_in_rad = OpenStudio.degToRad(90)
        # @todo change
        new_rotation = OpenStudio.createRotation(rot_origin, rot_vector, ninety_deg_in_rad)
        pri_sidelit_sub_polygon = new_rotation * pri_sidelit_sub_polygon
        sec_sidelit_sub_polygon = new_rotation * sec_sidelit_sub_polygon

        # Put the polygon vertices into counterclockwise order
        pri_sidelit_sub_polygon = pri_sidelit_sub_polygon.reverse
        sec_sidelit_sub_polygon = sec_sidelit_sub_polygon.reverse

        # Add these polygons to the list
        pri_sidelit_polygons << pri_sidelit_sub_polygon
        sec_sidelit_polygons << sec_sidelit_sub_polygon
      end
    elsif surface.outsideBoundaryCondition == 'Outdoors' && surface.surfaceType == 'RoofCeiling'

      # @todo stop skipping non-horizontal roofs
      surface_normal = surface.outwardNormal
      straight_upward = OpenStudio::Vector3d.new(0, 0, 1)
      unless surface_normal.to_s == straight_upward.to_s
        unless surface.subSurfaces.empty?
          OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Cannot currently handle non-horizontal roofs; skipping skylights on #{surface.name} in #{space.name}.")
          OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---Surface #{surface.name} has outward normal of #{surface_normal.to_s.gsub(/\[|\]/, '|')}; up is #{straight_upward.to_s.gsub(/\[|\]/, '|')}.")
          next
        end
      end

      surface.subSurfaces.sort.each do |sub_surface|
        next unless sub_surface.outsideBoundaryCondition == 'Outdoors' && sub_surface.subSurfaceType == 'Skylight'

        # OpenStudio::logFree(OpenStudio::Debug, "openstudio.standards.Space", "***#{sub_surface.name}***")
        total_skylight_area += sub_surface.netArea

        # Project the skylight onto the floor plane
        polygon_on_floor = []
        vertex_heights_above_floor = []
        sub_surface.vertices.each do |vertex|
          vertex_on_floorplane = floor_surface.plane.project(vertex)
          vertex_heights_above_floor << (vertex - vertex_on_floorplane).length
          polygon_on_floor << vertex_on_floorplane
        end

        # Determine the ceiling height.
        # Assumes skylight is flush with ceiling.
        ceiling_height_m = vertex_heights_above_floor.max

        # Align the vertices with face coordinate system
        face_transform = OpenStudio::Transformation.alignFace(polygon_on_floor)
        aligned_vertices = face_transform.inverse * polygon_on_floor

        # Find the min and max x and y values
        min_x_val = 99_999
        max_x_val = -99_999
        min_y_val = 99_999
        max_y_val = -99_999
        aligned_vertices.each do |vertex|
          # Min x value
          if vertex.x < min_x_val
            min_x_val = vertex.x
          end
          # Max x value
          if vertex.x > max_x_val
            max_x_val = vertex.x
          end
          # Min y value
          if vertex.y < min_y_val
            min_y_val = vertex.y
          end
          # Max y value
          if vertex.y > max_y_val
            max_y_val = vertex.y
          end
        end

        # Figure out how much to expand the window
        additional_extent_m = 0.7 * ceiling_height_m

        # Create polygons that are adjusted
        # to expand from the window shape to the sidelighteded areas.
        toplit_sub_polygon = []
        aligned_vertices.each do |vertex|
          # Move the x vertices outward by the specified amount.
          if vertex.x == min_x_val
            new_x = vertex.x - additional_extent_m
          elsif vertex.x == max_x_val
            new_x = vertex.x + additional_extent_m
          else
            new_x = 99.9
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "A skylight in space #{space.name} is non-rectangular; this sub-surface will not be included in the daylighted area calculation.")
          end

          # Move the y vertices outward by the specified amount.
          if vertex.y == min_y_val
            new_y = vertex.y - additional_extent_m
          elsif vertex.y == max_y_val
            new_y = vertex.y + additional_extent_m
          else
            new_y = 99.9
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "A skylight in space #{space.name} is non-rectangular; this sub-surface will not be included in the daylighted area calculation.")
          end

          # Set z = 0 so that intersection works.
          new_z = 0.0

          # Make the new vertex
          new_vertex = OpenStudio::Point3d.new(new_x, new_y, new_z)
          toplit_sub_polygon << new_vertex
        end

        # Realign the vertices with space coordinate system
        toplit_sub_polygon = face_transform * toplit_sub_polygon

        # Put the polygon vertices into counterclockwise order
        toplit_sub_polygon = toplit_sub_polygon.reverse

        # Add these polygons to the list
        toplit_polygons << toplit_sub_polygon
      end

    end
  end

  # Set z=0 for all the polygons so that intersection will work
  toplit_polygons = space_polygons_set_z(space, toplit_polygons, 0.0)
  pri_sidelit_polygons = space_polygons_set_z(space, pri_sidelit_polygons, 0.0)
  sec_sidelit_polygons = space_polygons_set_z(space, sec_sidelit_polygons, 0.0)

  # Check the initial polygons
  space_check_z_zero(space, floor_polygons, 'floor_polygons')
  space_check_z_zero(space, toplit_polygons, 'toplit_polygons')
  space_check_z_zero(space, pri_sidelit_polygons, 'pri_sidelit_polygons')
  space_check_z_zero(space, sec_sidelit_polygons, 'sec_sidelit_polygons')

  # Join, then subtract
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '***Joining polygons***')

  # Join toplighted polygons into a single set
  combined_toplit_polygons = space_join_polygons(space, toplit_polygons, 0.01, 'toplit_polygons')

  # Join primary sidelighted polygons into a single set
  combined_pri_sidelit_polygons = space_join_polygons(space, pri_sidelit_polygons, 0.01, 'pri_sidelit_polygons')

  # Join secondary sidelighted polygons into a single set
  combined_sec_sidelit_polygons = space_join_polygons(space, sec_sidelit_polygons, 0.01, 'sec_sidelit_polygons')

  # Join floor polygons into a single set
  combined_floor_polygons = space_join_polygons(space, floor_polygons, 0.01, 'floor_polygons')

  # Check the joined polygons
  space_check_z_zero(space, combined_floor_polygons, 'combined_floor_polygons')
  space_check_z_zero(space, combined_toplit_polygons, 'combined_toplit_polygons')
  space_check_z_zero(space, combined_pri_sidelit_polygons, 'combined_pri_sidelit_polygons')
  space_check_z_zero(space, combined_sec_sidelit_polygons, 'combined_sec_sidelit_polygons')

  # Make a new surface for each of the resulting polygons to visually inspect it
  # OpenStudio::logFree(OpenStudio::Debug, "openstudio.standards.Space", "***Making Surfaces to view in SketchUp***")

  # combined_toplit_polygons.each do |polygon|
  # dummy_space = OpenStudio::Model::Space.new(model)
  # polygon = up_translation_top * polygon
  # daylt_surf = OpenStudio::Model::Surface.new(polygon, model)
  # daylt_surf.setConstruction(toplit_construction)
  # daylt_surf.setSpace(dummy_space)
  # daylt_surf.setName("Top")
  # end

  # combined_pri_sidelit_polygons.each do |polygon|
  # dummy_space = OpenStudio::Model::Space.new(model)
  # polygon = up_translation_pri * polygon
  # daylt_surf = OpenStudio::Model::Surface.new(polygon, model)
  # daylt_surf.setConstruction(pri_sidelit_construction)
  # daylt_surf.setSpace(dummy_space)
  # daylt_surf.setName("Pri")
  # end

  # combined_sec_sidelit_polygons.each do |polygon|
  # dummy_space = OpenStudio::Model::Space.new(model)
  # polygon = up_translation_sec * polygon
  # daylt_surf = OpenStudio::Model::Surface.new(polygon, model)
  # daylt_surf.setConstruction(sec_sidelit_construction)
  # daylt_surf.setSpace(dummy_space)
  # daylt_surf.setName("Sec")
  # end

  # combined_floor_polygons.each do |polygon|
  # dummy_space = OpenStudio::Model::Space.new(model)
  # polygon = up_translation_flr * polygon
  # daylt_surf = OpenStudio::Model::Surface.new(polygon, model)
  # daylt_surf.setConstruction(flr_construction)
  # daylt_surf.setSpace(dummy_space)
  # daylt_surf.setName("Flr")
  # end

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '***Subtracting overlapping areas***')

  # Subtract lower-priority daylighting areas from higher priority ones
  pri_minus_top_polygons = space_a_polygons_minus_b_polygons(space, combined_pri_sidelit_polygons, combined_toplit_polygons, 'combined_pri_sidelit_polygons', 'combined_toplit_polygons')

  sec_minus_top_polygons = space_a_polygons_minus_b_polygons(space, combined_sec_sidelit_polygons, combined_toplit_polygons, 'combined_sec_sidelit_polygons', 'combined_toplit_polygons')

  sec_minus_top_minus_pri_polygons = space_a_polygons_minus_b_polygons(space, sec_minus_top_polygons, combined_pri_sidelit_polygons, 'sec_minus_top_polygons', 'combined_pri_sidelit_polygons')

  # Check the subtracted polygons
  space_check_z_zero(space, pri_minus_top_polygons, 'pri_minus_top_polygons')
  space_check_z_zero(space, sec_minus_top_polygons, 'sec_minus_top_polygons')
  space_check_z_zero(space, sec_minus_top_minus_pri_polygons, 'sec_minus_top_minus_pri_polygons')

  # Make a new surface for each of the resulting polygons to visually inspect it.
  # First reset the z so the surfaces show up on the correct plane.
  if draw_daylight_areas_for_debugging

    combined_toplit_polygons_at_floor = space_polygons_set_z(space, combined_toplit_polygons, floor_z)
    pri_minus_top_polygons_at_floor = space_polygons_set_z(space, pri_minus_top_polygons, floor_z)
    sec_minus_top_minus_pri_polygons_at_floor = space_polygons_set_z(space, sec_minus_top_minus_pri_polygons, floor_z)
    combined_floor_polygons_at_floor = space_polygons_set_z(space, combined_floor_polygons, floor_z)

    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '***Making Surfaces to view in SketchUp***')
    dummy_space = OpenStudio::Model::Space.new(space.model)

    combined_toplit_polygons_at_floor.each do |polygon|
      polygon = up_translation_top * polygon
      polygon = @space_transformation * polygon
      daylt_surf = OpenStudio::Model::Surface.new(polygon, space.model)
      daylt_surf.setConstruction(toplit_construction)
      daylt_surf.setSpace(dummy_space)
      daylt_surf.setName('Top')
    end

    pri_minus_top_polygons_at_floor.each do |polygon|
      polygon = up_translation_pri * polygon
      polygon = @space_transformation * polygon
      daylt_surf = OpenStudio::Model::Surface.new(polygon, space.model)
      daylt_surf.setConstruction(pri_sidelit_construction)
      daylt_surf.setSpace(dummy_space)
      daylt_surf.setName('Pri')
    end

    sec_minus_top_minus_pri_polygons_at_floor.each do |polygon|
      polygon = up_translation_sec * polygon
      polygon = @space_transformation * polygon
      daylt_surf = OpenStudio::Model::Surface.new(polygon, space.model)
      daylt_surf.setConstruction(sec_sidelit_construction)
      daylt_surf.setSpace(dummy_space)
      daylt_surf.setName('Sec')
    end

    combined_floor_polygons_at_floor.each do |polygon|
      polygon = up_translation_flr * polygon
      polygon = @space_transformation * polygon
      daylt_surf = OpenStudio::Model::Surface.new(polygon, space.model)
      daylt_surf.setConstruction(flr_construction)
      daylt_surf.setSpace(dummy_space)
      daylt_surf.setName('Flr')
    end
  end

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '***Calculating Daylighted Areas***')

  # Get the total floor area
  total_floor_area_m2 = space_total_area_of_polygons(space, combined_floor_polygons)
  total_floor_area_ft2 = OpenStudio.convert(total_floor_area_m2, 'm^2', 'ft^2').get
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "total_floor_area_ft2 = #{total_floor_area_ft2.round(1)}")

  # Toplighted area
  toplighted_area_m2 = space_area_a_polygons_overlap_b_polygons(space, combined_toplit_polygons, combined_floor_polygons, 'combined_toplit_polygons', 'combined_floor_polygons')

  # Primary sidelighted area
  primary_sidelighted_area_m2 = space_area_a_polygons_overlap_b_polygons(space, pri_minus_top_polygons, combined_floor_polygons, 'pri_minus_top_polygons', 'combined_floor_polygons')

  # Secondary sidelighted area
  secondary_sidelighted_area_m2 = space_area_a_polygons_overlap_b_polygons(space, sec_minus_top_minus_pri_polygons, combined_floor_polygons, 'sec_minus_top_minus_pri_polygons', 'combined_floor_polygons')

  # Convert to IP for displaying
  toplighted_area_ft2 = OpenStudio.convert(toplighted_area_m2, 'm^2', 'ft^2').get
  primary_sidelighted_area_ft2 = OpenStudio.convert(primary_sidelighted_area_m2, 'm^2', 'ft^2').get
  secondary_sidelighted_area_ft2 = OpenStudio.convert(secondary_sidelighted_area_m2, 'm^2', 'ft^2').get

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "toplighted_area_ft2 = #{toplighted_area_ft2.round(1)}")
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "primary_sidelighted_area_ft2 = #{primary_sidelighted_area_ft2.round(1)}")
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "secondary_sidelighted_area_ft2 = #{secondary_sidelighted_area_ft2.round(1)}")

  result['toplighted_area'] = toplighted_area_m2
  result['primary_sidelighted_area'] = primary_sidelighted_area_m2
  result['secondary_sidelighted_area'] = secondary_sidelighted_area_m2
  result['total_window_area'] = total_window_area
  result['total_skylight_area'] = total_skylight_area

  return result
end
space_daylighting_control_required?(space, areas) click to toggle source

Determine if the space requires daylighting controls for toplighting, primary sidelighting, and secondary sidelighting. Defaults to false for all types.

@param space [OpenStudio::Model::Space] the space in question @param areas [Hash] a hash of daylighted areas @return [Array<Bool>] req_top_ctrl, req_pri_ctrl, req_sec_ctrl

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1212
def space_daylighting_control_required?(space, areas)
  req_top_ctrl = false
  req_pri_ctrl = false
  req_sec_ctrl = false

  return [req_top_ctrl, req_pri_ctrl, req_sec_ctrl]
end
space_daylighting_fractions_and_windows(space, areas, sorted_windows, sorted_skylights, req_top_ctrl, req_pri_ctrl, req_sec_ctrl) click to toggle source

Determine the fraction controlled by each sensor and which window each sensor should go near.

@param space [OpenStudio::Model::Space] space object @param areas [Hash] a hash of daylighted areas @param sorted_windows [Hash] a hash of windows, sorted by priority @param sorted_skylights [Hash] a hash of skylights, sorted by priority @param req_top_ctrl [Boolean] if toplighting controls are required @param req_pri_ctrl [Boolean] if primary sidelighting controls are required @param req_sec_ctrl [Boolean] if secondary sidelighting controls are required @return [Array] array of 4 items

[sensor 1 fraction, sensor 2 fraction, sensor 1 window, sensor 2 window]
# File lib/openstudio-standards/standards/Standards.Space.rb, line 1231
def space_daylighting_fractions_and_windows(space,
                                            areas,
                                            sorted_windows,
                                            sorted_skylights,
                                            req_top_ctrl,
                                            req_pri_ctrl,
                                            req_sec_ctrl)
  sensor_1_frac = 0.0
  sensor_2_frac = 0.0
  sensor_1_window = nil
  sensor_2_window = nil

  return [sensor_1_frac, sensor_2_frac, sensor_1_window, sensor_2_window]
end
space_get_equip_annual_array(model, space, equip, eqp_type, ppl_total, load_values, return_noncoincident_value) click to toggle source

Returns an 8760 array of load values for a specific type of load in a space. This is useful for the Appendix G test for multizone systems to determine whether specific zones should be isolated to PSZ based on space loads that differ significantly from other zones on the multizone system

@param model [OpenStudio::Model::Model] OpenStudio model object @param space [OpenStudio::Model::Space] the space @param equip [object] This can be any type of equipment object in the space @param eqp_type [String] string description of the type of equipment object @param ppl_total [Numeric] total number of people in the space @param load_values [Array] 8760 array of load values for the equipment type @param return_noncoincident_value [Boolean] return a single peak value if true; return 8760 gain profile if false @return [Array] load values array; if return_noncoincident_value is true, array has only one value

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1784
def space_get_equip_annual_array(model, space, equip, eqp_type, ppl_total, load_values, return_noncoincident_value)
  # Get load schedule and load lost value depending on equipment type
  case eqp_type
  when 'electric equipment'
    load_sch = equip.schedule
    load_lost = equip.electricEquipmentDefinition.fractionLost # eqp-type-specific
    load_w = equip.getDesignLevel(space.floorArea, ppl_total) * (1 - load_lost)

    if equip.isScheduleDefaulted
      # Check default schedule set
      unless space.spaceType.get.defaultScheduleSet.empty?
        unless space.spaceType.get.defaultScheduleSet.get.electricEquipmentSchedule.empty? # eqp-type-specific
          load_sch = space.spaceType.get.defaultScheduleSet.get.electricEquipmentSchedule # eqp-type-specific
        end
      end
    end
  when 'gas equipment'
    load_sch = equip.schedule
    load_lost = equip.gasEquipmentDefinition.fractionLost # eqp-type-specific
    load_w = equip.getDesignLevel(space.floorArea, ppl_total) * (1 - load_lost)

    if equip.isScheduleDefaulted
      # Check default schedule set
      unless space.spaceType.get.defaultScheduleSet.empty?
        unless space.spaceType.get.defaultScheduleSet.get.gasEquipmentSchedule.empty? # eqp-type-specific
          load_sch = space.spaceType.get.defaultScheduleSet.get.gasEquipmentSchedule # eqp-type-specific
        end
      end
    end
  when 'steam equipment'
    load_sch = equip.schedule
    load_lost = equip.steamEquipmentDefinition.fractionLost # eqp-type-specific
    load_w = equip.getDesignLevel(space.floorArea, ppl_total) * (1 - load_lost)

    if equip.isScheduleDefaulted
      # Check default schedule set
      unless space.spaceType.get.defaultScheduleSet.empty?
        unless space.spaceType.get.defaultScheduleSet.get.steamEquipmentSchedule.empty? # eqp-type-specific
          load_sch = space.spaceType.get.defaultScheduleSet.get.steamEquipmentSchedule # eqp-type-specific
        end
      end
    end
  when 'hot water equipment'
    load_sch = equip.schedule
    load_lost = equip.hotWaterEquipmentDefinition.fractionLost # eqp-type-specific
    load_w = equip.getDesignLevel(space.floorArea, ppl_total) * (1 - load_lost)

    if equip.isScheduleDefaulted
      # Check default schedule set
      unless space.spaceType.get.defaultScheduleSet.empty?
        unless space.spaceType.get.defaultScheduleSet.get.hotWaterEquipmentSchedule.empty? # eqp-type-specific
          load_sch = space.spaceType.get.defaultScheduleSet.get.hotWaterEquipmentSchedule # eqp-type-specific
        end
      end
    end
  when 'other equipment'
    load_sch = equip.schedule
    load_lost = equip.otherEquipmentDefinition.fractionLost # eqp-type-specific
    load_w = equip.getDesignLevel(space.floorArea, ppl_total) * (1 - load_lost)

    if equip.isScheduleDefaulted
      # Check default schedule set
      unless space.spaceType.get.defaultScheduleSet.empty?
        unless space.spaceType.get.defaultScheduleSet.get.otherEquipmentSchedule.empty? # eqp-type-specific
          load_sch = space.spaceType.get.defaultScheduleSet.get.otherEquipmentSchedule # eqp-type-specific
        end
      end
    end
  end

  load_sch_ruleset = nil
  if load_sch.is_initialized
    load_sch_obj = load_sch.get
    load_sch_values = OpenstudioStandards::Schedules.schedule_get_hourly_values(load_sch_obj)
    if !load_sch_values.nil?
      load_sch_max = load_sch_values.max
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Failed to retreive schedule for equipment type #{eqp_type} in space #{space.name}.  Assuming #{load_w} W.")
    end
  end

  if return_noncoincident_value
    load_values[0] += load_w * load_sch_values.max
  else
    if !load_sch_values.nil?
      load_sch_value = 1.0
      (0..8759).each do |ihr|
        load_sch_value = load_sch_values[ihr]
        load_values[ihr] += load_w * load_sch_value
      end
    end
  end
  return load_values
end
space_get_loads_for_all_equips(model, space, equips, eqp_type, ppl_total, load_values, return_noncoincident_value) click to toggle source

Loops through a set of equipment objects of one type For each applicable equipment object, call method to get annual gain values This is useful for the Appendix G test for multizone systems to determine whether specific zones should be isolated to PSZ based on space loads that differ significantly from other zones on the multizone system

@param model [OpenStudio::Model::Model] OpenStudio model object @param space [OpenStudio::Model::Space] the space @param equips [object] This is an array of equipment objects in the model @param eqp_type [String] string description of the type of equipment object @param ppl_total [Numeric] total number of people in the space @param load_values [Array] 8760 array of load values for the equipment type @param return_noncoincident_value [Boolean] return a single peak value if true; return 8760 gain profile if false @return [Array] load values array; if return_noncoincident_value is true, array has only one value

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1748
def space_get_loads_for_all_equips(model, space, equips, eqp_type, ppl_total, load_values, return_noncoincident_value)
  space_name = space.name.get
  space_type_name = space.spaceType.get.name.get
  equips.sort.each do |equip|
    parent_obj = equip.parent.get.iddObjectType.valueName.to_s
    if parent_obj == 'OS_Space'
      # This object is associated with a single space
      # Check if it is the current space
      if space_name == equip.space.get.name.get
        euip_name = equip.name.get
        load_values = space_get_equip_annual_array(model, space, equip, eqp_type, ppl_total, load_values, return_noncoincident_value)
      end
    elsif parent_obj == 'OS_SpaceType'
      # This object is associated with a space type
      # Check if it is the current space type
      if space_type_name == equip.spaceType.get.name.get
        load_values = space_get_equip_annual_array(model, space, equip, eqp_type, ppl_total, load_values, return_noncoincident_value)
      end
    end
  end
  return load_values
end
space_infiltration_rate_75_pa(space = nil) click to toggle source

Baseline infiltration rate

@param space [OpenStudio::Model::Space] space object @return [Double] the baseline infiltration rate, in cfm/ft^2 exterior above grade wall area at 75 Pa

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1345
def space_infiltration_rate_75_pa(space = nil)
  basic_infil_rate_cfm_per_ft2 = 1.8
  return basic_infil_rate_cfm_per_ft2
end
space_internal_load_annual_array(model, space, return_noncoincident_value) click to toggle source

Determine the design internal gain (W) for this space without space multipliers. This includes People, Lights, Electric Equipment, and Gas Equipment. This version accounts for operating schedules and fraction lost for equipment @author Doug Maddox, PNNL @param space object @param return_noncoincident_value [Boolean] if true, return value is noncoincident peak; if false, return is array off coincident load @return [Double] 8760 array of the design internal load, in W, for this space

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1526
def space_internal_load_annual_array(model, space, return_noncoincident_value)
  # For each type of load, first convert schedules to 8760 arrays so coincident load can be determined
  ppl_values = Array.new(8760, 0)
  ltg_values = Array.new(8760, 0)
  load_values = Array.new(8760, 0)
  noncoincident_peak_load = 0
  space_name = space.name.get
  space_type_name = space.spaceType.get.name.get

  # People
  # Make list of people objects for this space
  # Including those associated with space directly and those associated with space type
  ppl_total = 0
  people_objs = []
  model.getPeoples.sort.each do |people|
    parent_obj = people.parent.get.iddObjectType.valueName.to_s
    if parent_obj == 'OS_Space'
      # This object is associated with a single space
      # Check if it is the current space
      if space_name == people.space.get.name.get
        people_objs << people
      end
    elsif parent_obj == 'OS_SpaceType'
      # This object is associated with a space type
      # Check if it is the current space type
      if space_type_name == people.spaceType.get.name.get
        people_objs << people
      end
    end
  end

  people_objs.each do |people|
    w_per_person = 125 # Initial assumption
    occ_sch_max = 1
    act_sch = people.activityLevelSchedule
    if people.isActivityLevelScheduleDefaulted
      # Check default schedule set
      unless space.spaceType.get.defaultScheduleSet.empty?
        unless space.spaceType.get.defaultScheduleSet.get.peopleActivityLevelSchedule.empty?
          act_sch = space.spaceType.get.defaultScheduleSet.get.peopleActivityLevelSchedule
        end
      end
    end
    if act_sch.is_initialized
      act_sch_obj = act_sch.get
      act_sch_values = OpenstudioStandards::Schedules.schedule_get_hourly_values(act_sch_obj)
      if !act_sch_values.nil?
        w_per_person = act_sch_values.max
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Failed to retrieve people activity schedule for #{space.name}.  Assuming #{w_per_person}W/person.")
      end
    end

    occ_sch_ruleset = nil
    occ_sch = people.numberofPeopleSchedule
    if people.isNumberofPeopleScheduleDefaulted
      # Check default schedule set
      unless space.spaceType.get.defaultScheduleSet.empty?
        unless space.spaceType.get.defaultScheduleSet.get.numberofPeopleSchedule.empty?
          occ_sch = space.spaceType.get.defaultScheduleSet.get.numberofPeopleSchedule
        end
      end
    end
    if occ_sch.is_initialized
      occ_sch_obj = occ_sch.get
      occ_sch_values = OpenstudioStandards::Schedules.schedule_get_hourly_values(occ_sch_obj)
      if !occ_sch_max.nil?
        occ_sch_max = occ_sch_values.max
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Failed to retrieve people schedule for #{space.name}.  Assuming #{w_per_person}W/person.")
      end
    end

    num_ppl = people.getNumberOfPeople(space.floorArea)
    ppl_total += num_ppl

    act_sch_value = w_per_person
    occ_sch_value = occ_sch_max
    (0..8759).each do |ihr|
      act_sch_value = act_sch_values[ihr] unless act_sch_values.nil?
      occ_sch_value = occ_sch_values[ihr] unless occ_sch_values.nil?
      ppl_values[ihr] += num_ppl * act_sch_value * occ_sch_value
    end
  end

  # Make list of lights objects for this space
  # Including those associated with space directly and those associated with space type
  # Note: in EnergyPlus, Lights are associated with zone or zonelist
  # In OS, they are associated with space or space type
  light_objs = []
  model.getLightss.sort.each do |light|
    parent_obj = light.parent.get.iddObjectType.valueName.to_s
    if parent_obj == 'OS_Space'
      # This object is associated with a single space
      # Check if it is the current space
      if space_name == light.space.get.name.get
        light_objs << light
      end
    elsif parent_obj == 'OS_SpaceType'
      # This object is associated with a space type
      # Check if it is the current space type
      if space_type_name == light.spaceType.get.name.get
        light_objs << light
      end
    end
  end

  light_objs.each do |light|
    ltg_sch_ruleset = nil
    ltg_sch = light.schedule
    ltg_w = light.getLightingPower(space.floorArea, ppl_total)

    if light.isScheduleDefaulted
      # Check default schedule set
      unless space.spaceType.get.defaultScheduleSet.empty?
        unless space.spaceType.get.defaultScheduleSet.get.lightingSchedule.empty?
          ltg_sch = space.spaceType.get.defaultScheduleSet.get.lightingSchedule
        end
      end
    end
    if ltg_sch.is_initialized
      ltg_sch_obj = ltg_sch.get
      ltg_sch_values = OpenstudioStandards::Schedules.schedule_get_hourly_values(ltg_sch_obj)
      if !ltg_sch_values.nil?
        ltg_sch_max = ltg_sch_values.max
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Failed to retreive lighting schedule for #{space.name}.  Assuming #{ltg_w} W.")
      end
    end

    if !ltg_sch_values.nil?
      ltg_sch_value = 1.0
      (0..8759).each do |ihr|
        ltg_sch_value = ltg_sch_values[ihr] unless ltg_sch_ruleset.nil?
        ltg_values[ihr] += ltg_w * ltg_sch_value
      end
    end
  end

  # Luminaire Objects
  space.spaceType.get.luminaires.each do |light|
    ltg_sch_values = nil
    ltg_sch = light.schedule
    ltg_w = light.lightingPower(space.floorArea, ppl_total)
    # not sure if above line is valid, so calculate from parts instead until above can be verified
    ltg_w = light.getPowerPerFloorArea(space.floorArea) * space.floorArea
    ltg_w += light.getPowerPerPerson(ppl_total) * ppl_total

    if light.isScheduleDefaulted
      # Check default schedule set
      unless space.spaceType.get.defaultScheduleSet.empty?
        unless space.spaceType.get.defaultScheduleSet.get.lightingSchedule.empty?
          ltg_sch = space.spaceType.get.defaultScheduleSet.get.lightingSchedule
        end
      end
    end
    if ltg_sch.is_initialized
      ltg_sch_obj = ltg_sch.get
      ltg_sch_values = OpenstudioStandards::Schedules.schedule_get_hourly_values(ltg_sch_obj)
      if !ltg_sch_values.nil?
        ltg_sch_max = ltg_sch_values.max
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Failed to retreive lighting schedule for luminaires for #{space.name}.  Assuming #{ltg_w} W.")
      end
    end

    if !ltg_sch_values.nil?
      ltg_sch_value = 1.0
      (0..8759).each do |ihr|
        ltg_sch_value = ltg_sch_values[ihr] unless ltg_sch_ruleset.nil?
        ltg_values[ihr] += ltg_w * ltg_sch_value
      end
    end
  end

  # Equipment Loads
  eqp_type = 'electric equipment'
  equips = model.getElectricEquipments
  load_values = space_get_loads_for_all_equips(model, space, equips, eqp_type, ppl_total, load_values, return_noncoincident_value)

  eqp_type = 'gas equipment'
  equips = model.getGasEquipments
  load_values = space_get_loads_for_all_equips(model, space, equips, eqp_type, ppl_total, load_values, return_noncoincident_value)

  eqp_type = 'steam equipment'
  equips = model.getSteamEquipments
  load_values = space_get_loads_for_all_equips(model, space, equips, eqp_type, ppl_total, load_values, return_noncoincident_value)

  eqp_type = 'hot water equipment'
  equips = model.getHotWaterEquipments
  load_values = space_get_loads_for_all_equips(model, space, equips, eqp_type, ppl_total, load_values, return_noncoincident_value)

  eqp_type = 'other equipment'
  equips = model.getOtherEquipments
  load_values = space_get_loads_for_all_equips(model, space, equips, eqp_type, ppl_total, load_values, return_noncoincident_value)

  # Add lighting and people to the load values array
  if return_noncoincident_value
    noncoincident_peak_load = load_values[0] + ppl_values.max + ltg_values.max
    return noncoincident_peak_load
  else
    (0..8759).each do |ihr|
      load_values[ihr] += ppl_values[ihr] + ltg_values[ihr]
    end
    return load_values
  end
end
space_occupancy_annual_array(model, space) click to toggle source

Create annual array of occupancy for the space: 1 = occupied, 0 = unoccupied @author Doug Maddox, PNNL @param space object @return [Double] 8760 array of the occupancy flag

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1472
def space_occupancy_annual_array(model, space)
  occ_sch_values = nil
  ppl_values = Array.new(8760, 0)

  # Need to review all people objects in this space
  space_name = space.name.get
  space_type_name = space.spaceType.get.name.get
  people_objs = []
  model.getPeoples.sort.each do |people|
    parent_obj = people.parent.get.iddObjectType.valueName.to_s
    if parent_obj == 'OS_Space'
      # This object is associated with a single space
      # Check if it is the current space
      if space_name == people.space.get.name.get
        people_objs << people
      end
    elsif parent_obj == 'OS_SpaceType'
      # This object is associated with a space type
      # Check if it is the current space type
      if space_type_name == people.spaceType.get.name.get
        people_objs << people
      end
    end
  end

  unoccupied_threshold = air_loop_hvac_unoccupied_threshold
  people_objs.each do |people|
    occ_sch = people.numberofPeopleSchedule
    if occ_sch.is_initialized
      occ_sch_obj = occ_sch.get
      occ_sch_values = OpenstudioStandards::Schedules.schedule_get_hourly_values(occ_sch_obj)
      # Flag = 1 if any schedule shows occupancy for a given hour
      if !occ_sch_values.nil?
        (0..8759).each do |ihr|
          ppl_values[ihr] = 1 if occ_sch_values[ihr] >= unoccupied_threshold
        end
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Failed to retrieve people schedule for #{space.name}.  Assuming #{w_per_person}W/person.")
      end
    end
  end

  return ppl_values
end
space_remove_daylighting_controls(space) click to toggle source

Removes daylighting controls from model

@param space [OpenStudio::Model::Space] OpenStudio space object

@return [Boolean] Returns true if a sizing run is required

# File lib/openstudio-standards/standards/Standards.Space.rb, line 794
def space_remove_daylighting_controls(space)
  # Retrieves daylighting control objects
  existing_daylighting_controls = space.daylightingControls
  unless existing_daylighting_controls.empty?
    existing_daylighting_controls.each(&:remove)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "For #{space.name}, removed #{existing_daylighting_controls.size} existing daylight controls before adding new controls.")
    return true
  end
  return false
end
space_set_baseline_daylighting_controls(space, remove_existing = false, draw_areas_for_debug = false) click to toggle source

Default for 2013 and earlier is to Add daylighting controls (sidelighting and toplighting) per the template @param space [OpenStudio::Model::Space] the space with daylighting @param remove_existing [Boolean] if true, will remove existing controls then add new ones @param draw_areas_for_debug [Boolean] If this argument is set to true, @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Space.rb, line 810
def space_set_baseline_daylighting_controls(space, remove_existing = false, draw_areas_for_debug = false)
  added = space_add_daylighting_controls(space, remove_existing, draw_areas_for_debug)
  return added
end
space_sidelighting_effective_aperture(space, primary_sidelighted_area) click to toggle source

Returns the sidelighting effective aperture space_sidelighting_effective_aperture(space) = E(window area * window VT) / primary_sidelighted_area

@param space [OpenStudio::Model::Space] space object @param primary_sidelighted_area [Double] the primary sidelighted area (m^2) of the space @return [Double] the unitless sidelighting effective aperture metric

# File lib/openstudio-standards/standards/Standards.Space.rb, line 564
def space_sidelighting_effective_aperture(space, primary_sidelighted_area)
  # space_sidelighting_effective_aperture(space)  = E(window area * window VT) / primary_sidelighted_area
  sidelighting_effective_aperture = 9999

  num_sub_surfaces = 0

  # Loop through all windows and add up area * VT
  sum_window_area_times_vt = 0
  construction_name_to_vt_map = {}
  space.surfaces.sort.each do |surface|
    next unless surface.outsideBoundaryCondition == 'Outdoors' && surface.surfaceType == 'Wall'

    surface.subSurfaces.sort.each do |sub_surface|
      next unless sub_surface.outsideBoundaryCondition == 'Outdoors' && (sub_surface.subSurfaceType == 'FixedWindow' || sub_surface.subSurfaceType == 'OperableWindow' || sub_surface.subSurfaceType == 'GlassDoor')

      num_sub_surfaces += 1

      # Get the area
      area_m2 = sub_surface.netArea

      # Get the window construction name
      construction_name = nil
      construction = sub_surface.construction
      if construction.is_initialized
        construction = construction.get
        construction_name = construction.name.get.upcase
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "For #{space.name}, could not determine construction for #{sub_surface.name}, will not be included in space_sidelighting_effective_aperture(space) calculation.")
        next
      end

      # Store VT for this construction in map if not already looked up
      if construction_name_to_vt_map[construction_name].nil?

        # Get the VT from construction (Simple Glazing) if available
        if construction.visibleTransmittance.is_initialized
          construction_name_to_vt_map[construction_name] = construction.visibleTransmittance.get
        else
          # get the VT from the sql file
          sql = space.model.sqlFile
          if sql.is_initialized
            sql = sql.get

            row_query = "SELECT RowName
                        FROM tabulardatawithstrings
                        WHERE ReportName='EnvelopeSummary'
                        AND ReportForString='Entire Facility'
                        AND TableName='Exterior Fenestration'
                        AND Value='#{construction_name.upcase}'"

            row_id = sql.execAndReturnFirstString(row_query)

            if row_id.is_initialized
              row_id = row_id.get
            else
              OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "VT row ID not found for construction: #{construction_name}, #{sub_surface.name} will not be included in space_sidelighting_effective_aperture(space) calculation.")
              row_id = 9999
            end

            vt_query = "SELECT Value
                        FROM tabulardatawithstrings
                        WHERE ReportName='EnvelopeSummary'
                        AND ReportForString='Entire Facility'
                        AND TableName='Exterior Fenestration'
                        AND ColumnName='Glass Visible Transmittance'
                        AND RowName='#{row_id}'"

            vt = sql.execAndReturnFirstDouble(vt_query)

            vt = if vt.is_initialized
                   vt.get
                 end

            # Record the VT
            construction_name_to_vt_map[construction_name] = vt
          else
            OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Space', 'Model has no sql file containing results, cannot lookup data.')
          end
        end
      end

      # Get the VT from the map
      vt = construction_name_to_vt_map[construction_name]
      if vt.nil?
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "For #{space.name}, could not determine VLT for #{construction_name}, will not be included in sidelighting effective aperture calculation.")
        vt = 0
      end

      sum_window_area_times_vt += area_m2 * vt
    end
  end

  # Calculate the effective aperture
  if sum_window_area_times_vt.zero?
    sidelighting_effective_aperture = 9999
    if num_sub_surfaces > 0
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "#{space.name} has no windows where VLT could be determined, sidelighting effective aperture will be higher than it should.")
    end
  else
    sidelighting_effective_aperture = sum_window_area_times_vt / primary_sidelighted_area
  end

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name} sidelighting effective aperture = #{sidelighting_effective_aperture.round(4)}.")

  return sidelighting_effective_aperture
end
space_skylight_effective_aperture(space, toplighted_area) click to toggle source

Returns the skylight effective aperture space_skylight_effective_aperture(space) = E(0.85 * skylight area * skylight VT * WF) / toplighted_area

@param space [OpenStudio::Model::Space] space object @param toplighted_area [Double] the toplighted area (m^2) of the space @return [Double] the unitless skylight effective aperture metric

# File lib/openstudio-standards/standards/Standards.Space.rb, line 677
def space_skylight_effective_aperture(space, toplighted_area)
  # space_skylight_effective_aperture(space)  = E(0.85 * skylight area * skylight VT * WF) / toplighted_area
  skylight_effective_aperture = 0.0

  num_sub_surfaces = 0

  # Assume that well factor (WF) is 0.9 (all wells are less than 2 feet deep)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', 'Assuming that all skylight wells are less than 2 feet deep to calculate skylight effective aperture.')
  wf = 0.9

  # Loop through all windows and add up area * VT
  sum_85pct_times_skylight_area_times_vt_times_wf = 0
  construction_name_to_vt_map = {}
  space.surfaces.sort.each do |surface|
    next unless surface.outsideBoundaryCondition == 'Outdoors' && surface.surfaceType == 'RoofCeiling'

    surface.subSurfaces.sort.each do |sub_surface|
      next unless sub_surface.outsideBoundaryCondition == 'Outdoors' && sub_surface.subSurfaceType == 'Skylight'

      num_sub_surfaces += 1

      # Get the area
      area_m2 = sub_surface.netArea

      # Get the window construction name
      construction_name = nil
      construction = sub_surface.construction
      if construction.is_initialized
        construction = construction.get
        construction_name = construction.name.get.upcase
      else
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "For #{space.name}, could not determine construction for #{sub_surface.name}, will not be included in space_skylight_effective_aperture(space) calculation.")
        next
      end

      # Store VT for this construction in map if not already looked up
      if construction_name_to_vt_map[construction_name].nil?

        # Get the VT from construction (Simple Glazing) if available
        if construction.visibleTransmittance.is_initialized
          construction_name_to_vt_map[construction_name] = construction.visibleTransmittance.get
        else
          # get the VT from the sql file
          sql = space.model.sqlFile
          if sql.is_initialized
            sql = sql.get

            row_query = "SELECT RowName
                        FROM tabulardatawithstrings
                        WHERE ReportName='EnvelopeSummary'
                        AND ReportForString='Entire Facility'
                        AND TableName='Exterior Fenestration'
                        AND Value='#{construction_name}'"

            row_id = sql.execAndReturnFirstString(row_query)

            if row_id.is_initialized
              row_id = row_id.get
            else
              OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Data not found for query: #{row_query}")
              next
            end

            vt_query = "SELECT Value
                        FROM tabulardatawithstrings
                        WHERE ReportName='EnvelopeSummary'
                        AND ReportForString='Entire Facility'
                        AND TableName='Exterior Fenestration'
                        AND ColumnName='Glass Visible Transmittance'
                        AND RowName='#{row_id}'"

            vt = sql.execAndReturnFirstDouble(vt_query)

            vt = if vt.is_initialized
                   vt.get
                 end

            # Record the VT
            construction_name_to_vt_map[construction_name] = vt

          else
            OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Space', 'Model has no sql file containing results, cannot lookup data.')
          end
        end
      end

      # Get the VT from the map
      vt = construction_name_to_vt_map[construction_name]
      if vt.nil?
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "For #{space.name}, could not determine VLT for #{construction_name}, will not be included in skylight effective aperture calculation.")
        vt = 0
      end

      sum_85pct_times_skylight_area_times_vt_times_wf += 0.85 * area_m2 * vt * wf
    end
  end

  # Calculate the effective aperture
  if sum_85pct_times_skylight_area_times_vt_times_wf.zero?
    skylight_effective_aperture = 9999
    if num_sub_surfaces > 0
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "#{space.name} has no skylights where VLT could be determined, skylight effective aperture will be higher than it should.")
    end
  else
    skylight_effective_aperture = sum_85pct_times_skylight_area_times_vt_times_wf / toplighted_area
  end

  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "#{space.name} skylight effective aperture = #{skylight_effective_aperture}.")

  return skylight_effective_aperture
end
space_type_apply_int_loads_prm(space_type, model) click to toggle source

Sets the internal loads for Appendix G PRM for 2016 and later Initially, only lighting power density will be set Possibly infiltration will also be set from here

@param space_type [OpenStudio::Model::SpaceType] OpenStudio space type object @param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.SpaceType.rb, line 490
def space_type_apply_int_loads_prm(space_type, model)
  # Skip plenums
  # Check if the space type name
  # contains the word plenum.
  if space_type.name.get.to_s.downcase.include?('plenum')
    return false
  end

  if space_type.standardsSpaceType.is_initialized
    if space_type.standardsSpaceType.get.downcase.include?('plenum')
      return false
    end
  end

  # Get the standards data
  space_type_properties = interior_lighting_get_prm_data(space_type)

  # Need to add a check, or it'll crash on space_type_properties['occupancy_per_area'].to_f below
  if space_type_properties.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} was not found in the standards data.")
    return false
  end

  # Lights
  lights_have_info = false
  lighting_per_area = space_type_properties['w/ft^2'].to_f
  lighting_per_length = space_type_properties['w/ft'].to_f
  lights_have_info = true unless lighting_per_area.zero? && lighting_per_length.zero?
  multiple_lpd_value_check = false

  if lighting_per_length > 0
    if space_type.spaces.size == 1
      # Space height
      space = space_type.spaces[0]
      space_volume = space.volume
      space_area = space.floorArea
      space_height = space_volume / space_area
      # New lpd value
      lighting_per_area += lighting_per_length * space_height
    else
      lighting_per_area_hash = {}
      multiple_lpd_value_check = true
      space_type.spaces.each do |space_type_space|
        # Space height
        space_volume = space_type_space.volume
        space_area = space_type_space.floorArea
        space_height = space_volume / space_area
        # New lpd values
        lighting_per_area_new = lighting_per_area + lighting_per_length * space_height
        lighting_per_area_hash[space_type_space.name.to_s] = lighting_per_area_new
      end
    end
  end

  if lights_have_info
    # Remove all but the first instance
    instances = space_type.lights.sort
    if instances.size.zero?
      definition = OpenStudio::Model::LightsDefinition.new(space_type.model)
      definition.setName("#{space_type.name} Lights Definition")
      instance = OpenStudio::Model::Lights.new(definition)
      instance.setName("#{space_type.name} Lights")
      instance.setSpaceType(space_type)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} had no lights, one has been created.")
      instances << instance
    elsif instances.size > 1
      instances.each_with_index do |inst, i|
        next if i.zero?

        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "Removed #{inst.name} from #{space_type.name}.")
        inst.remove
      end
    end
    # Modify the definition of the instance
    if multiple_lpd_value_check == false
      space_type.lights.sort.each do |inst|
        definition = inst.lightsDefinition
        unless lighting_per_area.zero?
          occ_sens_lpd_factor = 1.0
          definition.setWattsperSpaceFloorArea(OpenStudio.convert(lighting_per_area.to_f * occ_sens_lpd_factor, 'W/ft^2', 'W/m^2').get)
          OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set LPD to #{lighting_per_area} W/ft^2.")
        end
      end
    else
      space_type.spaces.each do |space_type_space|
        new_space_type = space_type.clone.to_SpaceType.get
        space_type_space.setSpaceType(new_space_type)
        lighting_per_area = lighting_per_area_hash[space_type_space.name.to_s]
        new_space_type.lights.sort.each do |inst|
          definition = inst.lightsDefinition
          unless lighting_per_area.zero?
            occ_sens_lpd_factor = 1.0
            definition.setWattsperSpaceFloorArea(OpenStudio.convert(lighting_per_area.to_f * occ_sens_lpd_factor, 'W/ft^2', 'W/m^2').get)
            OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set LPD to #{lighting_per_area} W/ft^2.")
          end
        end
      end
      space_type.remove
    end
  end
  return true
end
space_type_apply_internal_load_schedules(space_type, set_people, set_lights, set_electric_equipment, set_gas_equipment, set_ventilation, set_infiltration, make_thermostat) click to toggle source

Sets the schedules for the selected internal loads to typical schedules. Get the default schedule set for this space type if one exists or make one if none exists. For each category that is selected, add the typical schedule for this category to the default schedule set. This method does not alter any schedules of any internal loads that does not inherit from the default schedule set.

@param space_type [OpenStudio::Model::SpaceType] space type object @param set_people [Boolean] if true, set the occupancy and activity schedules @param set_lights [Boolean] if true, set the lighting schedule @param set_electric_equipment [Boolean] if true, set the electric schedule schedule @param set_gas_equipment [Boolean] if true, set the gas equipment density @param set_infiltration [Boolean] if true, set the infiltration schedule @param make_thermostat [Boolean] if true, makes a thermostat for this space type from the

schedules listed for the space type.  This thermostat is not hooked to any zone by this method,
but may be found and used later.

@return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.SpaceType.rb, line 618
def space_type_apply_internal_load_schedules(space_type, set_people, set_lights, set_electric_equipment, set_gas_equipment, set_ventilation, set_infiltration, make_thermostat)
  # Get the standards data
  space_type_properties = space_type_get_standards_data(space_type)

  # Get the default schedule set
  # or create a new one if none exists.
  default_sch_set = nil
  if space_type.defaultScheduleSet.is_initialized
    default_sch_set = space_type.defaultScheduleSet.get
  else
    default_sch_set = OpenStudio::Model::DefaultScheduleSet.new(space_type.model)
    default_sch_set.setName("#{space_type.name} Schedule Set")
    space_type.setDefaultScheduleSet(default_sch_set)
  end

  # People
  if set_people
    occupancy_sch = space_type_properties['occupancy_schedule']
    unless occupancy_sch.nil?
      default_sch_set.setNumberofPeopleSchedule(model_add_schedule(space_type.model, occupancy_sch))
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set occupancy schedule to #{occupancy_sch}.")
    end

    occupancy_activity_sch = space_type_properties['occupancy_activity_schedule']
    unless occupancy_activity_sch.nil?
      default_sch_set.setPeopleActivityLevelSchedule(model_add_schedule(space_type.model, occupancy_activity_sch))
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set occupant activity schedule to #{occupancy_activity_sch}.")
    end

  end

  # Lights
  if set_lights

    apply_lighting_schedule(space_type, space_type_properties, default_sch_set)

  end

  # Electric Equipment
  if set_electric_equipment
    elec_equip_sch = space_type_properties['electric_equipment_schedule']
    unless elec_equip_sch.nil?
      default_sch_set.setElectricEquipmentSchedule(model_add_schedule(space_type.model, elec_equip_sch))
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set electric equipment schedule to #{elec_equip_sch}.")
    end
  end

  # Gas Equipment
  if set_gas_equipment
    gas_equip_sch = space_type_properties['gas_equipment_schedule']
    unless gas_equip_sch.nil?
      default_sch_set.setGasEquipmentSchedule(model_add_schedule(space_type.model, gas_equip_sch))
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set gas equipment schedule to #{gas_equip_sch}.")
    end
  end

  # Infiltration
  if set_infiltration
    infiltration_sch = space_type_properties['infiltration_schedule']
    unless infiltration_sch.nil?
      default_sch_set.setInfiltrationSchedule(model_add_schedule(space_type.model, infiltration_sch))
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set infiltration schedule to #{infiltration_sch}.")
    end
  end

  # Thermostat
  if make_thermostat
    thermostat = OpenStudio::Model::ThermostatSetpointDualSetpoint.new(space_type.model)
    thermostat.setName("#{space_type.name} Thermostat")

    heating_setpoint_sch = space_type_properties['heating_setpoint_schedule']
    unless heating_setpoint_sch.nil?
      thermostat.setHeatingSetpointTemperatureSchedule(model_add_schedule(space_type.model, heating_setpoint_sch))
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set heating setpoint schedule to #{heating_setpoint_sch}.")
    end

    cooling_setpoint_sch = space_type_properties['cooling_setpoint_schedule']
    unless cooling_setpoint_sch.nil?
      thermostat.setCoolingSetpointTemperatureSchedule(model_add_schedule(space_type.model, cooling_setpoint_sch))
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set cooling setpoint schedule to #{cooling_setpoint_sch}.")
    end
  end

  return true
end
space_type_apply_internal_loads(space_type, set_people, set_lights, set_electric_equipment, set_gas_equipment, set_ventilation, set_infiltration) click to toggle source

Sets the selected internal loads to standards-based or typical values. For each category that is selected get all load instances. Remove all but the first instance if multiple instances. Add a new instance/definition if no instance exists. Modify the definition for the remaining instance to have the specified values. This method does not alter any loads directly assigned to spaces. This method skips plenums.

@param space_type [OpenStudio::Model::SpaceType] space type object @param set_people [Boolean] if true, set the people density.

Also, assign reasonable clothing, air velocity, and work efficiency inputs
to allow reasonable thermal comfort metrics to be calculated.

@param set_lights [Boolean] if true, set the lighting density, lighting fraction

to return air, fraction radiant, and fraction visible.

@param set_electric_equipment [Boolean] if true, set the electric equipment density @param set_gas_equipment [Boolean] if true, set the gas equipment density @param set_ventilation [Boolean] if true, set the ventilation rates (per-person and per-area) @param set_infiltration [Boolean] if true, set the infiltration rates @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.SpaceType.rb, line 110
def space_type_apply_internal_loads(space_type, set_people, set_lights, set_electric_equipment, set_gas_equipment, set_ventilation, set_infiltration)
  # Skip plenums
  # Check if the space type name
  # contains the word plenum.
  if space_type.name.get.to_s.downcase.include?('plenum')
    return false
  end

  if space_type.standardsSpaceType.is_initialized
    if space_type.standardsSpaceType.get.downcase.include?('plenum')
      return false
    end
  end

  # Get the standards data
  space_type_properties = space_type_get_standards_data(space_type)

  # Need to add a check, or it'll crash on space_type_properties['occupancy_per_area'].to_f below
  if space_type_properties.nil? || space_type_properties.empty?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} was not found in the standards data.")
    return false
  end
  # People
  people_have_info = false
  occupancy_per_area = space_type_properties['occupancy_per_area'].to_f
  people_have_info = true unless occupancy_per_area.zero?

  if set_people && people_have_info

    # Remove all but the first instance
    instances = space_type.people.sort
    if instances.size.zero?
      # Create a new definition and instance
      definition = OpenStudio::Model::PeopleDefinition.new(space_type.model)
      definition.setName("#{space_type.name} People Definition")
      instance = OpenStudio::Model::People.new(definition)
      instance.setName("#{space_type.name} People")
      instance.setSpaceType(space_type)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} had no people, one has been created.")
      instances << instance
    elsif instances.size > 1
      instances.each_with_index do |inst, i|
        next if i.zero?

        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "Removed #{inst.name} from #{space_type.name}.")
        inst.remove
      end
    end

    # Modify the definition of the instance
    space_type.people.sort.each do |inst|
      definition = inst.peopleDefinition
      unless occupancy_per_area.zero?
        definition.setPeopleperSpaceFloorArea(OpenStudio.convert(occupancy_per_area / 1000, 'people/ft^2', 'people/m^2').get)
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set occupancy to #{occupancy_per_area} people/1000 ft^2.")
      end

      # set fraction radiant  ##
      definition.setFractionRadiant(0.3)

      # Clothing schedule for thermal comfort metrics
      clothing_sch = space_type.model.getScheduleRulesetByName('Clothing Schedule')
      if clothing_sch.is_initialized
        clothing_sch = clothing_sch.get
      else
        clothing_sch = OpenStudio::Model::ScheduleRuleset.new(space_type.model)
        clothing_sch.setName('Clothing Schedule')
        clothing_sch.defaultDaySchedule.setName('Clothing Schedule Default Winter Clothes')
        clothing_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 1.0)
        sch_rule = OpenStudio::Model::ScheduleRule.new(clothing_sch)
        sch_rule.daySchedule.setName('Clothing Schedule Summer Clothes')
        sch_rule.daySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0.5)
        sch_rule.setStartDate(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(5), 1))
        sch_rule.setEndDate(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(9), 30))
      end
      inst.setClothingInsulationSchedule(clothing_sch)

      # Air velocity schedule for thermal comfort metrics
      air_velo_sch = space_type.model.getScheduleRulesetByName('Air Velocity Schedule')
      if air_velo_sch.is_initialized
        air_velo_sch = air_velo_sch.get
      else
        air_velo_sch = OpenStudio::Model::ScheduleRuleset.new(space_type.model)
        air_velo_sch.setName('Air Velocity Schedule')
        air_velo_sch.defaultDaySchedule.setName('Air Velocity Schedule Default')
        air_velo_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0.2)
      end
      inst.setAirVelocitySchedule(air_velo_sch)

      # Work efficiency schedule for thermal comfort metrics
      work_efficiency_sch = space_type.model.getScheduleRulesetByName('Work Efficiency Schedule')
      if work_efficiency_sch.is_initialized
        work_efficiency_sch = work_efficiency_sch.get
      else
        work_efficiency_sch = OpenStudio::Model::ScheduleRuleset.new(space_type.model)
        work_efficiency_sch.setName('Work Efficiency Schedule')
        work_efficiency_sch.defaultDaySchedule.setName('Work Efficiency Schedule Default')
        work_efficiency_sch.defaultDaySchedule.addValue(OpenStudio::Time.new(0, 24, 0, 0), 0)
      end
      inst.setWorkEfficiencySchedule(work_efficiency_sch)
    end

  end

  # Lights
  lights_have_info = false
  lighting_per_area = space_type_properties['lighting_per_area'].to_f
  lighting_per_person = space_type_properties['lighting_per_person'].to_f
  lights_frac_to_return_air = space_type_properties['lighting_fraction_to_return_air']
  lights_frac_radiant = space_type_properties['lighting_fraction_radiant']
  lights_frac_visible = space_type_properties['lighting_fraction_visible']
  lights_frac_replaceable = space_type_properties['lighting_fraction_replaceable'].to_f
  lights_frac_linear_fluorescent = space_type_properties['lpd_fraction_linear_fluorescent']
  lights_frac_compact_fluorescent = space_type_properties['lpd_fraction_compact_fluorescent']
  lights_frac_high_bay = space_type_properties['lpd_fraction_high_bay']
  lights_frac_specialty_lighting = space_type_properties['lpd_fraction_specialty_lighting']
  lights_frac_exit_lighting = space_type_properties['lpd_fraction_exit_lighting']
  lights_have_info = true unless lighting_per_area.zero? && lighting_per_person.zero?

  if set_lights && lights_have_info

    # Remove all but the first instance
    instances = space_type.lights.sort
    if instances.size.zero?
      definition = OpenStudio::Model::LightsDefinition.new(space_type.model)
      definition.setName("#{space_type.name} Lights Definition")
      instance = OpenStudio::Model::Lights.new(definition)
      instance.setName("#{space_type.name} Lights")
      instance.setSpaceType(space_type)
      instance.setFractionReplaceable(lights_frac_replaceable)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} had no lights, one has been created.")
      instances << instance
    elsif instances.size > 1
      instances.each_with_index do |inst, i|
        next if i.zero?

        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "Removed #{inst.name} from #{space_type.name}.")
        inst.remove
      end
    end

    # Modify the definition of the instance
    space_type.lights.sort.each do |inst|
      inst.setFractionReplaceable(lights_frac_replaceable)
      definition = inst.lightsDefinition
      unless lighting_per_area.zero?
        occ_sens_lpd_factor = 1.0
        definition.setWattsperSpaceFloorArea(OpenStudio.convert(lighting_per_area.to_f * occ_sens_lpd_factor, 'W/ft^2', 'W/m^2').get)
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set LPD to #{lighting_per_area} W/ft^2.")
      end
      unless lighting_per_person.zero?
        definition.setWattsperPerson(OpenStudio.convert(lighting_per_person.to_f, 'W/person', 'W/person').get)
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set lighting to #{lighting_per_person} W/person.")
      end
      definition.setReturnAirFraction(lights_frac_to_return_air.to_f) if lights_frac_to_return_air
      definition.setFractionRadiant(lights_frac_radiant.to_f) if lights_frac_radiant
      definition.setFractionVisible(lights_frac_visible.to_f) if lights_frac_visible
      # definition.setFractionReplaceable(lights_frac_replaceable) if lights_frac_replaceable
      definition.additionalProperties.setFeature('lpd_fraction_linear_fluorescent', lights_frac_linear_fluorescent.to_f) if lights_frac_linear_fluorescent
      definition.additionalProperties.setFeature('lpd_fraction_compact_fluorescent', lights_frac_compact_fluorescent.to_f) if lights_frac_compact_fluorescent
      definition.additionalProperties.setFeature('lpd_fraction_high_bay', lights_frac_high_bay.to_f) if lights_frac_high_bay
      definition.additionalProperties.setFeature('lpd_fraction_specialty_lighting', lights_frac_specialty_lighting.to_f) if lights_frac_specialty_lighting
      definition.additionalProperties.setFeature('lpd_fraction_exit_lighting', lights_frac_exit_lighting.to_f) if lights_frac_exit_lighting
    end

    # If additional lights are specified, add those too
    additional_lighting_per_area = space_type_properties['additional_lighting_per_area'].to_f
    unless additional_lighting_per_area.zero?
      # Create the lighting definition
      additional_lights_def = OpenStudio::Model::LightsDefinition.new(space_type.model)
      additional_lights_def.setName("#{space_type.name} Additional Lights Definition")
      additional_lights_def.setWattsperSpaceFloorArea(OpenStudio.convert(additional_lighting_per_area.to_f, 'W/ft^2', 'W/m^2').get)
      additional_lights_def.setReturnAirFraction(lights_frac_to_return_air)
      additional_lights_def.setFractionRadiant(lights_frac_radiant)
      additional_lights_def.setFractionVisible(lights_frac_visible)

      # By default, all additional lighting is specialty lighting
      additional_lights_def.additionalProperties.setFeature('lpd_fraction_linear_fluorescent', 0.0)
      additional_lights_def.additionalProperties.setFeature('lpd_fraction_compact_fluorescent', 0.0)
      additional_lights_def.additionalProperties.setFeature('lpd_fraction_high_bay', 0.0)
      additional_lights_def.additionalProperties.setFeature('lpd_fraction_specialty_lighting', 1.0)
      additional_lights_def.additionalProperties.setFeature('lpd_fraction_exit_lighting', 0.0)

      # Create the lighting instance and hook it up to the space type
      additional_lights = OpenStudio::Model::Lights.new(additional_lights_def)
      additional_lights.setName("#{space_type.name} Additional Lights")
      additional_lights.setSpaceType(space_type)
    end

  end

  # Electric Equipment
  elec_equip_have_info = false
  elec_equip_per_area = space_type_properties['electric_equipment_per_area'].to_f
  elec_equip_frac_latent = space_type_properties['electric_equipment_fraction_latent']
  elec_equip_frac_radiant = space_type_properties['electric_equipment_fraction_radiant']
  elec_equip_frac_lost = space_type_properties['electric_equipment_fraction_lost']
  elec_equip_have_info = true unless elec_equip_per_area.zero?

  if set_electric_equipment && elec_equip_have_info

    # Remove all but the first instance
    instances = space_type.electricEquipment.sort
    if instances.size.zero?
      definition = OpenStudio::Model::ElectricEquipmentDefinition.new(space_type.model)
      definition.setName("#{space_type.name} Elec Equip Definition")
      instance = OpenStudio::Model::ElectricEquipment.new(definition)
      instance.setName("#{space_type.name} Elec Equip")
      instance.setSpaceType(space_type)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} had no electric equipment, one has been created.")
      instances << instance
    elsif instances.size > 1
      instances.each_with_index do |inst, i|
        next if i.zero?

        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "Removed #{inst.name} from #{space_type.name}.")
        inst.remove
      end
    end

    # Modify the definition of the instance
    space_type.electricEquipment.sort.each do |inst|
      definition = inst.electricEquipmentDefinition
      unless elec_equip_per_area.zero?
        definition.setWattsperSpaceFloorArea(OpenStudio.convert(elec_equip_per_area.to_f, 'W/ft^2', 'W/m^2').get)
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set electric EPD to #{elec_equip_per_area} W/ft^2.")
      end
      definition.setFractionLatent(elec_equip_frac_latent.to_f) if elec_equip_frac_latent
      definition.setFractionRadiant(elec_equip_frac_radiant.to_f) if elec_equip_frac_radiant
      definition.setFractionLost(elec_equip_frac_lost.to_f) if elec_equip_frac_lost
    end

  end

  # Gas Equipment
  gas_equip_have_info = false
  gas_equip_per_area = space_type_properties['gas_equipment_per_area'].to_f
  gas_equip_frac_latent = space_type_properties['gas_equipment_fraction_latent']
  gas_equip_frac_radiant = space_type_properties['gas_equipment_fraction_radiant']
  gas_equip_frac_lost = space_type_properties['gas_equipment_fraction_lost']
  gas_equip_have_info = true unless gas_equip_per_area.zero?

  if set_gas_equipment && gas_equip_have_info

    # Remove all but the first instance
    instances = space_type.gasEquipment.sort
    if instances.size.zero?
      definition = OpenStudio::Model::GasEquipmentDefinition.new(space_type.model)
      definition.setName("#{space_type.name} Gas Equip Definition")
      instance = OpenStudio::Model::GasEquipment.new(definition)
      instance.setName("#{space_type.name} Gas Equip")
      instance.setSpaceType(space_type)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} had no gas equipment, one has been created.")
      instances << instance
    elsif instances.size > 1
      instances.each_with_index do |inst, i|
        next if i.zero?

        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "Removed #{inst.name} from #{space_type.name}.")
        inst.remove
      end
    end

    # Modify the definition of the instance
    space_type.gasEquipment.sort.each do |inst|
      definition = inst.gasEquipmentDefinition
      unless gas_equip_per_area.zero?
        definition.setWattsperSpaceFloorArea(OpenStudio.convert(gas_equip_per_area.to_f, 'Btu/hr*ft^2', 'W/m^2').get)
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set gas EPD to #{gas_equip_per_area} Btu/hr*ft^2.")
      end
      definition.setFractionLatent(gas_equip_frac_latent.to_f) if gas_equip_frac_latent
      definition.setFractionRadiant(gas_equip_frac_radiant.to_f) if gas_equip_frac_radiant
      definition.setFractionLost(gas_equip_frac_lost.to_f) if gas_equip_frac_lost
    end

  end

  # Ventilation
  ventilation_have_info = false
  ventilation_per_area = space_type_properties['ventilation_per_area'].to_f
  ventilation_per_person = space_type_properties['ventilation_per_person'].to_f
  ventilation_ach = space_type_properties['ventilation_air_changes'].to_f
  ventilation_have_info = true unless ventilation_per_area.zero?
  ventilation_have_info = true unless ventilation_per_person.zero?
  ventilation_have_info = true unless ventilation_ach.zero?

  # Get the design OA or create a new one if none exists
  ventilation = space_type.designSpecificationOutdoorAir
  if ventilation.is_initialized
    ventilation = ventilation.get
  else
    ventilation = OpenStudio::Model::DesignSpecificationOutdoorAir.new(space_type.model)
    ventilation.setName("#{space_type.name} Ventilation")
    space_type.setDesignSpecificationOutdoorAir(ventilation)
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} had no ventilation specification, one has been created.")
  end

  if set_ventilation && ventilation_have_info

    # Modify the ventilation properties
    ventilation_method = model_ventilation_method(space_type.model)
    ventilation.setOutdoorAirMethod(ventilation_method)
    unless ventilation_per_area.zero?
      ventilation.setOutdoorAirFlowperFloorArea(OpenStudio.convert(ventilation_per_area.to_f, 'ft^3/min*ft^2', 'm^3/s*m^2').get)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set ventilation per area to #{ventilation_per_area} cfm/ft^2.")
    end
    unless ventilation_per_person.zero?
      ventilation.setOutdoorAirFlowperPerson(OpenStudio.convert(ventilation_per_person.to_f, 'ft^3/min*person', 'm^3/s*person').get)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set ventilation per person to #{ventilation_per_person} cfm/person.")
    end
    unless ventilation_ach.zero?
      ventilation.setOutdoorAirFlowAirChangesperHour(ventilation_ach)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set ventilation to #{ventilation_ach} ACH.")
    end

  elsif set_ventilation && !ventilation_have_info

    # All space types must have a design spec OA
    # object for ventilation controls to work correctly,
    # even if the values are all zero.
    ventilation.setOutdoorAirFlowperFloorArea(0)
    ventilation.setOutdoorAirFlowperPerson(0)
    ventilation.setOutdoorAirFlowAirChangesperHour(0)

  end

  # Infiltration
  infiltration_have_info = false
  infiltration_per_area_ext = space_type_properties['infiltration_per_exterior_area'].to_f
  infiltration_per_area_ext_wall = space_type_properties['infiltration_per_exterior_wall_area'].to_f
  infiltration_ach = space_type_properties['infiltration_air_changes'].to_f
  unless infiltration_per_area_ext.zero? && infiltration_per_area_ext_wall.zero? && infiltration_ach.zero?
    infiltration_have_info = true
  end

  if set_infiltration && infiltration_have_info
    # Remove all but the first instance
    instances = space_type.spaceInfiltrationDesignFlowRates.sort
    if instances.size.zero?
      instance = OpenStudio::Model::SpaceInfiltrationDesignFlowRate.new(space_type.model)
      instance.setName("#{space_type.name} Infiltration")
      instance.setSpaceType(space_type)
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} had no infiltration objects, one has been created.")
      instances << instance
    elsif instances.size > 1
      instances.each_with_index do |inst, i|
        next if i.zero?

        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "Removed #{inst.name} from #{space_type.name}.")
        inst.remove
      end
    end

    # Modify each instance
    space_type.spaceInfiltrationDesignFlowRates.sort.each do |inst|
      unless infiltration_per_area_ext.zero?
        inst.setFlowperExteriorSurfaceArea(OpenStudio.convert(infiltration_per_area_ext.to_f, 'ft^3/min*ft^2', 'm^3/s*m^2').get.round(13))
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set infiltration to #{ventilation_ach} per ft^2 exterior surface area.")
      end
      unless infiltration_per_area_ext_wall.zero?
        inst.setFlowperExteriorWallArea(OpenStudio.convert(infiltration_per_area_ext_wall.to_f, 'ft^3/min*ft^2', 'm^3/s*m^2').get)
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set infiltration to #{infiltration_per_area_ext_wall} per ft^2 exterior wall area.")
      end
      unless infiltration_ach.zero?
        inst.setAirChangesperHour(infiltration_ach)
        OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.SpaceType', "#{space_type.name} set infiltration to #{ventilation_ach} ACH.")
      end
    end
  end

  return true
end
space_type_apply_rendering_color(space_type) click to toggle source

Sets the color for the space types as shown in the SketchUp plugin using render by space type.

@param space_type [OpenStudio::Model::SpaceType] space type object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.SpaceType.rb, line 68
def space_type_apply_rendering_color(space_type)
  # Get the standards data
  space_type_properties = space_type_get_standards_data(space_type)

  # Set the rendering color of the space type
  rgb = space_type_properties['rgb']
  if rgb.nil?
    return false
  end

  rgb = rgb.split('_')
  r = rgb[0].to_i
  g = rgb[1].to_i
  b = rgb[2].to_i
  rendering_color = OpenStudio::Model::RenderingColor.new(space_type.model)
  rendering_color.setName(space_type.name.get)
  rendering_color.setRenderingRedValue(r)
  rendering_color.setRenderingGreenValue(g)
  rendering_color.setRenderingBlueValue(b)
  space_type.setRenderingColor(rendering_color)

  return true
end
space_type_get_construction_properties(space_type, intended_surface_type, standards_construction_type) click to toggle source

Returns standards data for selected construction

@param space_type [OpenStudio::Model::SpaceType] space type object @param intended_surface_type [String] the type of surface @param standards_construction_type [String] the type of construction @return [Hash] hash of construction properties

# File lib/openstudio-standards/standards/Standards.SpaceType.rb, line 725
def space_type_get_construction_properties(space_type, intended_surface_type, standards_construction_type)
  # get building_category value
  building_category = if !space_type_get_standards_data(space_type).nil? && space_type_get_standards_data(space_type)['is_residential'] == 'Yes'
                        'Residential'
                      else
                        'Nonresidential'
                      end

  # get climate_zone_set
  climate_zone = model_get_building_properties(space_type.model)['climate_zone']
  climate_zone_set = model_find_climate_zone_set(space_type.model, climate_zone)

  # populate search hash
  search_criteria = {
    'template' => template,
    'climate_zone_set' => climate_zone_set,
    'intended_surface_type' => intended_surface_type,
    'standards_construction_type' => standards_construction_type,
    'building_category' => building_category
  }

  # switch to use this but update test in standards and measures to load this outside of the method
  construction_properties = model_find_object(standards_data['construction_properties'], search_criteria)

  if !construction_properties
    # Search again use climate zone (e.g. 3) instead of sub-climate zone (3A)
    search_criteria['climate_zone_set'] = climate_zone_set[0..-2]
    construction_properties = model_find_object(standards_data['construction_properties'], search_criteria)
  end

  return construction_properties
end
space_type_get_standards_data(space_type) click to toggle source

Returns standards data for selected space type and template

@param space_type [OpenStudio::Model::SpaceType] space type object @return [Hash] hash of internal loads for different load types

# File lib/openstudio-standards/standards/Standards.SpaceType.rb, line 8
def space_type_get_standards_data(space_type)
  standards_building_type = if space_type.standardsBuildingType.is_initialized
                              space_type.standardsBuildingType.get
                            end
  standards_space_type = if space_type.standardsSpaceType.is_initialized
                           space_type.standardsSpaceType.get
                         end

  # populate search hash
  search_criteria = {
    'template' => template,
    'building_type' => standards_building_type,
    'space_type' => standards_space_type
  }

  # lookup space type properties
  space_type_properties = model_find_object(standards_data['space_types'], search_criteria)

  if space_type_properties.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.SpaceType', "Space type properties lookup failed: #{search_criteria}.")
    space_type_properties = {}
  end

  return space_type_properties
end
space_type_light_sch_change(model) click to toggle source

Modify the lighting schedules for Appendix G PRM for 2016 and later

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.SpaceType.rb, line 597
def space_type_light_sch_change(model)
  return true
end
standard_design_sizing_temperatures() click to toggle source

Returns standard design sizing temperatures

@return [Hash] Hash of design sizing temperature lookups

# File lib/openstudio-standards/prototypes/common/objects/Prototype.hvac_systems.rb, line 7
def standard_design_sizing_temperatures
  dsgn_temps = {}
  dsgn_temps['prehtg_dsgn_sup_air_temp_f'] = 45.0
  dsgn_temps['preclg_dsgn_sup_air_temp_f'] = 55.0
  dsgn_temps['htg_dsgn_sup_air_temp_f'] = 55.0
  dsgn_temps['clg_dsgn_sup_air_temp_f'] = 55.0
  dsgn_temps['zn_htg_dsgn_sup_air_temp_f'] = 104.0
  dsgn_temps['zn_clg_dsgn_sup_air_temp_f'] = 55.0
  dsgn_temps['prehtg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['prehtg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['preclg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['preclg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['clg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['clg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['zn_htg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_htg_dsgn_sup_air_temp_f'], 'F', 'C').get
  dsgn_temps['zn_clg_dsgn_sup_air_temp_c'] = OpenStudio.convert(dsgn_temps['zn_clg_dsgn_sup_air_temp_f'], 'F', 'C').get
  return dsgn_temps
end
standards_lookup_table_first(table_name:, search_criteria: {}, capacity: nil, date: nil) click to toggle source

Method to search through a hash for an object that meets the desired search criteria, as passed via a hash. If capacity is supplied, the object will only be returned if the specified capacity is between the minimum_capacity and maximum_capacity values.

@param table_name [String] name of table @param search_criteria [Hash] hash of search criteria @param capacity [Double] capacity of the object in question. If capacity is supplied,

the objects will only be returned if the specified capacity is between the minimum_capacity and maximum_capacity values.

@param date [<OpenStudio::Date>] date of the object in question. If date is supplied,

the objects will only be returned if the specified date is between the start_date and end_date.

@return [Hash] Return tbe first matching object hash if successful, nil if not. @example Find the motor that meets these size criteria

search_criteria = {
'template' => template,
'number_of_poles' => 4.0,
'type' => 'Enclosed',
}
motor_properties = self.model.find_object(motors, search_criteria, 2.5)
# File lib/openstudio-standards/standards/Standards.Model.rb, line 2727
def standards_lookup_table_first(table_name:, search_criteria: {}, capacity: nil, date: nil)
  # run the many version of the look up code...DRY.
  matching_objects = standards_lookup_table_many(table_name: table_name,
                                                 search_criteria: search_criteria,
                                                 capacity: capacity,
                                                 date: date)

  # Check the number of matching objects found
  if matching_objects.size.zero?
    desired_object = nil
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Find object search criteria returned no results. Search criteria: #{search_criteria}. Called from #{caller(0)[1]}")
  elsif matching_objects.size == 1
    desired_object = matching_objects[0]
  else
    desired_object = matching_objects[0]
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Model', "Find object search criteria returned #{matching_objects.size} results, the first one will be returned. Called from #{caller(0)[1]}. \n Search criteria: \n #{search_criteria}, capacity = #{capacity} \n  All results: \n#{matching_objects.join("\n")}")
  end

  return desired_object
end
standards_lookup_table_many(table_name:, search_criteria: {}, capacity: nil, date: nil, area: nil, num_floors: nil) click to toggle source

Method to search through a hash for the objects that meets the desired search criteria, as passed via a hash. Returns an Array (empty if nothing found) of matching objects.

@param table_name [Hash] name of table in standards database. @param search_criteria [Hash] hash of search criteria @param capacity [Double] capacity of the object in question. If capacity is supplied,

the objects will only be returned if the specified capacity is between the minimum_capacity and maximum_capacity values.

@param date [<OpenStudio::Date>] date of the object in question. If date is supplied,

the objects will only be returned if the specified date is between the start_date and end_date.

@param area [Double] area of the object in question. If area is supplied,

the objects will only be returned if the specified area is between the minimum_area and maximum_area values.

@param num_floors [Double] capacity of the object in question. If num_floors is supplied,

the objects will only be returned if the specified num_floors is between the minimum_floors and maximum_floors values.

@return [Array] returns an array of hashes, one hash per object. Array is empty if no results. @example Find all the schedule rules that match the name

rules = model_find_objects(standards_data['schedules'], 'name' => schedule_name)
if rules.size.zero?
  OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Cannot find data for schedule: #{schedule_name}, will not be created.")
  return false
end
# File lib/openstudio-standards/standards/Standards.Model.rb, line 2591
def standards_lookup_table_many(table_name:, search_criteria: {}, capacity: nil, date: nil, area: nil, num_floors: nil)
  desired_object = nil
  search_criteria_matching_objects = []
  matching_objects = []
  hash_of_objects = @standards_data[table_name]

  # needed for NRCan data structure compatibility. We keep all tables in a 'tables' hash in @standards_data and the table
  # itself is in the 'table' hash index.
  if hash_of_objects.nil?
    # Format of @standards_data is not NRCan-style and table simply doesn't exist.
    return matching_objects if @standards_data['tables'].nil?

    table = @standards_data['tables'][table_name]['table']
    hash_of_objects = table
  end

  # Compare each of the objects against the search criteria
  hash_of_objects.each do |object|
    meets_all_search_criteria = true
    search_criteria.each do |key, value|
      # Don't check non-existent search criteria
      next unless object.key?(key)

      # Stop as soon as one of the search criteria is not met
      # 'Any' is a special key that matches anything
      unless object[key] == value || object[key] == 'Any'
        meets_all_search_criteria = false
        break
      end
    end
    # Skip objects that don't meet all search criteria
    next unless meets_all_search_criteria

    # If made it here, object matches all search criteria
    matching_objects << object
  end

  # If capacity was specified, narrow down the matching objects
  unless capacity.nil?
    # Skip objects that don't have fields for minimum_capacity and maximum_capacity
    matching_objects = matching_objects.reject { |object| !object.key?('minimum_capacity') || !object.key?('maximum_capacity') }

    # Skip objects that don't have values specified for minimum_capacity and maximum_capacity
    matching_objects = matching_objects.reject { |object| object['minimum_capacity'].nil? || object['maximum_capacity'].nil? }

    # Round up if capacity is an integer
    if capacity == capacity.round
      capacity += (capacity * 0.01)
    end
    # Skip objects whose the minimum capacity is below or maximum capacity above the specified capacity
    matching_capacity_objects = matching_objects.reject { |object| capacity.to_f <= object['minimum_capacity'].to_f || capacity.to_f > object['maximum_capacity'].to_f }

    # If no object was found, round the capacity down in case the number fell between the limits in the json file.
    if matching_capacity_objects.size.zero?
      capacity *= 0.99
      search_criteria_matching_objects.each do |object|
        # Skip objects that don't have fields for minimum_capacity and maximum_capacity
        next if !object.key?('minimum_capacity') || !object.key?('maximum_capacity')
        # Skip objects that don't have values specified for minimum_capacity and maximum_capacity
        next if object['minimum_capacity'].nil? || object['maximum_capacity'].nil?
        # Skip objects whose the minimum capacity is below the specified capacity
        next if capacity <= object['minimum_capacity'].to_f
        # Skip objects whose max
        next if capacity > object['maximum_capacity'].to_f

        # Found a matching object
        matching_objects << object
      end
    end
    # If date was specified, narrow down the matching objects
    unless date.nil?
      date_matching_objects = []
      matching_objects.each do |object|
        # Skip objects that don't have fields for minimum_capacity and maximum_capacity
        next if !object.key?('start_date') || !object.key?('end_date')
        # Skip objects whose the start date is earlier than the specified date
        next if date <= Date.parse(object['start_date'])
        # Skip objects whose end date is beyond the specified date
        next if date > Date.parse(object['end_date'])

        # Found a matching object
        date_matching_objects << object
      end
      matching_objects = date_matching_objects
    end
  end

  # If area was specified, narrow down the matching objects
  unless area.nil?
    # Skip objects that don't have fields for minimum_area and maximum_area
    matching_objects = matching_objects.reject { |object| !object.key?('minimum_area') || !object.key?('maximum_area') }

    # Skip objects that don't have values specified for minimum_area and maximum_area
    matching_objects = matching_objects.reject { |object| object['minimum_area'].nil? || object['maximum_area'].nil? }

    # Skip objects whose minimum area is below or maximum area is above area
    matching_objects = matching_objects.reject { |object| area.to_f <= object['minimum_area'].to_f || area.to_f > object['maximum_area'].to_f }
  end

  # If area was specified, narrow down the matching objects
  unless num_floors.nil?
    # Skip objects that don't have fields for minimum_floors and maximum_floors
    matching_objects = matching_objects.reject { |object| !object.key?('minimum_floors') || !object.key?('maximum_floors') }

    # Skip objects that don't have values specified for minimum_floors and maximum_floors
    matching_objects = matching_objects.reject { |object| object['minimum_floors'].nil? || object['maximum_floors'].nil? }

    # Skip objects whose minimum floors is below or maximum floors is above num_floors
    matching_objects = matching_objects.reject { |object| num_floors.to_f < object['minimum_floors'].to_f || num_floors.to_f > object['maximum_floors'].to_f }
  end

  # Check the number of matching objects found
  if matching_objects.size.zero?
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Model', "Find objects search criteria returned no results. Search criteria: #{search_criteria}. Called from #{caller(0)[1]}.")
  end

  return matching_objects
end
strip_model(model) click to toggle source

Remove all resource objects in the model

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::Model] OpenStudio model object

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 30
def strip_model(model)
  # remove all materials
  model.getMaterials.each(&:remove)

  # remove all constructions
  model.getConstructions.each(&:remove)

  # remove performance curves
  model.getCurves.each do |curve|
    model.removeObject(curve.handle)
  end

  # remove all zone equipment
  model.getThermalZones.sort.each do |zone|
    zone.equipment.each(&:remove)
  end

  # remove all thermostats
  model.getThermostatSetpointDualSetpoints.each(&:remove)

  # remove all people
  model.getPeoples.each(&:remove)
  model.getPeopleDefinitions.each(&:remove)

  # remove all lights
  model.getLightss.each(&:remove)
  model.getLightsDefinitions.each(&:remove)

  # remove all electric equipment
  model.getElectricEquipments.each(&:remove)
  model.getElectricEquipmentDefinitions.each(&:remove)

  # remove all gas equipment
  model.getGasEquipments.each(&:remove)
  model.getGasEquipmentDefinitions.each(&:remove)

  # remove all outdoor air
  model.getDesignSpecificationOutdoorAirs.each(&:remove)

  # remove all infiltration
  model.getSpaceInfiltrationDesignFlowRates.each(&:remove)

  # Remove all internal mass
  model.getInternalMasss.each(&:remove)

  # Remove all internal mass defs
  model.getInternalMassDefinitions.each(&:remove)

  # Remove all thermal zones
  model.getThermalZones.each(&:remove)

  # Remove all schedules
  model.getSchedules.each(&:remove)

  # Remove all schedule type limits
  model.getScheduleTypeLimitss.each(&:remove)

  # Remove the sizing parameters
  model.getSizingParameters.remove

  # Remove the design days
  model.getDesignDays.each(&:remove)

  # Remove the rendering colors
  model.getRenderingColors.each(&:remove)

  # Remove the daylight controls
  model.getDaylightingControls.each(&:remove)

  return model
end
sub_surface_create_centered_subsurface_from_scaled_surface(surface, area_fraction) click to toggle source

This method adds a subsurface (a window or a skylight depending on the surface) to the centroid of a surface. The shape of the subsurface is the same as the surface but is scaled so the area of the subsurface is the defined fraction of the surface (set by area_fraction). Note that this only works for surfaces that do not fold into themselves (like an ‘L’ or a ‘V’).

@param surface [OpenStudio::Model::Surface] surface object @param area_fraction [Double] fraction of area of the larger surface @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.SubSurface.rb, line 12
def sub_surface_create_centered_subsurface_from_scaled_surface(surface, area_fraction)
  # Get rid of all existing subsurfaces.
  surface.subSurfaces.sort.each(&:remove)

  # What is the centroid of the surface.
  surf_cent = surface.centroid
  scale_factor = Math.sqrt(area_fraction)

  # Create an array to collect the new vertices
  new_vertices = []

  # Loop on vertices (Point3ds)
  surface.vertices.each do |vertex|
    # Point3d - Point3d = Vector3d
    # Vector from centroid to vertex (GA, GB, GC, etc)
    centroid_vector = vertex - surf_cent

    # Resize the vector (done in place) according to scale_factor
    centroid_vector.setLength(centroid_vector.length * scale_factor)

    # Move the vertex toward the centroid
    new_vertex = surf_cent + centroid_vector

    # Add the new vertices to an array of vertices.
    new_vertices << new_vertex
  end

  # Create a new subsurface with the vertices determined above.
  new_sub_surface = OpenStudio::Model::SubSurface.new(new_vertices, surface.model)
  # Put this sub-surface on the surface.
  new_sub_surface.setSurface(surface)
  # Set the name of the subsurface to be the surface name plus the subsurface type (likely either 'fixedwindow' or
  # 'skylight').
  new_name = surface.name.to_s + '_' + new_sub_surface.subSurfaceType.to_s
  new_sub_surface.setName(new_name)
  # There is now only one surface on the subsurface.  Enforce this
  new_sub_surface.setMultiplier(1)
  return true
end
sub_surface_create_scaled_subsurfaces_from_surface(surface:, area_fraction:, construction:) click to toggle source

This method adds a subsurface (a window or a skylight depending on the surface) to the centroid of a surface. The shape of the subsurface is the same as the surface but is scaled so the area of the subsurface is the defined fraction of the surface (set by area_fraction). This method is different than the ‘sub_surface_create_centered_subsurface_from_scaled_surface’ method because it can handle concave surfaces. However, it takes longer because it uses BTAP::Geometry::Surfaces.make_convex_surfaces which includes many nested loops that cycle through the verticies in a surface.

@param surface [OpenStudio::Model::Surface] surface object @param area_fraction [Double] fraction of area of the larger surface @param construction [OpenStudio::Model::Construction] construction to use for the new surface @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.SubSurface.rb, line 63
def sub_surface_create_scaled_subsurfaces_from_surface(surface:, area_fraction:, construction:)
  # Set geometry tolerences:
  geometry_tolerence = 12

  # Get rid of all existing subsurfaces
  surface.subSurfaces.sort.each(&:remove)

  # Return vertices of smaller surfaces that fit inside this surface.  This is done in case the surface is
  # concave.

  # Throw an error if the roof is not flat.
  surface.vertices.each do |surf_vert|
    surface.vertices.each do |surf_vert_2|
      return OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "Currently skylights can only be added to buildings with non-plenum flat roofs.  No skylight added to surface #{surface.name}") if surf_vert_2.z.to_f.round(geometry_tolerence) != surf_vert.z.to_f.round(geometry_tolerence)
    end
  end
  new_surfaces = BTAP::Geometry::Surfaces.make_convex_surfaces(surface: surface, tol: geometry_tolerence)

  # What is the centroid of the surface.
  new_surf_cents = []
  for i in 0..(new_surfaces.length - 1)
    new_surf_cents << BTAP::Geometry::Surfaces.surf_centroid(surf: new_surfaces[i])
  end

  # Turn everything back into OpenStudio stuff
  os_surf_points = []
  os_surf_cents = []
  for i in 0..(new_surfaces.length - 1)
    os_surf_point = []
    for j in 0..(new_surfaces[i].length - 1)
      os_surf_point << OpenStudio::Point3d.new(new_surfaces[i][j][:x].to_f, new_surfaces[i][j][:y].to_f, new_surfaces[i][j][:z].to_f)
    end
    os_surf_cents << OpenStudio::Point3d.new(new_surf_cents[i][:x].to_f, new_surf_cents[i][:y].to_f, new_surf_cents[i][:z].to_f)
    os_surf_points << os_surf_point
  end
  scale_factor = Math.sqrt(area_fraction)

  new_sub_vertices = []
  os_surf_points.each_with_index do |new_surf, index|
    # Create an array to collect the new vertices
    new_vertices = []
    # Loop on vertices
    new_surf.each do |vertex|
      # Point3d - Point3d = Vector3d
      # Vector from centroid to vertex (GA, GB, GC, etc)
      centroid_vector = vertex - os_surf_cents[index]

      # Resize the vector (done in place) according to scale_factor
      centroid_vector.setLength(centroid_vector.length * scale_factor)

      # Move the vertex toward the centroid
      new_vertex = os_surf_cents[index] + centroid_vector

      # Add the new vertices to an array of vertices.
      new_vertices << new_vertex
    end
    # Check if the new surface/subsurface is too small to model.  If it is then skip it.
    new_area = BTAP::Geometry::Surfaces.getSurfaceAreafromVertices(vertices: new_vertices)
    if new_area < 0.0001
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.Model', "Attempting to create a subsurface in surface #{surface.name} with an area of #{new_area}m2.  This subsurface is too small so will be skipped")
      next
    end

    # Create a new subsurface with the vertices determined above.
    new_sub_surface = OpenStudio::Model::SubSurface.new(new_vertices, surface.model)
    # Put this sub-surface on the surface.
    new_sub_surface.setSurface(surface)
    # Set the name of the subsurface to be the surface name plus the subsurface type (likely either 'fixedwindow' or
    # 'skylight').  If there will be more than one subsurface then add a counter at the end.
    new_name = surface.name.to_s + '_' + new_sub_surface.subSurfaceType.to_s
    if new_surfaces.length > 1
      new_name = surface.name.to_s + '_' + new_sub_surface.subSurfaceType.to_s + '_' + index.to_s
    end
    # Set the skylight type to 'Skylight'
    new_sub_surface.setSubSurfaceType('Skylight')
    # Set the skylight construction to whatever was passed (should be the default skylight construction)
    new_sub_surface.setConstruction(construction)
    new_sub_surface.setName(new_name)
    # There is now only one surface on the subsurface.  Enforce this
    new_sub_surface.setMultiplier(1)
  end
  return true
end
surface_adjust_fenestration_in_a_surface(surface, reduction, model) click to toggle source

Adjust the fenestration area to the values specified by the reduction value in a surface

@param surface [OpenStudio::Model:Surface] openstudio surface object @param reduction [Double] ratio of adjustments @param model [OpenStudio::Model::Model] openstudio model @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Surface.rb, line 317
def surface_adjust_fenestration_in_a_surface(surface, reduction, model)
  # Subsurfaces in this surface
  # Default case only handles reduction
  if reduction < 1.0
    surface.subSurfaces.sort.each do |ss|
      next unless ss.subSurfaceType == 'FixedWindow' || ss.subSurfaceType == 'OperableWindow' || ss.subSurfaceType == 'GlassDoor'

      if OpenstudioStandards::Geometry.sub_surface_vertical_rectangle?(ss)
        OpenstudioStandards::Geometry.sub_surface_reduce_area_by_percent_by_raising_sill(ss, reduction)
      else
        OpenstudioStandards::Geometry.sub_surface_reduce_area_by_percent_by_shrinking_toward_centroid(ss, reduction)
      end
    end
  end
  return true
end
surface_subsurface_ua(surface) click to toggle source

Returns the surface and subsurface UA product

@param surface [OpenStudio::Model::Surface] OpenStudio model surface object @return [Double] UA product in W/K

# File lib/openstudio-standards/standards/Standards.Surface.rb, line 269
def surface_subsurface_ua(surface)
  # Compute the surface UA product
  if surface.outsideBoundaryCondition.to_s == 'GroundFCfactorMethod' && surface.construction.is_initialized
    cons = surface.construction.get
    fc_obj_type = cons.iddObjectType.valueName.to_s
    case fc_obj_type
      when 'OS_Construction_FfactorGroundFloor'
        cons = surface.construction.get.to_FFactorGroundFloorConstruction.get
        ffac = cons.fFactor
        area = cons.area
        peri = cons.perimeterExposed
        ua = ffac * peri * surface.netArea / area
      when 'OS_Construction_CfactorUndergroundWall'
        cons = surface.construction.get.to_CFactorUndergroundWallConstruction.get
        cfac = cons.cFactor
        heig = cons.height

        # From 90.1-2019 Section A.9.4.1: Interior vertical surfaces (SI units)
        r_inside_film = 0.1197548
        r_outside_film = 0.0

        # EnergyPlus Engineering Manual equation 3.195
        r_soil = 0.0607 + 0.3479 * heig

        r_eff = 1 / cfac + r_soil
        u_eff = 1 / (r_eff + r_inside_film + r_outside_film)

        ua = u_eff * surface.netArea
    end
  else
    ua = surface.uFactor.get * surface.netArea
  end

  surface.subSurfaces.sort.each do |subsurface|
    subsurface_construction = subsurface.construction.get
    u_factor = OpenstudioStandards::SqlFile.construction_calculated_fenestration_u_factor(subsurface_construction)
    ua += u_factor * subsurface.netArea
  end

  return ua
end
thermal_eff_to_afue(teff) click to toggle source

A helper method to convert from thermal efficiency to AFUE @ref [References::USDOEPrototypeBuildings] Boiler Addendum 90.1-04an

@param teff [Double] Thermal Efficiency @return [Double] AFUE

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 416
def thermal_eff_to_afue(teff)
  return teff
end
thermal_eff_to_comb_eff(thermal_eff) click to toggle source

A helper method to convert from thermal efficiency to combustion efficiency @ref [References::USDOEPrototypeBuildings] Boiler Addendum 90.1-04an

@param thermal_eff [Double] Thermal efficiency @return [Double] Combustion efficiency

# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 434
def thermal_eff_to_comb_eff(thermal_eff)
  return thermal_eff + 0.007
end
thermal_zone_add_exhaust(thermal_zone, exhaust_makeup_inputs = {}) click to toggle source

Add Exhaust Fans based on space type lookup. This measure doesn’t look if DCV is needed. Others methods can check if DCV needed and add it.

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @param exhaust_makeup_inputs [Hash] has of makeup exhaust inputs @return [Hash] Hash of newly made exhaust fan objects along with secondary exhaust and zone mixing objects @todo combine availability and fraction flow schedule to make zone mixing schedule

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 684
def thermal_zone_add_exhaust(thermal_zone, exhaust_makeup_inputs = {})
  exhaust_fans = {} # key is primary exhaust value is hash of arrays of secondary objects

  # hash to store space type information
  space_type_hash = {} # key is space type value is floor_area_si

  # get space type ratio for spaces in zone, making more than one exhaust fan if necessary
  thermal_zone.spaces.each do |space|
    next unless space.spaceType.is_initialized
    next unless space.partofTotalFloorArea

    space_type = space.spaceType.get
    if space_type_hash.key?(space_type)
      space_type_hash[space_type] += space.floorArea # excluding space.multiplier since used to calc loads in zone
    else
      next unless space_type.standardsBuildingType.is_initialized
      next unless space_type.standardsSpaceType.is_initialized

      space_type_hash[space_type] = space.floorArea # excluding space.multiplier since used to calc loads in zone
    end
  end

  # loop through space type hash and add exhaust as needed
  space_type_hash.each do |space_type, floor_area|
    # get floor custom or calculated floor area for max flow rate calculation
    makeup_target = [space_type.standardsBuildingType.get, space_type.standardsSpaceType.get]
    if exhaust_makeup_inputs.key?(makeup_target) && exhaust_makeup_inputs[makeup_target].key?(:target_effective_floor_area)
      # pass in custom floor area
      floor_area_si = exhaust_makeup_inputs[makeup_target][:target_effective_floor_area] / thermal_zone.multiplier.to_f
      floor_area_ip = OpenStudio.convert(floor_area_si, 'm^2', 'ft^2').get
    else
      floor_area_ip = OpenStudio.convert(floor_area, 'm^2', 'ft^2').get
    end

    space_type_properties = space_type_get_standards_data(space_type)
    exhaust_per_area = space_type_properties['exhaust_per_area']
    next if exhaust_per_area.nil?

    maximum_flow_rate_ip = exhaust_per_area * floor_area_ip
    maximum_flow_rate_si = OpenStudio.convert(maximum_flow_rate_ip, 'cfm', 'm^3/s').get
    if space_type_properties['exhaust_availability_schedule'].nil?
      exhaust_schedule = thermal_zone.model.alwaysOnDiscreteSchedule
      exhaust_flow_schedule = exhaust_schedule
    else
      sch_name = space_type_properties['exhaust_availability_schedule']
      exhaust_schedule = model_add_schedule(thermal_zone.model, sch_name)
      flow_sch_name = space_type_properties['exhaust_flow_fraction_schedule']
      exhaust_flow_schedule = model_add_schedule(thermal_zone.model, flow_sch_name)
      unless exhaust_schedule
        OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Standards.ThermalZone', "Could not find an exhaust schedule called #{sch_name}, exhaust fans will run continuously.")
        exhaust_schedule = thermal_zone.model.alwaysOnDiscreteSchedule
      end
    end

    # add exhaust fans
    zone_exhaust_fan = OpenStudio::Model::FanZoneExhaust.new(thermal_zone.model)
    zone_exhaust_fan.setName(thermal_zone.name.to_s + ' Exhaust Fan')
    zone_exhaust_fan.setAvailabilitySchedule(exhaust_schedule)
    zone_exhaust_fan.setFlowFractionSchedule(exhaust_flow_schedule)
    # not using zone_exhaust_fan.setFlowFractionSchedule. Exhaust fans are on when available
    zone_exhaust_fan.setMaximumFlowRate(maximum_flow_rate_si)
    zone_exhaust_fan.setEndUseSubcategory('Zone Exhaust Fans')
    zone_exhaust_fan.addToThermalZone(thermal_zone)
    exhaust_fans[zone_exhaust_fan] = {} # keys are :zone_mixing and :transfer_air_source_zone_exhaust

    # set fan pressure rise
    fan_zone_exhaust_apply_prototype_fan_pressure_rise(zone_exhaust_fan)

    # update efficiency and pressure rise
    prototype_fan_apply_prototype_fan_efficiency(zone_exhaust_fan)

    # add and alter objectxs related to zone exhaust makeup air
    if exhaust_makeup_inputs.key?(makeup_target) && exhaust_makeup_inputs[makeup_target][:source_zone]

      # add balanced schedule to zone_exhaust_fan
      balanced_sch_name = space_type_properties['balanced_exhaust_fraction_schedule']
      balanced_exhaust_schedule = model_add_schedule(thermal_zone.model, balanced_sch_name).to_ScheduleRuleset.get
      zone_exhaust_fan.setBalancedExhaustFractionSchedule(balanced_exhaust_schedule)

      # use max value of balanced exhaust fraction schedule for maximum flow rate
      max_sch_val = OpenstudioStandards::Schedules.schedule_ruleset_get_min_max(balanced_exhaust_schedule)['max']
      transfer_air_zone_mixing_si = maximum_flow_rate_si * max_sch_val

      # add dummy exhaust fan to a transfer_air_source_zones
      transfer_air_source_zone_exhaust = OpenStudio::Model::FanZoneExhaust.new(thermal_zone.model)
      transfer_air_source_zone_exhaust.setName(thermal_zone.name.to_s + ' Transfer Air Source')
      transfer_air_source_zone_exhaust.setAvailabilitySchedule(exhaust_schedule)
      # not using zone_exhaust_fan.setFlowFractionSchedule. Exhaust fans are on when available
      transfer_air_source_zone_exhaust.setMaximumFlowRate(transfer_air_zone_mixing_si)
      transfer_air_source_zone_exhaust.setFanEfficiency(1.0)
      transfer_air_source_zone_exhaust.setPressureRise(0.0)
      transfer_air_source_zone_exhaust.setEndUseSubcategory('Zone Exhaust Fans')
      transfer_air_source_zone_exhaust.addToThermalZone(exhaust_makeup_inputs[makeup_target][:source_zone])
      exhaust_fans[zone_exhaust_fan][:transfer_air_source_zone_exhaust] = transfer_air_source_zone_exhaust

      # @todo make zone mixing schedule by combining exhaust availability and fraction flow
      zone_mixing_schedule = exhaust_schedule

      # add zone mixing
      zone_mixing = OpenStudio::Model::ZoneMixing.new(thermal_zone)
      zone_mixing.setSchedule(zone_mixing_schedule)
      zone_mixing.setSourceZone(exhaust_makeup_inputs[makeup_target][:source_zone])
      zone_mixing.setDesignFlowRate(transfer_air_zone_mixing_si)
      exhaust_fans[zone_exhaust_fan][:zone_mixing] = zone_mixing

    end
  end

  return exhaust_fans
end
thermal_zone_add_exhaust_fan_dcv(thermal_zone, change_related_objects = true, zone_mixing_objects = [], transfer_air_source_zones = []) click to toggle source

Add DCV to exhaust fan and if requsted to related objects

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @param change_related_objects [Boolean] change related objects @param zone_mixing_objects [Array<OpenStudio::Model::ZoneMixing>] array of zone mixing objects @param transfer_air_source_zones [Array<OpenStudio::Model::ThermalZone>] array thermal zones that transfer air @return [Boolean] returns true if successful, false if not @todo this method is currently empty

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 809
def thermal_zone_add_exhaust_fan_dcv(thermal_zone, change_related_objects = true, zone_mixing_objects = [], transfer_air_source_zones = [])
  # set flow fraction schedule for all zone exhaust fans and then set zone mixing schedule to the intersection of exhaust availability and exhaust fractional schedule

  # are there associated zone mixing or dummy exhaust objects that need to change when this changes?
  # How are these objects identified?
  # If this is run directly after thermal_zone_add_exhaust(thermal_zone)  it will return a hash where each key is an exhaust object and hash is a hash of related zone mixing and dummy exhaust from the source zone
  return true
end
thermal_zone_apply_prm_baseline_supply_temperatures(thermal_zone) click to toggle source

Set the design delta-T for zone heating and cooling sizing supply air temperatures. This value determines zone air flows, which will be summed during system design airflow calculation.

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 464
def thermal_zone_apply_prm_baseline_supply_temperatures(thermal_zone)
  # Skip spaces that aren't heated or cooled
  return true unless OpenstudioStandards::ThermalZone.thermal_zone_heated?(thermal_zone) || OpenstudioStandards::ThermalZone.thermal_zone_cooled?(thermal_zone)

  # Heating
  htg_sat_c = thermal_zone_prm_baseline_heating_design_supply_temperature(thermal_zone)
  htg_success = thermal_zone.sizingZone.setZoneHeatingDesignSupplyAirTemperature(htg_sat_c)

  # Cooling
  clg_sat_c = thermal_zone_prm_baseline_cooling_design_supply_temperature(thermal_zone)
  clg_success = thermal_zone.sizingZone.setZoneCoolingDesignSupplyAirTemperature(clg_sat_c)

  htg_sat_f = OpenStudio.convert(htg_sat_c, 'C', 'F').get
  clg_sat_f = OpenStudio.convert(clg_sat_c, 'C', 'F').get
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "For #{thermal_zone.name}, Htg SAT = #{htg_sat_f.round(1)}F, Clg SAT = #{clg_sat_f.round(1)}F.")

  result = false
  if htg_success && clg_success
    result = true
  end

  return result
end
thermal_zone_conditioning_category(thermal_zone, climate_zone) click to toggle source

Determines whether the zone is conditioned per 90.1, which is based on heating and cooling loads. Logic to detect indirectly-conditioned spaces cannot be implemented as part of this measure as it would need to call itself. It is implemented as part of space_conditioning_category(). @todo Add addendum db rules to 90.1-2019 for 90.1-2022 (use stable baseline value for zones designated as semiheated using proposed sizing run)

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [String] NonResConditioned, ResConditioned, Semiheated, Unconditioned

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 224
def thermal_zone_conditioning_category(thermal_zone, climate_zone)
  # error if zone design load methods are not available
  if thermal_zone.model.version < OpenStudio::VersionString.new('3.6.0')
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Standards.ThermalZone', 'Required ThermalZone methods .autosizedHeatingDesignLoad and .autosizedCoolingDesignLoad are not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
  end

  # Get the heating load
  htg_load_btu_per_ft2 = 0.0
  htg_load_w = thermal_zone.autosizedHeatingDesignLoad
  if htg_load_w.is_initialized
    htg_load_w_per_m2 = thermal_zone.autosizedHeatingDesignLoad.get / thermal_zone.floorArea
    htg_load_btu_per_ft2 = OpenStudio.convert(htg_load_w_per_m2, 'W/m^2', 'Btu/hr*ft^2').get
  end

  # Get the cooling load
  clg_load_btu_per_ft2 = 0.0
  clg_load_w = thermal_zone.autosizedCoolingDesignLoad
  if clg_load_w.is_initialized
    clg_load_w_per_m2 = thermal_zone.autosizedCoolingDesignLoad.get / thermal_zone.floorArea
    clg_load_btu_per_ft2 = OpenStudio.convert(clg_load_w_per_m2, 'W/m^2', 'Btu/hr*ft^2').get
  end

  # Determine the heating limit based on climate zone
  # From Table 3.1 Heated Space Criteria
  htg_lim_btu_per_ft2 = 0.0
  climate_zone_code = climate_zone.split('-')[-1]
  if ['0A', '0B', '1A', '1B', '2A', '2B'].include? climate_zone_code
    htg_lim_btu_per_ft2 = 5
    stable_htg_lim_btu_per_ft2 = 5
  elsif ['3A', '3B'].include? climate_zone_code
    htg_lim_btu_per_ft2 = 9
    stable_htg_lim_btu_per_ft2 = 10
  elsif climate_zone_code == '3C'
    htg_lim_btu_per_ft2 = 7
    stable_htg_lim_btu_per_ft2 = 10
  elsif ['4A', '4B'].include? climate_zone_code
    htg_lim_btu_per_ft2 = 10
    stable_htg_lim_btu_per_ft2 = 15
  elsif climate_zone_code == '4C'
    htg_lim_btu_per_ft2 = 8
    stable_htg_lim_btu_per_ft2 = 15
  elsif ['5A', '5B', '5C'].include? climate_zone_code
    htg_lim_btu_per_ft2 = 12
    stable_htg_lim_btu_per_ft2 = 15
  elsif ['6A', '6B'].include? climate_zone_code
    htg_lim_btu_per_ft2 = 14
    stable_htg_lim_btu_per_ft2 = 20
  elsif ['7A', '7B'].include? climate_zone_code
    htg_lim_btu_per_ft2 = 16
    stable_htg_lim_btu_per_ft2 = 20
  elsif ['8A', '8B'].include? climate_zone_code
    htg_lim_btu_per_ft2 = 19
    stable_htg_lim_btu_per_ft2 = 25
  end

  # for older code versions use stable baseline value as primary target
  if ['90.1-2004', '90.1-2007', '90.1-2010', '90.1-2013'].include? template
    htg_lim_btu_per_ft2 = stable_htg_lim_btu_per_ft2
  end

  # Cooling limit is climate-independent
  case template
  when '90.1-2016', '90.1-PRM-2019'
    clg_lim_btu_per_ft2 = 3.4
  else
    clg_lim_btu_per_ft2 = 5
  end

  # Semiheated limit is climate-independent
  semihtd_lim_btu_per_ft2 = 3.4

  # Determine if residential
  res = false
  if OpenstudioStandards::ThermalZone.thermal_zone_residential?(thermal_zone)
    res = true
  end

  cond_cat = 'Unconditioned'
  if htg_load_btu_per_ft2 > htg_lim_btu_per_ft2
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "Zone #{thermal_zone.name} is conditioned because heating load of #{htg_load_btu_per_ft2.round} Btu/hr*ft^2 exceeds minimum of #{htg_lim_btu_per_ft2.round} Btu/hr*ft^2.")
    cond_cat = if res
                 'ResConditioned'
               else
                 'NonResConditioned'
               end
  elsif clg_load_btu_per_ft2 > clg_lim_btu_per_ft2
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "Zone #{thermal_zone.name} is conditioned because cooling load of #{clg_load_btu_per_ft2.round} Btu/hr*ft^2 exceeds minimum of #{clg_lim_btu_per_ft2.round} Btu/hr*ft^2.")
    cond_cat = if res
                 'ResConditioned'
               else
                 'NonResConditioned'
               end
  elsif htg_load_btu_per_ft2 > semihtd_lim_btu_per_ft2
    cond_cat = 'Semiheated'
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "Zone #{thermal_zone.name} is semiheated because heating load of #{htg_load_btu_per_ft2.round} Btu/hr*ft^2 exceeds minimum of #{semihtd_lim_btu_per_ft2.round} Btu/hr*ft^2.")
  end

  return cond_cat
end
thermal_zone_demand_control_ventilation_limits(thermal_zone) click to toggle source

Determine the area and occupancy level limits for demand control ventilation. No DCV requirements by default.

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @return [Array<Double>] the minimum area, in m^2 and the minimum occupancy density in m^2/person.

Returns nil if there is no requirement.
# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 670
def thermal_zone_demand_control_ventilation_limits(thermal_zone)
  min_area_m2 = nil
  min_area_per_occ = nil
  return [min_area_m2, min_area_per_occ]
end
thermal_zone_demand_control_ventilation_required?(thermal_zone, climate_zone) click to toggle source

Determine if demand control ventilation (DCV) is required for this zone based on area and occupant density. Does not account for System requirements like ERV, economizer, etc. Those are accounted for in the AirLoopHVAC method of the same name.

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] Returns true if required, false if not @todo Add exception logic for 90.1-2013

for cells, sickrooms, labs, barbers, salons, and bowling alleys
# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 603
def thermal_zone_demand_control_ventilation_required?(thermal_zone, climate_zone)
  dcv_required = false

  # Get the limits
  min_area_m2, min_area_m2_per_occ = thermal_zone_demand_control_ventilation_limits(thermal_zone)

  # Not required if both limits nil
  if min_area_m2.nil? && min_area_m2_per_occ.nil?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.ThermalZone', "For #{thermal_zone.name}: DCV is not required due to lack of minimum area requirements.")
    return dcv_required
  end

  # Get the area served and the number of occupants
  area_served_m2 = 0
  num_people = 0
  thermal_zone.spaces.each do |space|
    area_served_m2 += space.floorArea
    num_people += space.numberOfPeople
  end
  area_served_ft2 = OpenStudio.convert(area_served_m2, 'm^2', 'ft^2').get

  # Check the minimum area if there is a limit
  if min_area_m2
    # Convert limit to IP
    min_area_ft2 = OpenStudio.convert(min_area_m2, 'm^2', 'ft^2').get
    # Check the limit
    if area_served_ft2 < min_area_ft2
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.ThermalZone', "For #{thermal_zone.name}: DCV is not required since the area is #{area_served_ft2.round} ft2, but the minimum size is #{min_area_ft2.round} ft2.")
      return dcv_required
    end
  end

  # Check the minimum occupancy density if there is a limit
  if min_area_m2_per_occ
    # Convert limit to IP
    min_area_ft2_per_occ = OpenStudio.convert(min_area_m2_per_occ, 'm^2', 'ft^2').get
    min_occ_per_ft2 = 1.0 / min_area_ft2_per_occ
    min_occ_per_1000_ft2 = min_occ_per_ft2 * 1000
    # Check the limit
    occ_per_ft2 = num_people / area_served_ft2
    occ_per_1000_ft2 = occ_per_ft2 * 1000
    if occ_per_1000_ft2 < min_occ_per_1000_ft2
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.ThermalZone', "For #{thermal_zone.name}: DCV is not required since the occupant density is #{occ_per_1000_ft2.round} people/1000 ft2, but the minimum occupant density is #{min_occ_per_1000_ft2.round} people/1000 ft2.")
      return dcv_required
    end
  end

  # If here, DCV is required
  if min_area_m2 && min_area_m2_per_occ
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.ThermalZone', "For #{thermal_zone.name}: DCV is required since the occupant density of #{occ_per_1000_ft2.round} people/1000 ft2 is above minimum occupant density of #{min_occ_per_1000_ft2.round} people/1000 ft2 and the area of #{area_served_ft2.round} ft2 is above the minimum size of #{min_area_ft2.round} ft2.")
  elsif min_area_m2
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.ThermalZone', "For #{thermal_zone.name}: DCV is required since the area of #{area_served_ft2.round} ft2 is above the minimum size of #{min_area_ft2.round} ft2.")
  elsif min_area_m2_per_occ
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.ThermalZone', "For #{thermal_zone.name}: DCV is required since the occupant density of #{occ_per_1000_ft2.round} people/1000 ft2 is above minimum occupant density of #{min_occ_per_1000_ft2.round} people/1000 ft2.")
  end

  dcv_required = true

  return dcv_required
end
thermal_zone_exhaust_fan_dcv_required?(thermal_zone) click to toggle source

returns true if DCV is required for exhaust fan for specified tempate

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @return [Boolean] returns true if DCV is required for exhaust fan for specified template, false if not

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 799
def thermal_zone_exhaust_fan_dcv_required?(thermal_zone); end
thermal_zone_fossil_or_electric_type(thermal_zone, custom) click to toggle source

Determine if the thermal zone’s fuel type category. Options are:

fossil, electric, unconditioned

If a customization is passed, additional categories may be returned. If ‘Xcel Energy CO EDA’, the type fossilandelectric is added. DistrictHeating is considered a fossil fuel since it is typically created by natural gas boilers.

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @param custom [String] string for custom case statement @return [String] the fuel type category

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 22
def thermal_zone_fossil_or_electric_type(thermal_zone, custom)
  # error if HVACComponent heating fuels method is not available
  if thermal_zone.model.version < OpenStudio::VersionString.new('3.6.0')
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Standards.ThermalZone', 'Required HVACComponent methods .heatingFuelTypes and .coolingFuelTypes are not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
  end

  # Cooling fuels, for determining unconditioned zones
  htg_fuels = thermal_zone.heatingFuelTypes.map(&:valueName)
  clg_fuels = thermal_zone.coolingFuelTypes.map(&:valueName)
  fossil = OpenstudioStandards::ThermalZone.thermal_zone_fossil_heat?(thermal_zone)
  district = OpenstudioStandards::ThermalZone.thermal_zone_district_heat?(thermal_zone)
  electric = OpenstudioStandards::ThermalZone.thermal_zone_electric_heat?(thermal_zone)

  # Categorize
  fuel_type = nil
  if fossil || district
    # If uses any fossil, counts as fossil even if electric is present too
    fuel_type = 'fossil'
  elsif electric
    fuel_type = 'electric'
  elsif htg_fuels.size.zero? && clg_fuels.size.zero?
    fuel_type = 'unconditioned'
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Standards.ThermalZone', "For #{thermal_zone.name}, could not determine fuel type, assuming fossil.  Heating fuels = #{htg_fuels.join(', ')}; cooling fuels = #{clg_fuels.join(', ')}.")
    fuel_type = 'fossil'
  end

  # Customization for Xcel.
  # Likely useful for other utility
  # programs where fuel switching is important.
  # This is primarily for systems where Gas is
  # used at the central AHU and electric is
  # used at the terminals/zones.  Examples
  # include zone VRF/PTHP with gas-heated DOAS,
  # and gas VAV with electric reheat
  case custom
  when 'Xcel Energy CO EDA'
    if fossil && electric
      fuel_type = 'fossilandelectric'
    end
  end

  return fuel_type
end
thermal_zone_get_annual_operating_hours(model, zone, zone_fan_sched) click to toggle source

This is the operating hours for calulating EFLH which is used for determining whether a zone should be included in a multizone system or isolated to a separate PSZ system Based on the occupancy schedule for that zone @author Doug Maddox, PNNL @return [Array] 8760 array with 1 = operating, 0 = not operating

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 522
def thermal_zone_get_annual_operating_hours(model, zone, zone_fan_sched)
  zone_ppl_sch = Array.new(8760, 0)     # merged people schedule for zone
  zone_op_sch = Array.new(8760, 0)      # intersection of fan and people scheds

  unoccupied_threshold = air_loop_hvac_unoccupied_threshold
  # Need composite occupant schedule for spaces in the zone
  zone.spaces.each do |space|
    space_ppl_sch = space_occupancy_annual_array(model, space)
    # If any space is occupied, make zone occupied
    (0..8759).each do |ihr|
      zone_ppl_sch[ihr] = 1 if space_ppl_sch[ihr] > 0
    end
  end

  zone_op_sch = zone_ppl_sch

  return zone_op_sch
end
thermal_zone_get_zone_fuels_for_occ_and_fuel_type(thermal_zone) click to toggle source

for 2013 and prior, baseline fuel = proposed fuel @param thermal_zone @return [String with applicable DistrictHeating and/or DistrictCooling

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 7
def thermal_zone_get_zone_fuels_for_occ_and_fuel_type(thermal_zone)
  zone_fuels = thermal_zone_fossil_or_electric_type(thermal_zone, '')
  return zone_fuels
end
thermal_zone_infer_system_type(thermal_zone) click to toggle source

Infers the baseline system type based on the equipment serving the zone and their heating/cooling fuels. Only does a high-level inference; does not look for the presence/absence of required controls, etc.

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @return [String] system type. Possible system types are:

PTHP, PTAC, PSZ_AC, PSZ_HP, PVAV_Reheat, PVAV_PFP_Boxes,
VAV_Reheat, VAV_PFP_Boxes, Gas_Furnace, Electric_Furnace
# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 74
def thermal_zone_infer_system_type(thermal_zone)
  # Determine the characteristics
  # of the equipment serving the zone
  has_air_loop = false
  air_loop_num_zones = 0
  air_loop_is_vav = false
  air_loop_has_chw = false
  has_ptac = false
  has_pthp = false
  has_unitheater = false
  thermal_zone.equipment.each do |equip|
    # Skip HVAC components
    next unless equip.to_HVACComponent.is_initialized

    equip = equip.to_HVACComponent.get
    if equip.airLoopHVAC.is_initialized
      has_air_loop = true
      air_loop = equip.airLoopHVAC.get
      air_loop_num_zones = air_loop.thermalZones.size
      air_loop.supplyComponents.each do |sc|
        if sc.to_FanVariableVolume.is_initialized
          air_loop_is_vav = true
        elsif sc.to_CoilCoolingWater.is_initialized
          air_loop_has_chw = true
        end
      end
    elsif equip.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
      has_ptac = true
    elsif equip.to_ZoneHVACPackagedTerminalHeatPump.is_initialized
      has_pthp = true
    elsif equip.to_ZoneHVACUnitHeater.is_initialized
      has_unitheater = true
    end
  end

  # error if HVACComponent heating fuels method is not available
  if thermal_zone.model.version < OpenStudio::VersionString.new('3.6.0')
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.Standards.ThermalZone', 'Required HVACComponent methods .heatingFuelTypes and .coolingFuelTypes are not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
  end

  # Get the zone heating and cooling fuels
  htg_fuels = thermal_zone.heatingFuelTypes.map(&:valueName)
  clg_fuels = thermal_zone.coolingFuelTypes.map(&:valueName)
  is_fossil = OpenstudioStandards::ThermalZone.thermal_zone_fossil_heat?(thermal_zone) || OpenstudioStandards::ThermalZone.thermal_zone_district_heat?(thermal_zone)

  # Infer the HVAC type
  sys_type = 'Unknown'

  # Single zone
  if air_loop_num_zones < 2
    # Gas
    if is_fossil
      # Air Loop
      if has_air_loop
        # Gas_Furnace (as air loop)
        sys_type = if clg_fuels.size.zero?
                     'Gas_Furnace'
                   # PSZ_AC
                   else
                     'PSZ_AC'
                   end
      # Zone Equipment
      else
        # Gas_Furnace (as unit heater)
        if has_unitheater
          sys_type = 'Gas_Furnace'
        end
        # PTAC
        if has_ptac
          sys_type = 'PTAC'
        end
      end
    # Electric
    else
      # Air Loop
      if has_air_loop
        # Electric_Furnace (as air loop)
        sys_type = if clg_fuels.size.zero?
                     'Electric_Furnace'
                   # PSZ_HP
                   else
                     'PSZ_HP'
                   end
      # Zone Equipment
      else
        # Electric_Furnace (as unit heater)
        if has_unitheater
          sys_type = 'Electric_Furnace'
        end
        # PTHP
        if has_pthp
          sys_type = 'PTHP'
        end
      end
    end
  # Multi-zone
  else
    # Gas
    if is_fossil
      # VAV_Reheat
      if air_loop_has_chw && air_loop_is_vav
        sys_type = 'VAV_Reheat'
      end
      # PVAV_Reheat
      if !air_loop_has_chw && air_loop_is_vav
        sys_type = 'PVAV_Reheat'
      end
    # Electric
    else
      # VAV_PFP_Boxes
      if air_loop_has_chw && air_loop_is_vav
        sys_type = 'VAV_PFP_Boxes'
      end
      # PVAV_PFP_Boxes
      if !air_loop_has_chw && air_loop_is_vav
        sys_type = 'PVAV_PFP_Boxes'
      end
    end
  end

  # Report out the characteristics for debugging if
  # the system type cannot be inferred.
  if sys_type == 'Unknown'
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Standards.ThermalZone', "For #{thermal_zone.name}, the baseline system type could not be inferred.")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "***#{thermal_zone.name}***")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "system type = #{sys_type}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "has_air_loop = #{has_air_loop}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "air_loop_num_zones = #{air_loop_num_zones}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "air_loop_is_vav = #{air_loop_is_vav}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "air_loop_has_chw = #{air_loop_has_chw}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "has_ptac = #{has_ptac}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "has_pthp = #{has_pthp}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "has_unitheater = #{has_unitheater}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "htg_fuels = #{htg_fuels}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "clg_fuels = #{clg_fuels}")
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.Standards.ThermalZone', "is_fossil = #{is_fossil}")
  end

  return sys_type
end
thermal_zone_occupancy_eflh(zone, zone_op_sch) click to toggle source

This is the EFLH for determining whether a zone should be included in a multizone system or isolated to a separate PSZ system Based on the intersection of the fan schedule for that zone and the occupancy schedule for that zone @author Doug Maddox, PNNL @return [Double] the design internal load, in W

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 546
def thermal_zone_occupancy_eflh(zone, zone_op_sch)
  eflhs = [] # weekly array of eflh values

  # Convert 8760 array to weekly eflh values
  hr_of_yr = -1
  (0..51).each do |iweek|
    eflh = 0
    (0..6).each do |iday|
      (0..23).each do |ihr|
        hr_of_yr += 1
        eflh += zone_op_sch[hr_of_yr]
      end
    end
    eflhs << eflh
  end

  # Choose the most used weekly schedule as the representative eflh
  # This is the statistical mode of the array of values
  eflh_mode_list = eflhs.mode

  if eflh_mode_list.size > 1
    # Mode is an array of multiple values, take the largest value
    eflh = eflh_mode_list.max
  else
    eflh = eflh_mode_list[0]
  end
  return eflh
end
thermal_zone_occupancy_type(thermal_zone) click to toggle source

Determine the thermal zone’s occupancy type category. Options are: residential, nonresidential

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @return [String] the occupancy type category @todo Add public assembly building types

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 581
def thermal_zone_occupancy_type(thermal_zone)
  occ_type = if OpenstudioStandards::ThermalZone.thermal_zone_residential?(thermal_zone)
               'residential'
             else
               'nonresidential'
             end

  # OpenStudio::logFree(OpenStudio::Info, "openstudio.Standards.ThermalZone", "For #{self.name}, occupancy type = #{occ_type}.")

  return occ_type
end
thermal_zone_peak_internal_load(model, thermal_zone, use_noncoincident_value: true) click to toggle source

Determine the peak internal load (W) for this zone without space multipliers. This includes People, Lights, and all equipment types in all spaces in this zone. @author Doug Maddox, PNNL @return [Double] the design internal load, in W

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 494
def thermal_zone_peak_internal_load(model, thermal_zone, use_noncoincident_value: true)
  load_w = 0.0
  load_hrs_sum = Array.new(8760, 0)

  if !use_noncoincident_value
    # Get array of coincident internal gain
    thermal_zone.spaces.each do |space|
      load_hrs = space_internal_load_annual_array(model, space, use_noncoincident_value)
      (0..8759).each do |ihr|
        load_hrs_sum[ihr] += load_hrs[ihr]
      end
    end
    load_w = load_hrs_sum.max
  else
    # Get the non-coincident sum of peak internal gains
    thermal_zone.spaces.each do |space|
      load_w += space_internal_load_annual_array(model, space, use_noncoincident_value)
    end
  end

  return load_w
end
thermal_zone_prm_baseline_cooling_design_supply_temperature(thermal_zone) click to toggle source

Calculate the cooling supply temperature based on the specified delta-T. Delta-T is calculated based on the highest value found in the cooling setpoint schedule.

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @return [Double] the design heating supply temperature, in degrees Celsius @todo Exception: 17F delta-T for labs

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 398
def thermal_zone_prm_baseline_cooling_design_supply_temperature(thermal_zone)
  setpoint_c = nil

  # Setpoint schedule
  tstat = thermal_zone.thermostatSetpointDualSetpoint
  if tstat.is_initialized
    tstat = tstat.get
    setpoint_sch = tstat.coolingSetpointTemperatureSchedule
    if setpoint_sch.is_initialized
      setpoint_sch = setpoint_sch.get
      if setpoint_sch.to_ScheduleRuleset.is_initialized
        setpoint_sch = setpoint_sch.to_ScheduleRuleset.get
        setpoint_c = OpenstudioStandards::Schedules.schedule_ruleset_get_min_max(setpoint_sch)['min']
      elsif setpoint_sch.to_ScheduleConstant.is_initialized
        setpoint_sch = setpoint_sch.to_ScheduleConstant.get
        setpoint_c = OpenstudioStandards::Schedules.schedule_constant_get_min_max(setpoint_sch)['min']
      elsif setpoint_sch.to_ScheduleCompact.is_initialized
        setpoint_sch = setpoint_sch.to_ScheduleCompact.get
        setpoint_c = OpenstudioStandards::Schedules.schedule_compact_get_min_max(setpoint_sch)['min']
      end
    end
  end

  # If the cooling setpoint could not be determined
  # return the current design cooling temperature
  if setpoint_c.nil?
    setpoint_c = thermal_zone.sizingZone.zoneCoolingDesignSupplyAirTemperature
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Standards.ThermalZone', "For #{thermal_zone.name}: could not determine min cooling setpoint.  Design cooling SAT will be #{OpenStudio.convert(setpoint_c, 'C', 'F').get.round} F from proposed model.")
    return setpoint_c
  end

  # If the cooling setpoint was set very high so that
  # cooling equipment never comes on
  # return the current design cooling temperature
  if setpoint_c > OpenStudio.convert(91, 'F', 'C').get
    setpoint_f = OpenStudio.convert(setpoint_c, 'C', 'F').get
    new_setpoint_c = thermal_zone.sizingZone.zoneCoolingDesignSupplyAirTemperature
    new_setpoint_f = OpenStudio.convert(new_setpoint_c, 'C', 'F').get
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Standards.ThermalZone', "For #{thermal_zone.name}: max cooling setpoint in proposed model was #{setpoint_f.round} F.  20 F SAT delta-T from this point is unreasonable. Design cooling SAT will be #{new_setpoint_f.round} F from proposed model.")
    return new_setpoint_c
  end

  # Subtract 20F delta-T
  delta_t_r = 20
  if /prm/i =~ template # avoid affecting previous PRM tests
    # For labs, substract 17 delta-T; otherwise, substract 20 delta-T
    thermal_zone.spaces.each do |space|
      space_std_type = space.spaceType.get.standardsSpaceType.get
      if space_std_type == 'laboratory'
        delta_t_r = 17
      end
    end
  end

  delta_t_k = OpenStudio.convert(delta_t_r, 'R', 'K').get

  sat_c = setpoint_c - delta_t_k # Subtract for cooling

  return sat_c
end
thermal_zone_prm_baseline_heating_design_supply_temperature(thermal_zone) click to toggle source

Calculate the heating supply temperature based on the# specified delta-T. Delta-T is calculated based on the highest value found in the heating setpoint schedule.

@param thermal_zone [OpenStudio::Model::ThermalZone] thermal zone @return [Double] the design heating supply temperature, in degrees Celsius @todo Exception: 17F delta-T for labs

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 330
def thermal_zone_prm_baseline_heating_design_supply_temperature(thermal_zone)
  unit_heater_sup_temp = thermal_zone_prm_unitheater_design_supply_temperature(thermal_zone)
  unless unit_heater_sup_temp.nil?
    return unit_heater_sup_temp
  end

  setpoint_c = nil

  # Setpoint schedule
  tstat = thermal_zone.thermostatSetpointDualSetpoint
  if tstat.is_initialized
    tstat = tstat.get
    setpoint_sch = tstat.heatingSetpointTemperatureSchedule
    if setpoint_sch.is_initialized
      setpoint_sch = setpoint_sch.get
      if setpoint_sch.to_ScheduleRuleset.is_initialized
        setpoint_sch = setpoint_sch.to_ScheduleRuleset.get
        setpoint_c = OpenstudioStandards::Schedules.schedule_ruleset_get_min_max(setpoint_sch)['max']
      elsif setpoint_sch.to_ScheduleConstant.is_initialized
        setpoint_sch = setpoint_sch.to_ScheduleConstant.get
        setpoint_c = OpenstudioStandards::Schedules.schedule_constant_get_min_max(setpoint_sch)['max']
      elsif setpoint_sch.to_ScheduleCompact.is_initialized
        setpoint_sch = setpoint_sch.to_ScheduleCompact.get
        setpoint_c = OpenstudioStandards::Schedules.schedule_compact_get_min_max(setpoint_sch)['max']
      end
    end
  end

  # If the heating setpoint could not be determined
  # return the current design heating temperature
  if setpoint_c.nil?
    setpoint_c = thermal_zone.sizingZone.zoneHeatingDesignSupplyAirTemperature
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Standards.ThermalZone', "For #{thermal_zone.name}: could not determine max heating setpoint.  Design heating SAT will be #{OpenStudio.convert(setpoint_c, 'C', 'F').get.round} F from proposed model.")
    return setpoint_c
  end

  # If the heating setpoint was set very low so that
  # heating equipment never comes on
  # return the current design heating temperature
  if setpoint_c < OpenStudio.convert(41, 'F', 'C').get
    setpoint_f = OpenStudio.convert(setpoint_c, 'C', 'F').get
    new_setpoint_c = thermal_zone.sizingZone.zoneHeatingDesignSupplyAirTemperature
    new_setpoint_f = OpenStudio.convert(new_setpoint_c, 'C', 'F').get
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.Standards.ThermalZone', "For #{thermal_zone.name}: max heating setpoint in proposed model was #{setpoint_f.round} F.  20 F SAT delta-T from this point is unreasonable. Design heating SAT will be #{new_setpoint_f.round} F from proposed model.")
    return new_setpoint_c
  end

  # Add 20F delta-T
  delta_t_r = 20

  new_delta_t = thermal_zone_prm_lab_delta_t(thermal_zone)
  unless new_delta_t.nil?
    delta_t_r = new_delta_t
  end

  delta_t_k = OpenStudio.convert(delta_t_r, 'R', 'K').get

  sat_c = setpoint_c + delta_t_k # Add for heating

  return sat_c
end
thermal_zone_prm_lab_delta_t(thermal_zone) click to toggle source

Specify supply to room delta for laboratory spaces based on 90.1 Appendix G Exception to G3.1.2.8.1 (implementation in PRM subclass)

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 824
def thermal_zone_prm_lab_delta_t(thermal_zone)
  return nil
end
thermal_zone_prm_unitheater_design_supply_temperature(thermal_zone) click to toggle source

Specify supply air temperature setpoint for unit heaters based on 90.1 Appendix G G3.1.2.8.2 (implementation in PRM subclass)

# File lib/openstudio-standards/standards/Standards.ThermalZone.rb, line 819
def thermal_zone_prm_unitheater_design_supply_temperature(thermal_zone)
  return nil
end
true?(obj) click to toggle source
# File lib/openstudio-standards/prototypes/common/objects/Prototype.utilities.rb, line 883
def true?(obj)
  obj.to_s.downcase == 'true'
end
validate_initial_model(model) click to toggle source

validate that model contains objects

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if valid, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5432
def validate_initial_model(model)
  is_valid = true
  if model.getBuildingStorys.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Please assign Spaces to BuildingStorys the geometry model.')
    is_valid = false
  end
  if model.getThermalZones.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Please assign Spaces to ThermalZones the geometry model.')
    is_valid = false
  end
  if model.getBuilding.standardsNumberOfStories.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Please define Building.standardsNumberOfStories the geometry model.')
    is_valid = false
  end
  if model.getBuilding.standardsNumberOfAboveGroundStories.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', 'Please define Building.standardsNumberOfAboveStories in the geometry model.')
    is_valid = false
  end

  if @space_type_map.nil? || @space_type_map.empty?
    @space_type_map = get_space_type_maps_from_model(model)
    if @space_type_map.nil? || @space_type_map.empty?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please assign SpaceTypes in the geometry model or in standards database #{@space_type_map}.")
      is_valid = false
    else
      @space_type_map = @space_type_map.sort.to_h
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Loaded space type map from model')
    end
  end

  # ensure that model is intersected correctly.
  model.getSpaces.each { |space1| model.getSpaces.each { |space2| space1.intersectSurfaces(space2) } }
  # Get multipliers from TZ in model. Need this for HVAC contruction.
  @space_multiplier_map = {}
  model.getSpaces.sort.each do |space|
    @space_multiplier_map[space.name.get] = space.multiplier if space.multiplier > 1
  end
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', 'Finished adding geometry')
  unless @space_multiplier_map.empty?
    OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Found multipliers for space #{@space_multiplier_map}")
  end
  return is_valid
end
water_heater_convert_energy_factor_to_thermal_efficiency_and_ua(fuel_type, energy_factor, capacity_btu_per_hr) click to toggle source

Convert Energy Factor (EF) to Thermal Efficiency and storage tank UA

@param fuel_type [String] water heater fuel type @param energy_factor [Float] water heater Energy Factor (EF) @param capacity_btu_per_hr [Float] water heater capacity in Btu/h @return [Array] returns water heater thermal efficiency and storage tank UA

# File lib/openstudio-standards/standards/Standards.WaterHeaterMixed.rb, line 350
def water_heater_convert_energy_factor_to_thermal_efficiency_and_ua(fuel_type, energy_factor, capacity_btu_per_hr)
  # Calculate the skin loss coefficient (UA)
  # differently depending on the fuel type
  if fuel_type == 'Electricity'
    # Fixed water heater efficiency per PNNL
    water_heater_efficiency = 1.0
    ua_btu_per_hr_per_f = (41_094 * (1 / energy_factor - 1)) / (24 * 67.5)
  elsif fuel_type == 'NaturalGas'
    # Fixed water heater thermal efficiency per PNNL
    water_heater_efficiency = 0.82
    # Calculate the Recovery Efficiency (RE)
    # based on a fixed capacity of 75,000 Btu/hr
    # and a fixed volume of 40 gallons by solving
    # this system of equations:
    # ua = (1/.95-1/re)/(67.5*(24/41094-1/(re*cap)))
    # 0.82 = (ua*67.5+cap*re)/cap
    # Solutions to the system of equations were determined
    # for discrete values of Energy Factor (EF) and modeled using a regression
    recovery_efficiency = -0.1137 * energy_factor**2 + 0.1997 * energy_factor + 0.731
    # Calculate the skin loss coefficient (UA)
    # Input capacity is assumed to be the output capacity
    # divided by a burner efficiency of 80%
    ua_btu_per_hr_per_f = (water_heater_efficiency - recovery_efficiency) * capacity_btu_per_hr / 0.8 / 67.5
  end

  return water_heater_efficiency, ua_btu_per_hr_per_f
end
water_heater_convert_uniform_energy_factor_to_energy_factor(water_heater_mixed, fuel_type, uniform_energy_factor, capacity_btu_per_hr, volume_gal) click to toggle source

Convert Uniform Energy Factor (UEF) to Energy Factor (EF)

@param water_heater_mixed [OpenStudio::Model::WaterHeaterMixed] water heater mixed object @param fuel_type [String] water heater fuel type @param uniform_energy_factor [Float] water heater Uniform Energy Factor (UEF) @param capacity_btu_per_hr [Float] water heater capacity @param volume_gal [Float] water heater storage volume in gallons @return [Float] returns Energy Factor (EF)

# File lib/openstudio-standards/standards/Standards.WaterHeaterMixed.rb, line 320
def water_heater_convert_uniform_energy_factor_to_energy_factor(water_heater_mixed, fuel_type, uniform_energy_factor, capacity_btu_per_hr, volume_gal)
  # Get water heater sub type
  sub_type = water_heater_determine_sub_type(fuel_type, capacity_btu_per_hr, volume_gal)

  # source: RESNET, https://www.resnet.us/wp-content/uploads/RESNET-EF-Calculator-2017.xlsx
  if sub_type.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.WaterHeaterMixed', "No sub type identified for #{water_heater_mixed.name}, Energy Factor (EF) = Uniform Energy Factor (UEF) is assumed.")
    return uniform_energy_factor
  elsif sub_type == 'consumer_storage' && fuel_type == 'NaturalGas'
    return 0.9066 * uniform_energy_factor + 0.0711
  elsif sub_type == 'consumer_storage' && fuel_type == 'Electricity'
    return 2.4029 * uniform_energy_factor - 1.2844
  elsif sub_type == 'residential_duty' && (fuel_type == 'NaturalGas' || fuel_type == 'Oil')
    return 1.0005 * uniform_energy_factor + 0.0019
  elsif sub_type == 'residential_duty' && fuel_type == 'Electricity'
    return 1.0219 * uniform_energy_factor - 0.0025
  elsif sub_type == 'instantaneous'
    return uniform_energy_factor
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.WaterHeaterMixed', "Invalid sub_type for #{water_heater_mixed.name}, Energy Factor (EF) = Uniform Energy Factor (UEF) is assumed.")
    return uniform_energy_factor
  end
end
water_heater_determine_sub_type(fuel_type, capacity_btu_per_hr, volume_gal) click to toggle source

Get water heater sub type

@param fuel_type [String] water heater fuel type @param capacity_btu_per_hr [Float] water heater capacity @param volume_gal [Float] water heater storage volume in gallons @return [String] returns water heater sub type

# File lib/openstudio-standards/standards/Standards.WaterHeaterMixed.rb, line 291
def water_heater_determine_sub_type(fuel_type, capacity_btu_per_hr, volume_gal)
  sub_type = nil
  capacity_w = OpenStudio.convert(capacity_btu_per_hr, 'Btu/hr', 'W').get
  # source: https://energycodeace.com/site/custom/public/reference-ace-2019/index.html#!Documents/52residentialwaterheatingequipment.htm
  if fuel_type == 'NaturalGas' && capacity_btu_per_hr <= 75_000 && (volume_gal >= 20 && volume_gal <= 100)
    sub_type = 'consumer_storage'
  elsif fuel_type == 'Electricity' && capacity_w <= 12_000 && (volume_gal >= 20 && volume_gal <= 120)
    sub_type = 'consumer_storage'
  elsif fuel_type == 'NaturalGas' && capacity_btu_per_hr < 105_000 && volume_gal < 120
    sub_type = 'residential_duty'
  elsif fuel_type == 'Oil' && capacity_btu_per_hr < 140_000 && volume_gal < 120
    sub_type = 'residential_duty'
  elsif fuel_type == 'Electricity' && capacity_w < 58_600 && volume_gal <= 2
    sub_type = 'residential_duty'
  elsif volume_gal <= 2
    sub_type = 'instantaneous'
  end

  return sub_type
end
water_heater_mixed_additional_search_criteria(water_heater_mixed, search_criteria) click to toggle source

Add additional search criteria for water heater lookup efficiency.

@param water_heater_mixed [OpenStudio::Model::WaterHeaterMixed] water heater mixed object @param search_criteria [Hash] search criteria for looking up water heater data @return [Hash] updated search criteria

# File lib/openstudio-standards/standards/Standards.WaterHeaterMixed.rb, line 383
def water_heater_mixed_additional_search_criteria(water_heater_mixed, search_criteria)
  return search_criteria
end
water_heater_mixed_apply_efficiency(water_heater_mixed) click to toggle source

Applies the standard efficiency ratings and typical losses and paraisitic loads to this object. Efficiency and skin loss coefficient (UA) Per PNNL www.energycodes.gov/sites/default/files/documents/PrototypeModelEnhancements_2014_0.pdf Appendix A: Service Water Heating

@param water_heater_mixed [OpenStudio::Model::WaterHeaterMixed] water heater mixed object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.WaterHeaterMixed.rb, line 11
def water_heater_mixed_apply_efficiency(water_heater_mixed)
  # @todo remove this once workaround for HPWHs is removed
  if water_heater_mixed.partLoadFactorCurve.is_initialized
    if water_heater_mixed.partLoadFactorCurve.get.name.get.include?('HPWH_COP')
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.WaterHeaterMixed', "For #{water_heater_mixed.name}, the workaround for HPWHs has been applied, efficiency will not be changed.")
      return true
    end
  end

  # get number of water heaters
  if water_heater_mixed.additionalProperties.getFeatureAsInteger('component_quantity').is_initialized
    comp_qty = water_heater_mixed.additionalProperties.getFeatureAsInteger('component_quantity').get
  else
    comp_qty = 1
  end

  # Get the capacity of the water heater
  # @todo add capability to pull autosized water heater capacity
  # if the Sizing:WaterHeater object is ever implemented in OpenStudio.
  capacity_w = water_heater_mixed.heaterMaximumCapacity
  if capacity_w.empty?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.WaterHeaterMixed', "For #{water_heater_mixed.name}, cannot find capacity, standard will not be applied.")
    return false
  else
    capacity_w = capacity_w.get / comp_qty
  end
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get

  # Get the volume of the water heater
  # @todo add capability to pull autosized water heater volume
  # if the Sizing:WaterHeater object is ever implemented in OpenStudio.
  volume_m3 = water_heater_mixed.tankVolume
  if volume_m3.empty?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.WaterHeaterMixed', "For #{water_heater_mixed.name}, cannot find volume, standard will not be applied.")
    return false
  else
    volume_m3 = @instvarbuilding_type == 'MidriseApartment' ? volume_m3.get / 23 : volume_m3.get / comp_qty
  end
  volume_gal = OpenStudio.convert(volume_m3, 'm^3', 'gal').get

  # Get the heater fuel type
  fuel_type = water_heater_mixed.heaterFuelType
  unless fuel_type == 'NaturalGas' || fuel_type == 'Electricity'
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.WaterHeaterMixed', "For #{water_heater_mixed.name}, fuel type of #{fuel_type} is not yet supported, standard will not be applied.")
  end

  wh_props = water_heater_mixed_get_efficiency_requirement(water_heater_mixed, fuel_type, capacity_btu_per_hr, volume_gal)
  return false if wh_props == {}

  # Calculate the water heater efficiency and
  # skin loss coefficient (UA) using different methods,
  # depending on the metrics specified by the standard
  water_heater_efficiency = nil
  ua_btu_per_hr_per_f = nil

  if wh_props['thermal_efficiency'] && !wh_props['standby_loss_capacity_allowance']
    thermal_efficiency = wh_props['thermal_efficiency']
    water_heater_efficiency = thermal_efficiency
    # Fixed UA
    ua_btu_per_hr_per_f = 11.37
  end

  # Typically specified this way for small electric water heaters
  # and small natural gas water heaters
  if wh_props['energy_factor_base'] && wh_props['energy_factor_volume_derate']
    # Calculate the energy factor (EF)
    base_energy_factor = wh_props['energy_factor_base']
    vol_drt = wh_props['energy_factor_volume_derate']
    energy_factor = base_energy_factor - (vol_drt * volume_gal)
    water_heater_efficiency, ua_btu_per_hr_per_f = water_heater_convert_energy_factor_to_thermal_efficiency_and_ua(fuel_type, energy_factor, capacity_btu_per_hr)
    # Two booster water heaters
    ua_btu_per_hr_per_f = water_heater_mixed.name.to_s.include?('Booster') ? ua_btu_per_hr_per_f * 2 : ua_btu_per_hr_per_f
  end

  if (wh_props['uniform_energy_factor_base'] && wh_props['uniform_energy_factor_volume_allowance']) || wh_props['uniform_energy_factor']
    if wh_props['uniform_energy_factor']
      uniform_energy_factor = wh_props['uniform_energy_factor']
    else
      base_uniform_energy_factor = wh_props['uniform_energy_factor_base']
      vol_drt = wh_props['uniform_energy_factor_volume_allowance']
      uniform_energy_factor = base_uniform_energy_factor - (vol_drt * volume_gal)
    end
    energy_factor = water_heater_convert_uniform_energy_factor_to_energy_factor(water_heater_mixed, fuel_type, uniform_energy_factor, capacity_btu_per_hr, volume_gal)
    water_heater_efficiency, ua_btu_per_hr_per_f = water_heater_convert_energy_factor_to_thermal_efficiency_and_ua(fuel_type, energy_factor, capacity_btu_per_hr)
    # Two booster water heaters
    ua_btu_per_hr_per_f = water_heater_mixed.name.to_s.include?('Booster') ? ua_btu_per_hr_per_f * 2 : ua_btu_per_hr_per_f
  end

  # Typically specified this way for large electric water heaters
  if wh_props['standby_loss_base'] && (wh_props['standby_loss_volume_allowance'] || wh_props['standby_loss_square_root_volume_allowance'])
    # Fixed water heater efficiency per PNNL
    water_heater_efficiency = 1.0
    # Calculate the max allowable standby loss (SL)
    sl_base = wh_props['standby_loss_base']
    if wh_props['standby_loss_square_root_volume_allowance']
      sl_drt = wh_props['standby_loss_square_root_volume_allowance']
      sl_btu_per_hr = sl_base + (sl_drt * Math.sqrt(volume_gal))
    else # standby_loss_volume_allowance
      sl_drt = wh_props['standby_loss_volume_allowance']
      sl_btu_per_hr = sl_base + (sl_drt * volume_gal)
    end
    # Calculate the skin loss coefficient (UA)
    ua_btu_per_hr_per_f = @instvarbuilding_type == 'MidriseApartment' ? sl_btu_per_hr / 70 * 23 :  sl_btu_per_hr / 70
    ua_btu_per_hr_per_f = water_heater_mixed.name.to_s.include?('Booster') ? ua_btu_per_hr_per_f * 2 : ua_btu_per_hr_per_f
  end

  # Typically specified this way for newer large electric water heaters
  if wh_props['hourly_loss_base'] && wh_props['hourly_loss_volume_allowance']
    # Fixed water heater efficiency per PNNL
    water_heater_efficiency = 1.0
    # Calculate the percent loss per hr
    hr_loss_base = wh_props['hourly_loss_base']
    hr_loss_allow = wh_props['hourly_loss_volume_allowance']
    hrly_loss_pct = hr_loss_base + hr_loss_allow / volume_gal
    # Convert to Btu/hr, assuming:
    # Water at 120F, density = 8.25 lb/gal
    # 1 Btu to raise 1 lb of water 1 F
    # Therefore 8.25 Btu / gal of water * deg F
    # 70F delta-T between water and zone
    hrly_loss_btu_per_hr = (hrly_loss_pct / 100) * volume_gal * 8.25 * 70
    # Calculate the skin loss coefficient (UA)
    ua_btu_per_hr_per_f = hrly_loss_btu_per_hr / 70
  end

  # Typically specified this way for large natural gas water heaters
  if wh_props['standby_loss_capacity_allowance'] && (wh_props['standby_loss_volume_allowance'] || wh_props['standby_loss_square_root_volume_allowance']) && wh_props['thermal_efficiency']
    sl_cap_adj = wh_props['standby_loss_capacity_allowance']
    if !wh_props['standby_loss_volume_allowance'].nil?
      sl_vol_drt = wh_props['standby_loss_volume_allowance']
    elsif !wh_props['standby_loss_square_root_volume_allowance'].nil?
      sl_vol_drt = wh_props['standby_loss_square_root_volume_allowance']
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.WaterHeaterMixed', "For #{water_heater_mixed.name}, could not retrieve the standby loss volume allowance.")
      return false
    end
    et = wh_props['thermal_efficiency']
    # Estimate storage tank volume
    tank_volume = volume_gal > 100 ? (volume_gal - 100).round(0) : 0
    wh_tank_volume = volume_gal > 100 ? 100 : volume_gal
    # SL Storage Tank: polynomial regression based on a set of manufacturer data
    sl_tank = 0.0000005 * tank_volume**3 - 0.001 * tank_volume**2 + 1.3519 * tank_volume + 64.456 # in Btu/h
    # Calculate the max allowable standby loss (SL)
    # Output capacity is assumed to be 10 * Tank volume
    # Input capacity = Output capacity / Et
    p_on = capacity_btu_per_hr / et
    sl_btu_per_hr = p_on / sl_cap_adj + sl_vol_drt * Math.sqrt(wh_tank_volume) + sl_tank
    # Calculate the skin loss coefficient (UA)
    ua_btu_per_hr_per_f = (sl_btu_per_hr * et) / 70
    # Calculate water heater efficiency
    water_heater_efficiency = (ua_btu_per_hr_per_f * 70 + p_on * et) / p_on
  end

  # Ensure that efficiency and UA were both set\
  if water_heater_efficiency.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.WaterHeaterMixed', "For #{water_heater_mixed.name}, cannot calculate efficiency, cannot apply efficiency standard.")
    return false
  end

  if ua_btu_per_hr_per_f.nil?
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.WaterHeaterMixed', "For #{water_heater_mixed.name}, cannot calculate UA, cannot apply efficiency standard.")
    return false
  end

  # Convert to SI
  ua_w_per_k = OpenStudio.convert(ua_btu_per_hr_per_f, 'Btu/hr*R', 'W/K').get
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.WaterHeaterMixed', "For #{water_heater_mixed.name}, skin-loss UA = #{ua_w_per_k} W/K.")

  # Set the water heater properties
  # Efficiency
  water_heater_mixed.setHeaterThermalEfficiency(water_heater_efficiency)
  # Skin loss
  water_heater_mixed.setOffCycleLossCoefficienttoAmbientTemperature(ua_w_per_k)
  water_heater_mixed.setOnCycleLossCoefficienttoAmbientTemperature(ua_w_per_k)
  # @todo Parasitic loss (pilot light)
  # PNNL document says pilot lights were removed, but IDFs
  # still have the on/off cycle parasitic fuel consumptions filled in
  water_heater_mixed.setOnCycleParasiticFuelType(fuel_type)
  # self.setOffCycleParasiticFuelConsumptionRate(??)
  water_heater_mixed.setOnCycleParasiticHeatFractiontoTank(0)
  water_heater_mixed.setOffCycleParasiticFuelType(fuel_type)
  # self.setOffCycleParasiticFuelConsumptionRate(??)
  water_heater_mixed.setOffCycleParasiticHeatFractiontoTank(0)

  # Append the name with standards information
  water_heater_mixed.setName("#{water_heater_mixed.name} #{water_heater_efficiency.round(3)} Therm Eff")
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.WaterHeaterMixed', "For #{template}: #{water_heater_mixed.name}; thermal efficiency = #{water_heater_efficiency.round(3)}, skin-loss UA = #{ua_btu_per_hr_per_f.round}Btu/hr-R")

  return true
end
water_heater_mixed_apply_prm_baseline_fuel_type(water_heater_mixed, building_type) click to toggle source

Applies the correct fuel type for the water heaters in the baseline model. For most standards and for most building types, the baseline uses the same fuel type as the proposed.

@param water_heater_mixed [OpenStudio::Model::WaterHeaterMixed] water heater mixed object @param building_type [String] the building type @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.WaterHeaterMixed.rb, line 258
def water_heater_mixed_apply_prm_baseline_fuel_type(water_heater_mixed, building_type)
  # baseline is same as proposed per Table G3.1 item 11.b
  return true # Do nothing
end
water_heater_mixed_find_capacity(water_heater_mixed) click to toggle source

Finds capacity in Btu/hr

@param water_heater_mixed [OpenStudio::Model::WaterHeaterMixed] water heater mixed object @return [Double] capacity in Btu/hr to be used for find object

# File lib/openstudio-standards/standards/Standards.WaterHeaterMixed.rb, line 267
def water_heater_mixed_find_capacity(water_heater_mixed)
  # Get the coil capacity
  capacity_w = nil
  if water_heater_mixed.heaterMaximumCapacity.is_initialized
    capacity_w = water_heater_mixed.heaterMaximumCapacity.get
  elsif water_heater_mixed.autosizedHeaterMaximumCapacity.is_initialized
    capacity_w = water_heater_mixed.autosizedHeaterMaximumCapacity.get
  else
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.WaterHeaterMixed', "For #{water_heater_mixed.name} capacity is not available.")
    return false
  end

  # Convert capacity to Btu/hr
  capacity_btu_per_hr = OpenStudio.convert(capacity_w, 'W', 'Btu/hr').get

  return capacity_btu_per_hr
end
water_heater_mixed_get_efficiency_requirement(water_heater_mixed, fuel_type, capacity_btu_per_hr, volume_gal) click to toggle source

@param water_heater_mixed [OpenStudio::Model::WaterHeaterMixed] OpenStudio WaterHeaterMixed object @param fuel_type [Float] water heater fuel type @param capacity_btu_per_hr [Float] water heater capacity in Btu/h @param volume_gal [Float] water heater gallons of storage @return [Hash] returns a hash wwith the applicable efficiency requirements

# File lib/openstudio-standards/standards/Standards.WaterHeaterMixed.rb, line 206
def water_heater_mixed_get_efficiency_requirement(water_heater_mixed, fuel_type, capacity_btu_per_hr, volume_gal)
  # Get the water heater properties
  search_criteria = {}
  search_criteria['template'] = template
  search_criteria['fuel_type'] = fuel_type
  search_criteria['equipment_type'] = 'Storage Water Heaters'

  # Search base on capacity first
  wh_props_capacity = model_find_objects(standards_data['water_heaters'], search_criteria, capacity_btu_per_hr)
  wh_props_capacity_and_volume = model_find_objects(standards_data['water_heaters'], search_criteria, capacity_btu_per_hr, nil, nil, nil, nil, volume_gal.round(0))
  wh_props_capacity_and_capacity_btu_per_hr = model_find_objects(standards_data['water_heaters'], search_criteria, capacity_btu_per_hr, nil, nil, nil, nil, nil, capacity_btu_per_hr)
  wh_props_capacity_and_volume_and_capacity_per_volume = model_find_objects(standards_data['water_heaters'], search_criteria, capacity_btu_per_hr, nil, nil, nil, nil, volume_gal, capacity_btu_per_hr / volume_gal)

  # We consider that the lookup is successful if only one set of record is returned
  if wh_props_capacity.size == 1
    wh_props = wh_props_capacity[0]
  elsif wh_props_capacity_and_volume.size == 1
    wh_props = wh_props_capacity_and_volume[0]
  elsif wh_props_capacity_and_capacity_btu_per_hr == 1
    wh_props = wh_props_capacity_and_capacity_btu_per_hr[0]
  elsif wh_props_capacity_and_volume_and_capacity_per_volume == 1
    wh_props = wh_props_capacity_and_volume_and_capacity_per_volume[0]
  else
    # Search again with additional criteria
    search_criteria = water_heater_mixed_additional_search_criteria(water_heater_mixed, search_criteria)
    wh_props_capacity = model_find_objects(standards_data['water_heaters'], search_criteria, capacity_btu_per_hr)
    wh_props_capacity_and_volume = model_find_objects(standards_data['water_heaters'], search_criteria, capacity_btu_per_hr, nil, nil, nil, nil, volume_gal.round(0))
    wh_props_capacity_and_capacity_btu_per_hr = model_find_objects(standards_data['water_heaters'], search_criteria, capacity_btu_per_hr, nil, nil, nil, nil, nil, capacity_btu_per_hr)
    wh_props_capacity_and_volume_and_capacity_per_volume = model_find_objects(standards_data['water_heaters'], search_criteria, capacity_btu_per_hr, nil, nil, nil, nil, volume_gal, capacity_btu_per_hr / volume_gal)
    if wh_props_capacity.size == 1
      wh_props = wh_props_capacity[0]
    elsif wh_props_capacity_and_volume.size == 1
      wh_props = wh_props_capacity_and_volume[0]
    elsif wh_props_capacity_and_capacity_btu_per_hr == 1
      wh_props = wh_props_capacity_and_capacity_btu_per_hr[0]
    elsif wh_props_capacity_and_volume_and_capacity_per_volume == 1
      wh_props = wh_props_capacity_and_volume_and_capacity_per_volume[0]
    else
      return {}
    end
  end

  return wh_props
end
zone_hvac_component_apply_prm_baseline_fan_power(zone_hvac_component) click to toggle source

Sets the fan power of zone level HVAC equipment (Fan coils, Unit Heaters, PTACs, PTHPs, VRF Terminals, WSHPs, ERVs) based on the W/cfm specified in the standard.

@param zone_hvac_component [OpenStudio::Model::ZoneHVACComponent] zone hvac component @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.ZoneHVACComponent.rb, line 18
def zone_hvac_component_apply_prm_baseline_fan_power(zone_hvac_component)
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.ZoneHVACComponent', "Setting fan power for #{zone_hvac_component.name}.")

  # Convert this to the actual class type
  zone_hvac = if zone_hvac_component.to_ZoneHVACFourPipeFanCoil.is_initialized
                zone_hvac_component.to_ZoneHVACFourPipeFanCoil.get
              elsif zone_hvac_component.to_ZoneHVACUnitHeater.is_initialized
                zone_hvac_component.to_ZoneHVACUnitHeater.get
              elsif zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
                zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.get
              elsif zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.is_initialized
                zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.get
              elsif zone_hvac_component.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.is_initialized
                zone_hvac_component.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.get
              elsif zone_hvac_component.to_ZoneHVACWaterToAirHeatPump.is_initialized
                zone_hvac_component.to_ZoneHVACWaterToAirHeatPump.get
              elsif zone_hvac_component.to_ZoneHVACEnergyRecoveryVentilator.is_initialized
                zone_hvac_component.to_ZoneHVACEnergyRecoveryVentilator.get
              end

  # Do nothing for other types of zone HVAC equipment
  if zone_hvac.nil?
    return false
  end

  # Determine the W/cfm
  fan_efficacy_w_per_cfm = zone_hvac_component_prm_baseline_fan_efficacy

  # Convert efficacy to metric
  # 1 cfm = 0.0004719 m^3/s
  fan_efficacy_w_per_m3_per_s = fan_efficacy_w_per_cfm / 0.0004719

  # Get the fan
  fan = if zone_hvac.supplyAirFan.to_FanConstantVolume.is_initialized
          zone_hvac.supplyAirFan.to_FanConstantVolume.get
        elsif zone_hvac.supplyAirFan.to_FanVariableVolume.is_initialized
          zone_hvac.supplyAirFan.to_FanVariableVolume.get
        elsif zone_hvac.supplyAirFan.to_FanOnOff.is_initialized
          zone_hvac.supplyAirFan.to_FanOnOff.get
        end

  # Get the maximum flow rate through the fan
  max_air_flow_rate = nil
  if fan.maximumFlowRate.is_initialized
    max_air_flow_rate = fan.maximumFlowRate.get
  elsif fan.autosizedMaximumFlowRate.is_initialized
    max_air_flow_rate = fan.autosizedMaximumFlowRate.get
  end
  max_air_flow_rate_cfm = OpenStudio.convert(max_air_flow_rate, 'm^3/s', 'ft^3/min').get

  # Set the impeller efficiency
  fan_change_impeller_efficiency(fan, fan_baseline_impeller_efficiency(fan))

  # Set the motor efficiency, preserving the impeller efficency.
  # For zone HVAC fans, a bhp lookup of 0.5bhp is always used because
  # they are assumed to represent a series of small fans in reality.
  fan_apply_standard_minimum_motor_efficiency(fan, fan_brake_horsepower(fan))

  # Calculate a new pressure rise to hit the target W/cfm
  fan_tot_eff = fan.fanEfficiency
  fan_rise_new_pa = fan_efficacy_w_per_m3_per_s * fan_tot_eff
  fan.setPressureRise(fan_rise_new_pa)

  # Calculate the newly set efficacy
  fan_power_new_w = fan_rise_new_pa * max_air_flow_rate / fan_tot_eff
  fan_efficacy_new_w_per_cfm = fan_power_new_w / max_air_flow_rate_cfm
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.ZoneHVACComponent', "For #{zone_hvac_component.name}: fan efficacy set to #{fan_efficacy_new_w_per_cfm.round(2)} W/cfm.")

  return true
end
zone_hvac_component_apply_standard_controls(zone_hvac_component) click to toggle source

Apply all standard required controls to the zone equipment

@param zone_hvac_component [OpenStudio::Model::ZoneHVACComponent] zone hvac component @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.ZoneHVACComponent.rb, line 220
def zone_hvac_component_apply_standard_controls(zone_hvac_component)
  # Vestibule heating control
  if zone_hvac_component_vestibule_heating_control_required?(zone_hvac_component)
    zone_hvac_component_apply_vestibule_heating_control(zone_hvac_component)
  end

  # Convert to objects
  zone_hvac_component = if zone_hvac_component.to_ZoneHVACFourPipeFanCoil.is_initialized
                          zone_hvac_component.to_ZoneHVACFourPipeFanCoil.get
                        elsif zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
                          zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.get
                        elsif zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.is_initialized
                          zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.get
                        end

  # Do nothing for other types of zone HVAC equipment
  if zone_hvac_component.nil?
    return true
  end

  # Standby mode occupancy control
  return true unless zone_hvac_component.thermalZone.empty?

  thermal_zone = zone_hvac_component.thermalZone.get

  standby_mode_spaces = []
  thermal_zone.spaces.sort.each do |space|
    if space_occupancy_standby_mode_required?(space)
      standby_mode_spaces << space
    end
  end
  if !standby_mode_spaces.empty?
    zone_hvac_model_standby_mode_occupancy_control(zone_hvac_component)
  end

  # zone ventilation occupancy control for systems with ventilation
  zone_hvac_component_occupancy_ventilation_control(zone_hvac_component)

  return true
end
zone_hvac_component_apply_vestibule_heating_control(zone_hvac_component) click to toggle source

Turns off vestibule heating below 45F

@param zone_hvac_component [OpenStudio::Model::ZoneHVACComponent] zone hvac component @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.ZoneHVACComponent.rb, line 285
  def zone_hvac_component_apply_vestibule_heating_control(zone_hvac_component)
    # Ensure that the equipment is assigned to a thermal zone
    if zone_hvac_component.thermalZone.empty?
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.model.ZoneHVACComponent', "For #{zone_hvac_component.name}: equipment is not assigned to a thermal zone, cannot apply vestibule heating control.")
      return true
    end

    # Convert this to the actual class type
    zone_hvac = if zone_hvac_component.to_ZoneHVACFourPipeFanCoil.is_initialized
                  zone_hvac_component.to_ZoneHVACFourPipeFanCoil.get
                elsif zone_hvac_component.to_ZoneHVACUnitHeater.is_initialized
                  zone_hvac_component.to_ZoneHVACUnitHeater.get
                elsif zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
                  zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.get
                elsif zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.is_initialized
                  zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.get
                end

    # Do nothing for other types of zone HVAC equipment
    if zone_hvac.nil?
      return true
    end

    # Get the heating coil and fan
    htg_coil = zone_hvac.heatingCoil
    htg_coil = if htg_coil.to_CoilHeatingGas.is_initialized
                 htg_coil.to_CoilHeatingGas.get
               elsif htg_coil.to_CoilHeatingElectric.is_initialized
                 htg_coil.to_CoilHeatingElectric.get
               elsif htg_coil.to_CoilHeatingWater.is_initialized
                 htg_coil.to_CoilHeatingWater.get
               elsif htg_coil.to_CoilHeatingDXSingleSpeed.is_initialized
                 htg_coil.to_CoilHeatingDXSingleSpeed.get
               end

    fan = zone_hvac.supplyAirFan
    fan = if fan.to_FanOnOff.is_initialized
            fan.to_FanOnOff.get
          elsif fan.to_FanConstantVolume.is_initialized
            fan.to_FanConstantVolume.get
          elsif fan.to_FanVariableVolume.is_initialized
            fan.to_FanVariableVolume.get
          end

    # Get existing heater availability schedule if present
    # or create a new one
    avail_sch = nil
    avail_sch_name = 'VestibuleHeaterAvailSch'
    if zone_hvac_component.model.getScheduleConstantByName(avail_sch_name).is_initialized
      avail_sch = zone_hvac_component.model.getScheduleConstantByName(avail_sch_name).get
    else
      avail_sch = OpenStudio::Model::ScheduleConstant.new(zone_hvac_component.model)
      avail_sch.setName(avail_sch_name)
      avail_sch.setValue(1)
    end

    # Replace the existing availabilty schedule with the one
    # that will be controlled via EMS
    htg_coil.setAvailabilitySchedule(avail_sch)
    fan.setAvailabilitySchedule(avail_sch)

    # Clean name of zone HVAC
    equip_name_clean = zone_hvac.name.get.to_s.gsub(/\W/, '').delete('_')
    # If the name starts with a number, prepend with a letter
    if equip_name_clean[0] =~ /[0-9]/
      equip_name_clean = "EQUIP#{equip_name_clean}"
    end

    # Sensors
    # Get existing OAT sensor if present
    oat_db_c_sen = nil
    if zone_hvac_component.model.getEnergyManagementSystemSensorByName('OATVestibule').is_initialized
      oat_db_c_sen = zone_hvac_component.model.getEnergyManagementSystemSensorByName('OATVestibule').get
    else
      oat_db_c_sen = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Site Outdoor Air Drybulb Temperature')
      oat_db_c_sen.setName('OATVestibule')
      oat_db_c_sen.setKeyName('Environment')
    end

    # Actuators
    avail_sch_act = OpenStudio::Model::EnergyManagementSystemActuator.new(avail_sch, 'Schedule:Constant', 'Schedule Value')
    avail_sch_act.setName("#{equip_name_clean}VestHtgAvailSch")

    # Programs
    htg_lim_f = 45
    vestibule_htg_prg = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
    vestibule_htg_prg.setName("#{equip_name_clean}VestHtgPrg")
    vestibule_htg_prg_body = <<-EMS
    IF #{oat_db_c_sen.handle} > #{OpenStudio.convert(htg_lim_f, 'F', 'C').get}
      SET #{avail_sch_act.handle} = 0
    ENDIF
    EMS
    vestibule_htg_prg.setBody(vestibule_htg_prg_body)

    # Program Calling Managers
    vestibule_htg_mgr = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)
    vestibule_htg_mgr.setName("#{equip_name_clean}VestHtgMgr")
    vestibule_htg_mgr.setCallingPoint('BeginTimestepBeforePredictor')
    vestibule_htg_mgr.addProgram(vestibule_htg_prg)

    OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.ZoneHVACComponent', "For #{zone_hvac_component.name}: Vestibule heating control applied, heating disabled below #{htg_lim_f} F.")

    return true
  end
zone_hvac_component_occupancy_ventilation_control(zone_hvac_component) click to toggle source

If the supply air fan operating mode schedule is always off (to follow load), and the zone requires ventilation, override it to follow the zone occupancy schedule

@param zone_hvac_component [OpenStudio::Model::ZoneHVACComponent] zone hvac component @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.ZoneHVACComponent.rb, line 142
def zone_hvac_component_occupancy_ventilation_control(zone_hvac_component)
  ventilation = false
  # Zone HVAC operating schedule if providing ventilation
  # Zone HVAC components return an OptionalSchedule object for supplyAirFanOperatingModeSchedule
  # except for ZoneHVACTerminalUnitVariableRefrigerantFlow which returns a Schedule
  # and starting at 3.5.0, PTAC / PTHP also return a Schedule, optional before that
  existing_sch = nil
  if zone_hvac_component.to_ZoneHVACFourPipeFanCoil.is_initialized
    zone_hvac_component = zone_hvac_component.to_ZoneHVACFourPipeFanCoil.get
    if zone_hvac_component.maximumOutdoorAirFlowRate.is_initialized
      oa_rate = zone_hvac_component.maximumOutdoorAirFlowRate.get
      ventilation = true if oa_rate > 0.0
    end
    ventilation = true if zone_hvac_component.isMaximumOutdoorAirFlowRateAutosized
    fan_op_sch = zone_hvac_component.supplyAirFanOperatingModeSchedule
    existing_sch = fan_op_sch.get if fan_op_sch.is_initialized
  elsif zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
    zone_hvac_component = zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.get
    if zone_hvac_component.outdoorAirFlowRateWhenNoCoolingorHeatingisNeeded.is_initialized
      oa_rate = zone_hvac_component.outdoorAirFlowRateWhenNoCoolingorHeatingisNeeded.get
      ventilation = true if oa_rate > 0.0
    end
    ventilation = true if zone_hvac_component.isOutdoorAirFlowRateWhenNoCoolingorHeatingisNeededAutosized
    fan_op_sch = OpenStudio::Model::OptionalSchedule.new(zone_hvac_component.supplyAirFanOperatingModeSchedule)
    existing_sch = fan_op_sch.get if fan_op_sch.is_initialized
  elsif zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.is_initialized
    zone_hvac_component = zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.get
    if zone_hvac_component.outdoorAirFlowRateWhenNoCoolingorHeatingisNeeded.is_initialized
      oa_rate = zone_hvac_component.outdoorAirFlowRateWhenNoCoolingorHeatingisNeeded.get
      ventilation = true if oa_rate > 0.0
    end
    ventilation = true if zone_hvac_component.isOutdoorAirFlowRateWhenNoCoolingorHeatingisNeededAutosized
    fan_op_sch = OpenStudio::Model::OptionalSchedule.new(zone_hvac_component.supplyAirFanOperatingModeSchedule)
    existing_sch = fan_op_sch.get if fan_op_sch.is_initialized
  elsif zone_hvac_component.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.is_initialized
    zone_hvac_component = zone_hvac_component.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.get
    if zone_hvac_component.outdoorAirFlowRateWhenNoCoolingorHeatingisNeeded.is_initialized
      oa_rate = zone_hvac_component.outdoorAirFlowRateWhenNoCoolingorHeatingisNeeded.get
      ventilation = true if oa_rate > 0.0
    end
    ventilation = true if zone_hvac_component.isOutdoorAirFlowRateWhenNoCoolingorHeatingisNeededAutosized
    existing_sch = zone_hvac_component.supplyAirFanOperatingModeSchedule
  elsif zone_hvac_component.to_ZoneHVACWaterToAirHeatPump.is_initialized
    zone_hvac_component = zone_hvac_component.to_ZoneHVACWaterToAirHeatPump.get
    if zone_hvac_component.outdoorAirFlowRateWhenNoCoolingorHeatingisNeeded.is_initialized
      oa_rate = zone_hvac_component.outdoorAirFlowRateWhenNoCoolingorHeatingisNeeded.get
      ventilation = true if oa_rate > 0.0
    end
    ventilation = true if zone_hvac_component.isOutdoorAirFlowRateWhenNoCoolingorHeatingisNeededAutosized
    fan_op_sch = zone_hvac_component.supplyAirFanOperatingModeSchedule
    existing_sch = fan_op_sch.get if fan_op_sch.is_initialized
  end
  return false unless ventilation

  # if supply air fan operating schedule is always off,
  # override to provide ventilation during occupied hours
  unless existing_sch.nil?
    if existing_sch.name.is_initialized
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.Standards.ZoneHVACComponent', "#{zone_hvac_component.name} has ventilation, and schedule is set to always on; keeping always on schedule.")
      return false if existing_sch.name.get.to_s.downcase.include?('always on discrete') || existing_sch.name.get.to_s.downcase.include?('guestroom_vent_ctrl_sch')
    end
  end

  thermal_zone = zone_hvac_component.thermalZone.get
  occ_threshold = zone_hvac_unoccupied_threshold
  occ_sch = OpenstudioStandards::ThermalZone.thermal_zone_get_occupancy_schedule(thermal_zone,
                                                                                 sch_name: "#{zone_hvac_component.name} Occ Sch",
                                                                                 occupied_percentage_threshold: occ_threshold)
  zone_hvac_component.setSupplyAirFanOperatingModeSchedule(occ_sch)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.Standards.ZoneHVACComponent', "#{zone_hvac_component.name} has ventilation.  Setting fan operating mode schedule to align with zone occupancy schedule.")

  return true
end
zone_hvac_component_prm_baseline_fan_efficacy() click to toggle source

default fan efficiency for small zone hvac fans, in watts per cfm

@return [Double] fan efficiency in watts per cfm

# File lib/openstudio-standards/standards/Standards.ZoneHVACComponent.rb, line 7
def zone_hvac_component_prm_baseline_fan_efficacy
  fan_efficacy_w_per_cfm = 0.3
  return fan_efficacy_w_per_cfm
end
zone_hvac_component_vestibule_heating_control_required?(zone_hvac_component) click to toggle source

Determine if vestibule heating control is required. Defaults to 90.1-2004 through 2010, not required.

@param zone_hvac_component [OpenStudio::Model::ZoneHVACComponent] zone hvac component @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.ZoneHVACComponent.rb, line 266
def zone_hvac_component_vestibule_heating_control_required?(zone_hvac_component)
  vest_htg_control_required = false
  return vest_htg_control_required
end
zone_hvac_get_fan_object(zone_hvac_component) click to toggle source

Get the supply fan object for a zone equipment component @author Doug Maddox, PNNL @param zone_hvac_component [object] @return [object] supply fan of zone equipment component

# File lib/openstudio-standards/standards/Standards.ZoneHVACComponent.rb, line 93
def zone_hvac_get_fan_object(zone_hvac_component)
  zone_hvac = nil
  # Check for any zone equipment type that has a supply fan
  # except EnergyRecoveryVentilator, which is not a primary conditioning system
  zone_hvac = if zone_hvac_component.to_ZoneHVACFourPipeFanCoil.is_initialized
                zone_hvac_component.to_ZoneHVACFourPipeFanCoil.get
              elsif zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.is_initialized
                zone_hvac_component.to_ZoneHVACPackagedTerminalAirConditioner.get
              elsif zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.is_initialized
                zone_hvac_component.to_ZoneHVACPackagedTerminalHeatPump.get
              elsif zone_hvac_component.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.is_initialized
                zone_hvac_component.to_ZoneHVACTerminalUnitVariableRefrigerantFlow.get
              elsif zone_hvac_component.to_ZoneHVACUnitHeater.is_initialized
                zone_hvac_component.to_ZoneHVACUnitHeater.get
              elsif zone_hvac_component.to_ZoneHVACUnitVentilator.is_initialized
                zone_hvac_component.to_ZoneHVACUnitVentilator.get
              elsif zone_hvac_component.to_ZoneHVACWaterToAirHeatPump.is_initialized
                zone_hvac_component.to_ZoneHVACWaterToAirHeatPump.get
              end

  # Get the fan
  if !zone_hvac.nil?
    fan_obj = if zone_hvac.supplyAirFan.to_FanConstantVolume.is_initialized
                zone_hvac.supplyAirFan.to_FanConstantVolume.get
              elsif zone_hvac.supplyAirFan.to_FanVariableVolume.is_initialized
                zone_hvac.supplyAirFan.to_FanVariableVolume.get
              elsif zone_hvac.supplyAirFan.to_FanOnOff.is_initialized
                zone_hvac.supplyAirFan.to_FanOnOff.get
              elsif zone_hvac.supplyAirFan.to_FanSystemModel.is_initialized
                zone_hvac.supplyAirFan.to_FanSystemModel.get
              end
    return fan_obj
  else
    return nil
  end
end
zone_hvac_model_standby_mode_occupancy_control(zone_hvac_component) click to toggle source

Add occupant standby controls to zone equipment Currently, the controls consists of cycling the fan during the occupant standby mode hours

@param zone_hvac_component OpenStudio zonal equipment object @return [Boolean] true if sucessful, false otherwise

# File lib/openstudio-standards/standards/Standards.ZoneHVACComponent.rb, line 277
def zone_hvac_model_standby_mode_occupancy_control(zone_hvac_component)
  return true
end
zone_hvac_unoccupied_threshold() click to toggle source

Default occupancy fraction threshold for determining if the spaces served by the zone hvac are occupied

@return [Double] unoccupied threshold

# File lib/openstudio-standards/standards/Standards.ZoneHVACComponent.rb, line 133
def zone_hvac_unoccupied_threshold
  return 0.15
end

Private Instance Methods

air_loop_hvac_supply_air_temperature_reset_type(air_loop_hvac) click to toggle source

Default SAT reset type

@param air_loop_hvac [OpenStudio::Model::AirLoopHVAC] air loop @return [String] Returns type of SAT reset

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5851
def air_loop_hvac_supply_air_temperature_reset_type(air_loop_hvac)
  return 'warmest_zone'
end
find_lowest_story(model) click to toggle source

Retrieves the lowest story in a model

@param model [OpenStudio::Model::Model] OpenStudio model object @return [OpenStudio::Model::BuildingStory] Lowest story included in the model

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5805
def find_lowest_story(model)
  min_z_story = 1E+10
  lowest_story = nil
  model.getSpaces.sort.each do |space|
    story = space.buildingStory.get
    lowest_story = story if lowest_story.nil?
    space_min_z = OpenstudioStandards::Geometry.building_story_get_minimum_height(story)
    if space_min_z < min_z_story
      min_z_story = space_min_z
      lowest_story = story
    end
  end
  return lowest_story
end
generate_baseline_log(file_directory) click to toggle source

Generate baseline log to a specific file directory @param file_directory [String] file directory @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 6109
def generate_baseline_log(file_directory)
  return true
end
handle_user_input_data(model, climate_zone, sizing_run_dir, default_hvac_building_type, default_wwr_building_type, default_swh_building_type, bldg_type_hvac_zone_hash) click to toggle source

A template method that handles the loading of user input data from multiple sources include data source from:

  1. user data csv files

  2. data from measure and OpenStudio interface

@param [OpenStudio:model:Model] model @param [String] climate_zone @param [String] sizing_run_dir @param [String] default_hvac_building_type @param [String] default_wwr_building_type @param [String] default_swh_building_type @param [Hash] bldg_type_hvac_zone_hash A hash maps building type for hvac to a list of thermal zones @return [Boolean] returns true

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5888
def handle_user_input_data(model, climate_zone, sizing_run_dir, default_hvac_building_type, default_wwr_building_type, default_swh_building_type, bldg_type_hvac_zone_hash)
  return true
end
load_geometry_osm(osm_file) click to toggle source

Loads a osm as a starting point.

@param osm_file [String] path to the .osm file, relative to the /data folder @return [OpenStudio::Model::Model] model object, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5751
def load_geometry_osm(osm_file)
  # Load the geometry .osm from relative to the data folder
  osm_model_path = "../../../data/#{osm_file}"

  # Load the .osm depending on whether running from normal gem location
  # or from the embedded location in the OpenStudio CLI
  if File.dirname(__FILE__)[0] == ':'
    # running from embedded location in OpenStudio CLI
    geom_model_string = load_resource_relative(osm_model_path)
    version_translator = OpenStudio::OSVersion::VersionTranslator.new
    model = version_translator.loadModelFromString(geom_model_string)
  else
    abs_path = File.join(File.dirname(__FILE__), osm_model_path)
    version_translator = OpenStudio::OSVersion::VersionTranslator.new
    model = version_translator.loadModel(abs_path)
  end

  # Check that the model loaded successfully
  if model.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Version translation failed for #{osm_model_path}")
    return false
  end
  model = model.get

  # Check for expected characteristics of geometry model
  if model.getBuildingStorys.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please assign Spaces to BuildingStorys in the geometry model: #{osm_model_path}.")
  end
  if model.getThermalZones.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please assign Spaces to ThermalZones in the geometry model: #{osm_model_path}.")
  end
  if model.getBuilding.standardsNumberOfStories.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please define Building.standardsNumberOfStories in the geometry model #{osm_model_path}.")
  end
  if model.getBuilding.standardsNumberOfAboveGroundStories.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please define Building.standardsNumberOfAboveStories in the geometry model#{osm_model_path}.")
  end

  if @space_type_map.nil? || @space_type_map.empty?
    @space_type_map = get_space_type_maps_from_model(model)
    if @space_type_map.nil? || @space_type_map.empty?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please assign SpaceTypes in the geometry model: #{osm_model_path} or in standards database #{@space_type_map}.")
    else
      @space_type_map = @space_type_map.sort.to_h
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Loaded space type map from osm file: #{osm_model_path}")
    end
  end
  return model
end
load_user_geometry_osm(osm_model_path:) click to toggle source

Loads a geometry osm as a starting point.

@param osm_model_path [String] path to the .osm file, relative to the /data folder @return [OpenStudio::Model::Model] model object

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5710
def load_user_geometry_osm(osm_model_path:)
  version_translator = OpenStudio::OSVersion::VersionTranslator.new
  model = version_translator.loadModel(osm_model_path)

  # Check that the model loaded successfully
  if model.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Version translation failed for #{osm_model_path}")
    return false
  end
  model = model.get

  # Check for expected characteristics of geometry model
  if model.getBuildingStorys.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please assign Spaces to BuildingStorys in the geometry model: #{osm_model_path}.")
  end
  if model.getThermalZones.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please assign Spaces to ThermalZones in the geometry model: #{osm_model_path}.")
  end
  if model.getBuilding.standardsNumberOfStories.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please define Building.standardsNumberOfStories in the geometry model #{osm_model_path}.")
  end
  if model.getBuilding.standardsNumberOfAboveGroundStories.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please define Building.standardsNumberOfAboveStories in the geometry model#{osm_model_path}.")
  end

  if @space_type_map.nil? || @space_type_map.empty?
    @space_type_map = get_space_type_maps_from_model(model)
    if @space_type_map.nil? || @space_type_map.empty?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Please assign SpaceTypes in the geometry model: #{osm_model_path} or in standards database #{@space_type_map}.")
    else
      @space_type_map = @space_type_map.sort.to_h
      OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "Loaded space type map from osm file: #{osm_model_path}")
    end
  end
  return model
end
model_add_reporting_tolerances(model, heating_tolerance_deg_f: 1.0, cooling_tolerance_deg_f: 1.0) click to toggle source

Add reporting tolerances. Default values are based on the suggestions from the PRM-RM.

@param model [OpenStudio::Model::Model] OpenStudio Model @param heating_tolerance_deg_f [Double] Tolerance for time heating setpoint not met in degree F @param cooling_tolerance_deg_f [Double] Tolerance for time cooling setpoint not met in degree F @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 6085
def model_add_reporting_tolerances(model, heating_tolerance_deg_f: 1.0, cooling_tolerance_deg_f: 1.0)
  reporting_tolerances = model.getOutputControlReportingTolerances
  heating_tolerance_deg_c = OpenStudio.convert(heating_tolerance_deg_f, 'R', 'K').get
  cooling_tolerance_deg_c = OpenStudio.convert(cooling_tolerance_deg_f, 'R', 'K').get
  reporting_tolerances.setToleranceforTimeHeatingSetpointNotMet(heating_tolerance_deg_c)
  reporting_tolerances.setToleranceforTimeCoolingSetpointNotMet(cooling_tolerance_deg_c)

  return true
end
model_add_vals_to_sch(model, day_sch, sch_type, values) click to toggle source

Helper method to fill in hourly values

@param model [OpenStudio::Model::Model] OpenStudio model object @param day_sch [OpenStudio::Model::ScheduleDay] schedule day object @param sch_type [String] Constant or Hourly @param values [Array<Double>] @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5559
def model_add_vals_to_sch(model, day_sch, sch_type, values)
  if sch_type == 'Constant'
    day_sch.addValue(OpenStudio::Time.new(0, 24, 0, 0), values[0])
  elsif sch_type == 'Hourly'
    (0..23).each do |i|
      next if values[i] == values[i + 1]

      day_sch.addValue(OpenStudio::Time.new(0, i + 1, 0, 0), values[i])
    end
  else
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.standards.Model', "Schedule type: #{sch_type} is not recognized.  Valid choices are 'Constant' and 'Hourly'.")
  end
end
model_apply_baseline_swh_loops(model, building_type) click to toggle source

Modify the existing service water heating loops to match the baseline required heating type.

@param model [OpenStudio::Model::Model] OpenStudio model object @param building_type [String] the building type @return [Boolean] returns true if successful, false if not @author Julien Marrec

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5579
def model_apply_baseline_swh_loops(model, building_type)
  model.getPlantLoops.sort.each do |plant_loop|
    # Skip non service water heating loops
    next unless plant_loop_swh_loop?(plant_loop)

    # Rename the loop to avoid accidentally hooking up the HVAC systems to this loop later.
    plant_loop.setName('Service Water Heating Loop')

    htg_fuels, combination_system, storage_capacity, total_heating_capacity = plant_loop_swh_system_type(plant_loop)

    # htg_fuels.size == 0 shoudln't happen

    electric = true

    if htg_fuels.include?('NaturalGas') ||
       htg_fuels.include?('Propane') ||
       htg_fuels.include?('PropaneGas') ||
       htg_fuels.include?('FuelOilNo1') ||
       htg_fuels.include?('FuelOilNo2') ||
       htg_fuels.include?('Coal') ||
       htg_fuels.include?('Diesel') ||
       htg_fuels.include?('Gasoline')
      electric = false
    end

    # Per Table G3.1 11.e, if the baseline system was a combination of heating and service water heating,
    # delete all heating equipment and recreate a WaterHeater:Mixed.
    if combination_system
      plant_loop.supplyComponents.each do |component|
        # Get the object type
        obj_type = component.iddObjectType.valueName.to_s
        next if ['OS_Node', 'OS_Pump_ConstantSpeed', 'OS_Pump_VariableSpeed', 'OS_Connector_Splitter', 'OS_Connector_Mixer', 'OS_Pipe_Adiabatic'].include?(obj_type)

        component.remove
      end

      water_heater = OpenStudio::Model::WaterHeaterMixed.new(model)
      water_heater.setName('Baseline Water Heater')
      water_heater.setHeaterMaximumCapacity(total_heating_capacity)
      water_heater.setTankVolume(storage_capacity)
      plant_loop.addSupplyBranchForComponent(water_heater)

      if electric
        # G3.1.11.b: If electric, WaterHeater:Mixed with electric resistance
        water_heater.setHeaterFuelType('Electricity')
        water_heater.setHeaterThermalEfficiency(1.0)
      else
        # @todo for now, just get the first fuel that isn't Electricity
        # A better way would be to count the capacities associated
        # with each fuel type and use the preponderant one
        fuels = htg_fuels - ['Electricity']
        fossil_fuel_type = fuels[0]
        water_heater.setHeaterFuelType(fossil_fuel_type)
        water_heater.setHeaterThermalEfficiency(0.8)
      end
      # If it's not a combination heating and service water heating system
      # just change the fuel type of all water heaters on the system
      # to electric resistance if it's electric
    else
      if electric
        plant_loop.supplyComponents.each do |component|
          next unless component.to_WaterHeaterMixed.is_initialized

          water_heater = component.to_WaterHeaterMixed.get
          # G3.1.11.b: If electric, WaterHeater:Mixed with electric resistance
          water_heater.setHeaterFuelType('Electricity')
          water_heater.setHeaterThermalEfficiency(1.0)
        end
      end
    end
  end

  # Set the water heater fuel types if it's 90.1-2013
  model.getWaterHeaterMixeds.sort.each do |water_heater|
    water_heater_mixed_apply_prm_baseline_fuel_type(water_heater, building_type)
  end

  return true
end
model_apply_constructions(model, climate_zone, wwr_building_type, wwr_info) click to toggle source

Apply the standard construction to each surface in the model, based on the construction type currently assigned.

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 6100
def model_apply_constructions(model, climate_zone, wwr_building_type, wwr_info)
  model_apply_standard_constructions(model, climate_zone, wwr_building_type: nil, wwr_info: {})

  return true
end
model_apply_userdata_outdoor_air(model) click to toggle source
# File lib/openstudio-standards/standards/Standards.Model.rb, line 5514
def model_apply_userdata_outdoor_air(model)
  return true
end
model_determine_baseline_return_air_type(model, baseline_system_type, zones) click to toggle source

Determine the baseline return air type associated with each zone

@param model [OpenStudio::Model::model] OpenStudio model object @param baseline_system_type [String] Baseline system type name @param zones [Array] List of zone associated with a system @return [Array] Array of length 2, the first item is the name

of the plenum zone and the second the return air type
# File lib/openstudio-standards/standards/Standards.Model.rb, line 6022
def model_determine_baseline_return_air_type(model, baseline_system_type, zones)
  return ['', 'ducted_return_or_direct_to_unit'] unless ['PSZ_AC', 'PSZ_HP', 'PVAV_Reheat', 'PVAV_PFP_Boxes', 'VAV_Reheat', 'VAV_PFP_Boxes', 'SZ_VAV', 'SZ_CV'].include?(baseline_system_type)

  zone_return_air_type = {}
  zones.each do |zone|
    if zone.additionalProperties.hasFeature('proposed_model_zone_design_air_flow')
      zone_design_air_flow = zone.additionalProperties.getFeatureAsDouble('proposed_model_zone_design_air_flow').get

      if zone.additionalProperties.hasFeature('return_air_type')
        return_air_type = zone.additionalProperties.getFeatureAsString('return_air_type').get

        if zone_return_air_type.keys.include?(return_air_type)
          zone_return_air_type[return_air_type] += zone_design_air_flow
        else
          zone_return_air_type[return_air_type] = zone_design_air_flow
        end

        if zone.additionalProperties.hasFeature('plenum')
          plenum = zone.additionalProperties.getFeatureAsString('plenum').get

          if zone_return_air_type.keys.include?('plenum')
            if zone_return_air_type['plenum'].keys.include?(plenum)
              zone_return_air_type['plenum'][plenum] += zone_design_air_flow
            end
          else
            zone_return_air_type['plenum'] = { plenum => zone_design_air_flow }
          end
        end
      end
    end
  end

  # Find dominant zone return air type and plenum zone
  # if the return air type is return air plenum
  return_air_types = zone_return_air_type.keys - ['plenum']
  return_air_types_score = 0
  return_air_type = nil
  plenum_score = 0
  plenum = nil
  return_air_types.each do |return_type|
    if zone_return_air_type[return_type] > return_air_types_score
      return_air_type = return_type
      return_air_types_score = zone_return_air_type[return_type]
    end
    if return_air_type == 'return_plenum'
      zone_return_air_type['plenum'].keys.each do |p|
        if zone_return_air_type['plenum'][p] > plenum_score
          plenum = p
          plenum_score = zone_return_air_type['plenum'][p]
        end
      end
    end
  end

  return plenum, return_air_type
end
model_does_require_wwr_adjustment?(wwr_limit, wwr_list) click to toggle source

This function checks whether it is required to adjust the window to wall ratio based on the model WWR and wwr limit. @param wwr_limit [Double] window to wall ratio limit @param wwr_list [Array] list of wwr of zone conditioning category in a building area type category - residential, nonresidential and semiheated @return [Boolean] True, require adjustment, false not require adjustment.

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5522
def model_does_require_wwr_adjustment?(wwr_limit, wwr_list)
  require_adjustment = false
  wwr_list.each do |wwr|
    require_adjustment = true unless wwr > wwr_limit
  end
  return require_adjustment
end
model_evaluate_dcv_requirements(model) click to toggle source

Template method for evaluate DCV requirements in the user model

@param model [OpenStudio::Model::Model] OpenStudio model @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5907
def model_evaluate_dcv_requirements(model)
  return true
end
model_get_bat_wwr_target(bat, wwr_list) click to toggle source

The function is used for codes that requires to adjusted wwr based on building categories for all other types

@param bat [String] building area type category @param wwr_list [Array] list of wwr of zone conditioning category in a building area type category - residential, nonresidential and semiheated @return [Double] return adjusted wwr_limit

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5535
def model_get_bat_wwr_target(bat, wwr_list)
  return 40.0
end
model_get_fan_power_breakdown() click to toggle source

Indicate if fan power breakdown (supply, return, and relief) are needed

@return [Boolean] true if necessary, false otherwise

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5832
def model_get_fan_power_breakdown
  return false
end
model_get_percent_of_surface_range(model, wwr_parameter = {}) click to toggle source

Determine the surface range of a baseline model. The method calculates the window to wall ratio (assuming all spaces are conditioned) and select the range based on the calculated window to wall ratio @param model [OpenStudio::Model::Model] OpenStudio model object @param wwr_parameter [Hash] parameters to choose min and max percent of surfaces,

could be different set in different standard

@return [Hash] Hash of minimum_percent_of_surface and maximum_percent_of_surface

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5843
def model_get_percent_of_surface_range(model, wwr_parameter = {})
  return { 'minimum_percent_of_surface' => nil, 'maximum_percent_of_surface' => nil }
end
model_get_return_plenum_from_system(model, system) click to toggle source

returns the thermal zone that serves as the return plenum

@param model [OpenStudio::Model::Model] OpenStudio model object @param system [Hash] hash of system inputs @return [OpenStudio::Model::ThermalZone] the return plenum thermal zone

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.hvac.rb, line 595
def model_get_return_plenum_from_system(model, system)
  # Find the zone associated with the return plenum space name
  return_plenum = nil

  # Return nil if no return plenum
  return return_plenum if system['return_plenum'].nil?

  # Get the space
  space = model.getSpaceByName(system['return_plenum'])
  if space.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "No space called #{system['return_plenum']} was found in the model, cannot be a return plenum.")
    return return_plenum
  end
  space = space.get

  # Get the space's zone
  zone = space.thermalZone
  if zone.empty?
    OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Space #{space.name} has no thermal zone; cannot be a return plenum.")
    return return_plenum
  end

  return zone.get
end
model_get_zones_from_spaces_on_system(model, system) click to toggle source

returns the thermal zones served by the system

@param model [OpenStudio::Model::Model] OpenStudio model object @param system [Hash] hash of system inputs @return [Array<OpenStudio::Model::ThermalZone>] system thermal zones

# File lib/openstudio-standards/prototypes/common/objects/Prototype.Model.hvac.rb, line 569
def model_get_zones_from_spaces_on_system(model, system)
  # Find all zones associated with these spaces
  thermal_zones = []
  system['space_names'].each do |space_name|
    space = model.getSpaceByName(space_name)
    if space.empty?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "No space called #{space_name} was found in the model, cannot be added to HVAC system.")
      next
    end
    space = space.get
    zone = space.thermalZone
    if zone.empty?
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.model.Model', "Space #{space_name} has no thermal zone; cannot add an HVAC system to this space.")
      next
    end
    thermal_zones << zone.get
  end

  return thermal_zones
end
model_identify_non_mechanically_cooled_systems(model) click to toggle source

Identifies non mechanically cooled (“nmc”) systems, if applicable

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Hash] Zone to nmc system type mapping

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5824
def model_identify_non_mechanically_cooled_systems(model)
  return true
end
model_identify_return_air_type(model) click to toggle source

Identify the return air type associated with each thermal zone

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5934
def model_identify_return_air_type(model)
  # air-loop based system
  model.getThermalZones.each do |zone|
    # Conditioning category won't include indirectly conditioned thermal zones
    cond_cat = thermal_zone_conditioning_category(zone, OpenstudioStandards::Weather.model_get_climate_zone(model))

    # Initialize the return air type
    return_air_type = nil

    # The thermal zone is conditioned by zonal system
    if (cond_cat != 'Unconditioned') && zone.airLoopHVACs.empty?
      return_air_type = 'ducted_return_or_direct_to_unit'
    end

    # Assume that the primary heating and cooling (PHC) system
    # is last in the heating and cooling order (ignore DOAS)
    #
    # Get the heating and cooling PHC components
    heating_equipment = zone.equipmentInHeatingOrder[-1]
    cooling_equipment = zone.equipmentInCoolingOrder[-1]
    if heating_equipment.nil? && cooling_equipment.nil?
      next
    end

    unless heating_equipment.nil?
      if heating_equipment.to_ZoneHVACComponent.is_initialized
        heating_equipment_type = 'ZoneHVACComponent'
      elsif heating_equipment.to_StraightComponent.is_initialized
        heating_equipment_type = 'StraightComponent'
      end
    end
    unless cooling_equipment.nil?
      if cooling_equipment.to_ZoneHVACComponent.is_initialized
        cooling_equipment_type = 'ZoneHVACComponent'
      elsif cooling_equipment.to_StraightComponent.is_initialized
        cooling_equipment_type = 'StraightComponent'
      end
    end

    # Determine return configuration
    if (heating_equipment_type == 'ZoneHVACComponent') && (cooling_equipment_type == 'ZoneHVACComponent')
      return_air_type = 'ducted_return_or_direct_to_unit'
    else
      # Check heating air loop first
      unless heating_equipment.nil?
        if heating_equipment.to_StraightComponent.is_initialized
          air_loop = heating_equipment.to_StraightComponent.get.airLoopHVAC.get
          return_plenum = air_loop_hvac_return_air_plenum(air_loop)
          return_air_type = return_plenum.nil? ? 'ducted_return_or_direct_to_unit' : 'return_plenum'
          return_plenum = return_plenum.nil? ? nil : return_plenum.name.to_s
        end
      end

      # Check cooling air loop second; Assume that return air plenum is the dominant case
      unless cooling_equipment.nil?
        if (return_air_type != 'return_plenum') && cooling_equipment.to_StraightComponent.is_initialized
          air_loop = cooling_equipment.to_StraightComponent.get.airLoopHVAC.get
          return_plenum = air_loop_hvac_return_air_plenum(air_loop)
          return_air_type = return_plenum.nil? ? 'ducted_return_or_direct_to_unit' : 'return_plenum'
          return_plenum = return_plenum.nil? ? nil : return_plenum.name.to_s
        end
      end
    end

    # Catch all
    if return_air_type.nil?
      return_air_type = 'ducted_return_or_direct_to_unit'
    end

    # error if zone design air flow rate is not available
    if zone.model.version < OpenStudio::VersionString.new('3.6.0')
      OpenStudio.logFree(OpenStudio::Error, 'openstudio.Standards.Model', 'Required ThermalZone method .autosizedDesignAirFlowRate is not available in pre-OpenStudio 3.6.0 versions. Use a more recent version of OpenStudio.')
    end

    zone.additionalProperties.setFeature('return_air_type', return_air_type)
    zone.additionalProperties.setFeature('plenum', return_plenum) unless return_plenum.nil?
    zone.additionalProperties.setFeature('proposed_model_zone_design_air_flow', zone.autosizedDesignAirFlowRate.to_f)
  end
  return true
end
model_readjust_surface_wwr(residual_ratio, space, model) click to toggle source

Readjusted the WWR for surfaces previously has no windows to meet the overall WWR requirement. This function shall only be called if the maximum WWR value for surfaces with fenestration is lower than 90% due to accommodating the total door surface areas

@param residual_ratio [Double] the ratio of residual surfaces among the total wall surface area with no fenestrations @param space [OpenStudio::Model:Space] a space @param model [OpenStudio::Model::Model] openstudio model @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5548
def model_readjust_surface_wwr(residual_ratio, space, model)
  return true
end
model_refine_size_dependent_values(model, sizing_run_dir) click to toggle source

This method is a catch-all run at the end of create-baseline to make final adjustements to HVAC capacities to account for recent model changes @author Doug Maddox, PNNL @param model

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5688
def model_refine_size_dependent_values(model, sizing_run_dir)
  return true
end
model_rotate(model, degs) click to toggle source

This method rotates the building model from its original position

@param model [OpenStudio::Model::Model] OpenStudio Model object @param degs [Integer] Degress of rotation from original position

@return [OpenStudio::Model::Model] OpenStudio Model object

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5698
def model_rotate(model, degs)
  building = model.getBuilding
  org_north_axis = building.northAxis
  building.setNorthAxis(org_north_axis + degs)
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.model.Model', "The model was rotated of #{degs} degrees from its original position.")
  return model
end
model_set_baseline_demand_control_ventilation(model, climate_zone) click to toggle source

Template method for setting DCV in baseline HVAC system if required

@author Xuechen (Jerry) Lei, PNNL @param model [OpenStudio::Model::Model] OpenStudio model @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5926
def model_set_baseline_demand_control_ventilation(model, climate_zone)
  return true
end
model_set_central_preheat_coil_spm(model, thermal_zones, coil) click to toggle source

Template method for adding a setpoint manager for a coil control logic to a heating coil. ASHRAE 90.1-2019 Appendix G.

@param model [OpenStudio::Model::Model] OpenStudio model @param thermal_zones [Array<OpenStudio::Model::ThermalZone>] thermal zone array @param coil [OpenStudio::Model::StraightComponent] heating coil @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5899
def model_set_central_preheat_coil_spm(model, thermal_zones, coil)
  return true
end
model_temp_fix_ems_references(model) click to toggle source

This method goes through certain types of EnergyManagementSystem variables and replaces UIDs with object names. This should be done by the forward translator, and this code should be removed after this bug is fixed: github.com/NREL/OpenStudio/issues/2598

@param model [OpenStudio::Model::Model] OpenStudio model object @return [Boolean] returns true if successful, false if not @todo remove this method after OpenStudio issue #2598 is fixed.

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5666
def model_temp_fix_ems_references(model)
  # Internal Variables
  model.getEnergyManagementSystemInternalVariables.sort.each do |var|
    # Get the reference field value
    ref = var.internalDataIndexKeyName
    # Convert to UUID
    uid = OpenStudio.toUUID(ref)
    # Get the model object with this UID
    obj = model.getModelObject(uid)
    # If it exists, replace the UID with the object name
    if obj.is_initialized
      var.setInternalDataIndexKeyName(obj.get.name.get)
    end
  end

  return true
end
model_update_ground_temperature_profile(model, climate_zone) click to toggle source

Update ground temperature profile based on the weather file specified in the model

@param model [OpenStudio::Model::Model] OpenStudio model object @param climate_zone [String] ASHRAE climate zone, e.g. ‘ASHRAE 169-2013-4A’ @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 6118
def model_update_ground_temperature_profile(model, climate_zone)
  return true
end
run_all_orientations(run_all_orients, user_model) click to toggle source

Check whether the baseline model generation needs to run all four orientations The default shall be true

@param run_all_orients [Boolean] user inputs to indicate whether it is required to run all orientations @param user_model [OpenStudio::Model::Model] OpenStudio model @return [Boolean] return True if all orientation need to be run, False if not

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5917
def run_all_orientations(run_all_orients, user_model)
  return run_all_orients
end
space_a_polygons_minus_b_polygons(space, a_polygons, b_polygons, a_name, b_name) click to toggle source

Subtracts one array of polygons from the next, returning an array of resulting polygons.

@param space [OpenStudio::Model::Space] space object @param a_polygons [Array<Array>] Array of array of vertices (polygons) @param b_polygons [Array<Array>] Array of array of vertices (polygons) @param a_name [String] name of a polygons @param b_name [String] name of b polygons @return [Array<Array>] Array of array of vertices (polygons) @api private

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1991
def space_a_polygons_minus_b_polygons(space, a_polygons, b_polygons, a_name, b_name)
  final_polygons_ruby = []

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "#{a_polygons.size} #{a_name} minus #{b_polygons.size} #{b_name}")

  # Don't try to subtract anything if either set is empty
  if a_polygons.size.zero?
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---#{a_name} - #{b_name}: #{a_name} contains no polygons.")
    return space_polygons_set_z(space, a_polygons, 0.0)
  elsif b_polygons.size.zero?
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---#{a_name} - #{b_name}: #{b_name} contains no polygons.")
    return space_polygons_set_z(space, a_polygons, 0.0)
  end

  # Loop through all a polygons, and for each one,
  # subtract all the b polygons.
  a_polygons.each do |a_polygon|
    # Translate the polygon to plain arrays
    a_polygon_ruby = []
    a_polygon.each do |vertex|
      a_polygon_ruby << [vertex.x, vertex.y, vertex.z]
    end

    # @todo Skip really small polygons
    # reduced_b_polygons = []
    # b_polygons.each do |b_polygon|
    # next
    # end

    # Perform the subtraction
    a_minus_b_polygons = OpenStudio.subtract(a_polygon, b_polygons, 0.01)

    # Translate the resulting polygons to plain ruby arrays
    a_minus_b_polygons_ruby = []
    num_small_polygons = 0
    a_minus_b_polygons.each do |a_minus_b_polygon|
      # Drop any super small or zero-vertex polygons resulting from the subtraction
      area = OpenStudio.getArea(a_minus_b_polygon)
      if area.is_initialized
        if area.get < 0.5 # 5 square feet
          num_small_polygons += 1
          next
        end
      else
        num_small_polygons += 1
        next
      end

      # Translate polygon to ruby array
      a_minus_b_polygon_ruby = []
      a_minus_b_polygon.each do |vertex|
        a_minus_b_polygon_ruby << [vertex.x, vertex.y, vertex.z]
      end

      a_minus_b_polygons_ruby << a_minus_b_polygon_ruby
    end

    if num_small_polygons > 0
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---Dropped #{num_small_polygons} small or invalid polygons resulting from subtraction.")
    end

    # Remove duplicate polygons
    unique_a_minus_b_polygons_ruby = a_minus_b_polygons_ruby.uniq

    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---Remove duplicates: #{a_minus_b_polygons_ruby.size} to #{unique_a_minus_b_polygons_ruby.size}")

    # @todo bug workaround?
    # If the result includes the a polygon, the a polygon
    # was unchanged; only include that polgon and throw away the other junk?/bug? polygons.
    # If the result does not include the a polygon, the a polygon was
    # split into multiple pieces.  Keep all those pieces.
    if unique_a_minus_b_polygons_ruby.include?(a_polygon_ruby)
      if unique_a_minus_b_polygons_ruby.size == 1
        final_polygons_ruby.concat([a_polygon_ruby])
        OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '---includes only original polygon, keeping that one')
      else
        # Remove the original polygon
        unique_a_minus_b_polygons_ruby.delete(a_polygon_ruby)
        final_polygons_ruby.concat(unique_a_minus_b_polygons_ruby)
        OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '---includes the original and others; keeping all other polygons')
      end
    else
      final_polygons_ruby.concat(unique_a_minus_b_polygons_ruby)
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '---does not include original, keeping all resulting polygons')
    end
  end

  # Remove duplicate polygons again
  unique_final_polygons_ruby = final_polygons_ruby.uniq

  # @todo remove this workaround
  # Split any polygons that are joined by a line into two separate
  # polygons.  Do this by finding duplicate
  # unique_final_polygons_ruby.each do |unique_final_polygon_ruby|
  # next if unique_final_polygon_ruby.size == 4 # Don't check 4-sided polygons
  # dupes = space_find_duplicate_vertices(space, unique_final_polygon_ruby)
  # if dupes.size > 0
  # OpenStudio::logFree(OpenStudio::Error, "openstudio.standards.Space", "---Two polygons attached by line = #{unique_final_polygon_ruby.to_s.gsub(/\[|\]/,'|')}")
  # end
  # end

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---Remove final duplicates: #{final_polygons_ruby.size} to #{unique_final_polygons_ruby.size}")

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---#{a_name} minus #{b_name} = #{unique_final_polygons_ruby.size} polygons.")

  # Convert the final polygons back to OpenStudio
  unique_final_polygons = space_ruby_polygons_to_point3d_z_zero(space, unique_final_polygons_ruby)

  return unique_final_polygons
end
space_add_prm_computer_room_equipment_schedule(space) click to toggle source

Create and assign PRM computer room electric equipment schedule

@param space [OpenStudio::Model::Space] OpenStudio Space object @return [Boolean] returns true if successful, false if not

# File lib/openstudio-standards/standards/Standards.Space.rb, line 2378
def space_add_prm_computer_room_equipment_schedule(space)
  return true
end
space_area_a_polygons_overlap_b_polygons(space, a_polygons, b_polygons, a_name, b_name) click to toggle source

Returns an array of resulting polygons. Assumes that a_polygons don’t overlap one another, and that b_polygons don’t overlap one another

@param a_polygons [Array<Array>] Array of array of vertices (polygons) @param b_polygons [Array<Array>] Array of array of vertices (polygons) @param a_name [String] name of a polygons @param b_name [String] name of b polygons @return [Double] overlapping area in meters @api private

# File lib/openstudio-standards/standards/Standards.Space.rb, line 2237
def space_area_a_polygons_overlap_b_polygons(space, a_polygons, b_polygons, a_name, b_name)
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "#{a_polygons.size} #{a_name} overlaps #{b_polygons.size} #{b_name}")

  overlap_area = 0

  # Don't try anything if either set is empty
  if a_polygons.size.zero?
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---#{a_name} overlaps #{b_name}: #{a_name} contains no polygons.")
    return overlap_area
  elsif b_polygons.size.zero?
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---#{a_name} overlaps #{b_name}: #{b_name} contains no polygons.")
    return overlap_area
  end

  # Loop through each base surface
  b_polygons.each do |b_polygon|
    # OpenStudio::logFree(OpenStudio::Info, "openstudio.standards.Space", "---b polygon = #{b_polygon_ruby.to_s.gsub(/\[|\]/,'|')}")

    # Loop through each overlap surface and determine if it overlaps this base surface
    a_polygons.each do |a_polygon|
      # OpenStudio::logFree(OpenStudio::Info, "openstudio.standards.Space", "------a polygon = #{a_polygon_ruby.to_s.gsub(/\[|\]/,'|')}")

      # If the entire a polygon is within the b polygon, count 100% of the area
      # as overlapping and remove a polygon from the list
      if OpenStudio.within(a_polygon, b_polygon, 0.01)

        OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '---------a overlaps b ENTIRELY.')

        area = OpenStudio.getArea(a_polygon)
        if area.is_initialized
          overlap_area += area.get
          next
        else
          OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "Could not determine the area of #{a_polygon.to_s.gsub(/\[|\]/, '|')} in #{a_name}; #{a_name} overlaps #{b_name}.")
        end

        # If part of a polygon overlaps b polygon, determine the
        # original area of polygon b, subtract polygon a from b,
        # then add the difference in area to the total.
      elsif OpenStudio.intersects(a_polygon, b_polygon, 0.01)

        OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '---------a overlaps b PARTIALLY.')

        # Get the initial area
        area_initial = 0
        area = OpenStudio.getArea(b_polygon)
        if area.is_initialized
          area_initial = area.get
        else
          OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "Could not determine the area of #{a_polygon.to_s.gsub(/\[|\]/, '|')} in #{a_name}; #{a_name} overlaps #{b_name}.")
        end

        # Perform the subtraction
        b_minus_a_polygons = OpenStudio.subtract(b_polygon, [a_polygon], 0.01)

        # Get the final area
        area_final = 0
        b_minus_a_polygons.each do |polygon|
          # Skip polygons that have no vertices
          # resulting from the subtraction.
          if polygon.size.zero?
            OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "Zero-vertex polygon resulting from #{b_polygon.to_s.gsub(/\[|\]/, '|')} minus #{a_polygon.to_s.gsub(/\[|\]/, '|')}.")
            next
          end
          # Find the area of real polygons
          area = OpenStudio.getArea(polygon)
          if area.is_initialized
            area_final += area.get
          else
            OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Could not determine the area of #{polygon.to_s.gsub(/\[|\]/, '|')} in #{a_name}; #{a_name} overlaps #{b_name}.")
          end
        end

        # Add the diference to the total
        overlap_area += (area_initial - area_final)

        # There is no overlap
      else

        OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '---------a does not overlaps b at all.')

      end
    end
  end

  return overlap_area
end
space_check_z_zero(space, polygons, name) click to toggle source

Check the z coordinates of a polygon

@param space [OpenStudio::Model::Space] space object @param polygons [Array<Array>] Array of array of vertices (polygons) @param name [String] name of polygons @return [Integer] return number of errors @api private

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1891
def space_check_z_zero(space, polygons, name)
  fails = []
  errs = 0
  polygons.each do |polygon|
    # OpenStudio::logFree(OpenStudio::Error, "openstudio.standards.Space", "Checking z=0: #{name} is greater than or equal to #{polygon.to_s.gsub(/\[|\]/,'|')}.")
    polygon.each do |vertex|
      # clsss << vertex.class
      unless vertex.z == 0.0
        errs += 1
        fails << vertex.z
      end
    end
  end
  # OpenStudio::logFree(OpenStudio::Error, "openstudio.standards.Space", "Checking z=0: #{name} is greater than or equal to #{clsss.uniq.to_s.gsub(/\[|\]/,'|')}.")
  OpenStudio.logFree(OpenStudio::Info, 'openstudio.standards.Space', "***FAIL*** #{space.name} z=0 failed for #{errs} vertices in #{name}; #{fails.join(', ')}.") if errs > 0
  return errs
end
space_daylighting_control_type(space) click to toggle source

Provide the type of daylighting control type

@param space [OpenStudio::Model::Space] OpenStudio Space object @return [String] daylighting control type

# File lib/openstudio-standards/standards/Standards.Space.rb, line 2361
def space_daylighting_control_type(space)
  return 'Stepped'
end
space_daylighting_minimum_input_power_fraction(space) click to toggle source

Provide the minimum input power fraction for continuous dimming daylighting control

@param space [OpenStudio::Model::Space] OpenStudio Space object @return [Double] daylighting minimum input power fraction

# File lib/openstudio-standards/standards/Standards.Space.rb, line 2370
def space_daylighting_minimum_input_power_fraction(space)
  return 0.3
end
space_find_duplicate_vertices(space, ruby_polygon, tol = 0.001) click to toggle source

A method to returns the number of duplicate vertices in a polygon. @todo does not actually work

@param space [OpenStudio::Model::Space] space object @param ruby_polygon [Array] array of vertices (polygon) @param tol [Double] tolerance @return [Array] array of duplicates @api private

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1962
def space_find_duplicate_vertices(space, ruby_polygon, tol = 0.001)
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', '***')
  duplicates = []

  combos = ruby_polygon.combination(2).to_a
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "########{combos.size}")
  combos.each do |i, j|
    i_vertex = OpenStudio::Point3d.new(i[0], i[1], i[2])
    j_vertex = OpenStudio::Point3d.new(j[0], j[1], j[2])

    distance = OpenStudio.getDistance(i_vertex, j_vertex)
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "------- #{i} to #{j} = #{distance}")
    if distance < tol
      duplicates << i
    end
  end

  return duplicates
end
space_is_plenum(space) click to toggle source

A function to check whether a space is a return / supply plenum. This function only works on spaces used as a AirLoopSupplyPlenum or AirLoopReturnPlenum @param space [OpenStudio::Model::Space] @return [Boolean] true if it is plenum, else false.

# File lib/openstudio-standards/standards/Standards.Space.rb, line 2329
def space_is_plenum(space)
  # Get the zone this space is inside
  zone = space.thermalZone
  # the zone is a return air plenum
  space.model.getAirLoopHVACReturnPlenums.each do |return_air_plenum|
    if return_air_plenum.thermalZone.get.name.to_s == zone.get.name.to_s
      # Determine if residential
      return true
    end
  end
  # the zone is a supply plenum
  space.model.getAirLoopHVACSupplyPlenums.each do |supply_air_plenum|
    if supply_air_plenum.thermalZone.get.name.to_s == zone.get.name.to_s
      return true
    end
  end
  # None match, return false
  return false
end
space_join_polygons(space, polygons, tol, name) click to toggle source

Wrapper to catch errors in joinAll method

utilities.geometry.joinAll

<1> Expected polygons to join together

@param space [OpenStudio::Model::Space] space object @param polygons [Array] array of vertices (polygon) @param tol [Double] tolerance @param name [String] name of polygons @return [Array<Array>] Array of array of vertices (polygons) @api private

# File lib/openstudio-standards/standards/Standards.Space.rb, line 2111
def space_join_polygons(space, polygons, tol, name)
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "Joining #{name} from #{space.name}")

  combined_polygons = []

  # Don't try to combine an empty array of polygons
  if polygons.size.zero?
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---#{name} contains no polygons, not combining.")
    return combined_polygons
  end

  # Open a log
  msg_log = OpenStudio::StringStreamLogSink.new
  msg_log.setLogLevel(OpenStudio::Info)

  # Combine the polygons
  combined_polygons = OpenStudio.joinAll(polygons, 0.01)

  # Count logged errors
  join_errs = 0
  inner_loop_errs = 0
  msg_log.logMessages.each do |msg|
    if /utilities.geometry/ =~ msg.logChannel
      if msg.logMessage.include?('Expected polygons to join together')
        join_errs += 1
      elsif msg.logMessage.include?('Union has inner loops')
        inner_loop_errs += 1
      end
    end
  end

  # Disable the log sink to prevent memory hogging
  msg_log.disable

  # @todo remove this workaround, which is tried if there
  # are any join errors.  This handles the case of polygons
  # that make an inner loop, the most common case being
  # when all 4 sides of a space have windows.
  # If an error occurs, attempt to join n-1 polygons,
  # then subtract the
  if join_errs > 0 || inner_loop_errs > 0

    # Open a log
    msg_log_2 = OpenStudio::StringStreamLogSink.new
    msg_log_2.setLogLevel(OpenStudio::Info)

    first_polygon = polygons.first
    polygons = polygons.drop(1)

    combined_polygons_2 = OpenStudio.joinAll(polygons, 0.01)

    join_errs_2 = 0
    inner_loop_errs_2 = 0
    msg_log_2.logMessages.each do |msg|
      if /utilities.geometry/ =~ msg.logChannel
        if msg.logMessage.include?('Expected polygons to join together')
          join_errs_2 += 1
        elsif msg.logMessage.include?('Union has inner loops')
          inner_loop_errs_2 += 1
        end
      end
    end

    # Disable the log sink to prevent memory hogging
    msg_log_2.disable

    if join_errs_2 > 0 || inner_loop_errs_2 > 0
      OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, the workaround for joining polygons failed.")
    else

      # First polygon minus the already combined polygons
      first_polygon_minus_combined = space_a_polygons_minus_b_polygons(space, [first_polygon], combined_polygons_2, 'first_polygon', 'combined_polygons_2')

      # Add the result back
      combined_polygons_2 += first_polygon_minus_combined
      combined_polygons = combined_polygons_2
      join_errs = 0
      inner_loop_errs = 0

    end
  end

  # Report logged errors to user
  if join_errs > 0
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, #{join_errs} of #{polygons.size} #{space.name} were not joined properly due to limitations of the geometry calculation methods.  The resulting daylighted areas will be smaller than they should be.")
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "For #{space.name}, the #{name.gsub('_polygons', '')} daylight area calculations hit limitations.  Double-check and possibly correct the fraction of lights controlled by each daylight sensor.")
  end
  if inner_loop_errs > 0
    OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "For #{space.name}, #{inner_loop_errs} of #{polygons.size} #{space.name} were not joined properly because the joined polygons have an internal hole.  The resulting daylighted areas will be smaller than they should be.")
    OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "For #{space.name}, the #{name.gsub('_polygons', '')} daylight area calculations hit limitations.  Double-check and possibly correct the fraction of lights controlled by each daylight sensor.")
  end

  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "---Joined #{polygons.size} #{space.name} into #{combined_polygons.size} polygons.")

  return combined_polygons
end
space_occupancy_standby_mode_required?(space) click to toggle source

Determine if a space should be modeled with an occupancy standby mode

@param space [OpenStudio::Model::Space] OpenStudio Space object @return [Boolean] true if occupancy standby mode is to be modeled, false otherwise

# File lib/openstudio-standards/standards/Standards.Space.rb, line 2353
def space_occupancy_standby_mode_required?(space)
  return false
end
space_polygons_set_z(space, polygons, new_z) click to toggle source

A method to zero-out the z vertex of an array of polygons

@param space [OpenStudio::Model::Space] space object @param polygons [Array<Array>] Array of array of vertices (polygons) @param new_z [Double] new z value in meters @return [Array<Array>] Array of array of Point3D objects (polygons) @api private

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1937
def space_polygons_set_z(space, polygons, new_z)
  OpenStudio.logFree(OpenStudio::Debug, 'openstudio.standards.Space', "### #{polygons}")

  # Convert the final polygons back to OpenStudio
  new_polygons = []
  polygons.each do |polygon|
    new_polygon = []
    polygon.each do |vertex|
      new_vertex = OpenStudio::Point3d.new(vertex.x, vertex.y, new_z) # Set z to hard-zero instead of vertex[2]
      new_polygon << new_vertex
    end
    new_polygons << new_polygon
  end

  return new_polygons
end
space_ruby_polygons_to_point3d_z_zero(space, ruby_polygons) click to toggle source

A method to convert an array of arrays to an array of OpenStudio::Point3ds.

@param space [OpenStudio::Model::Space] space object @param ruby_polygons [Array<Array>] Array of array of vertices (polygons) @return [Array<Array>] Array of array of Point3D objects (polygons) @api private

# File lib/openstudio-standards/standards/Standards.Space.rb, line 1915
def space_ruby_polygons_to_point3d_z_zero(space, ruby_polygons)
  # Convert the final polygons back to OpenStudio
  os_polygons = []
  ruby_polygons.each do |ruby_polygon|
    os_polygon = []
    ruby_polygon.each do |vertex|
      vertex = OpenStudio::Point3d.new(vertex[0], vertex[1], 0.0) # Set z to hard-zero instead of vertex[2]
      os_polygon << vertex
    end
    os_polygons << os_polygon
  end

  return os_polygons
end
space_total_area_of_polygons(space, polygons) click to toggle source

Gets the total area of a series of polygons

@param space [OpenStudio::Model::Space] space object @param polygons [Array] array of vertices (polygon) @return [Double] area in meters @api private

# File lib/openstudio-standards/standards/Standards.Space.rb, line 2214
def space_total_area_of_polygons(space, polygons)
  total_area_m2 = 0
  polygons.each do |polygon|
    area_m2 = OpenStudio.getArea(polygon)
    if area_m2.is_initialized
      total_area_m2 += area_m2.get
    else
      OpenStudio.logFree(OpenStudio::Warn, 'openstudio.standards.Space', "Could not get area for a polygon in #{space.name}, daylighted area calculation will not be accurate.")
    end
  end

  return total_area_m2
end
surface_get_wwr_reduction_ratio(multiplier, surface, wwr_building_type: 'All others', wwr_target: 0.0, total_wall_m2: 0.0, total_wall_with_fene_m2: 0.0, total_fene_m2: 0.0, total_plenum_wall_m2: 0.0) click to toggle source

Calculate the window to wall ratio reduction factor

@param multiplier [Double] multiplier of the wwr @param surface [OpenStudio::Model:Surface] OpenStudio Surface object @param wwr_target [Double] target window to wall ratio @param total_wall_m2 [Double] total wall area of the category in m2. @param total_wall_with_fene_m2 [Double] total wall area of the category with fenestrations in m2. @param total_fene_m2 [Double] total fenestration area @param total_plenum_wall_m2 [Double] total sqaure meter of a plenum @return [Double] reduction factor

# File lib/openstudio-standards/standards/Standards.Model.rb, line 5865
def surface_get_wwr_reduction_ratio(multiplier,
                                    surface,
                                    wwr_building_type: 'All others',
                                    wwr_target: 0.0,
                                    total_wall_m2: 0.0,
                                    total_wall_with_fene_m2: 0.0,
                                    total_fene_m2: 0.0,
                                    total_plenum_wall_m2: 0.0)
  return 1.0 - multiplier
end