Module: OSut

Extended by:
OSlg
Defined in:
lib/osut/version.rb,
lib/osut/utils.rb

Overview

BSD 3-Clause License

Copyright © 2022-2024, Denis Bourgeois All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Constant Summary collapse

TOL =

default distance tolerance (m)

0.01
TOL2 =

default area tolerance (m2)

TOL * TOL
DBG =

see github.com/rd2/oslg

OSlg::DEBUG.dup
INF =

see github.com/rd2/oslg

OSlg::INFO.dup
WRN =

see github.com/rd2/oslg

OSlg::WARN.dup
ERR =

see github.com/rd2/oslg

OSlg::ERROR.dup
FTL =

see github.com/rd2/oslg

OSlg::FATAL.dup
NS =

OpenStudio object identifier method

"nameString"
HEAD =

standard 80“ door

2.032
SILL =

standard 30“ window sill

0.762
SIDZ =

General surface orientations (see facets method)

[:bottom, # e.g. ground-facing, exposed floors
    :top, # e.g. roof/ceiling
  :north, # NORTH
   :east, # EAST
  :south, # SOUTH
   :west  # WEST
].freeze
VERSION =

OSut version

"0.6.0".freeze
@@mass =

Thermal mass categories (e.g. exterior cladding, interior finish, framing).

[
    :none, # token for 'no user selection', resort to defaults
   :light, # e.g. 16mm drywall interior
  :medium, # e.g. 100mm brick cladding
   :heavy  # e.g. 200mm poured concrete
].freeze
@@mats =

Basic materials (StandardOpaqueMaterials only).

{
  material: {}, # generic, e.g. lightweight cladding over furring, fibreboard
      sand: {},
  concrete: {},
     brick: {},
   drywall: {}, # e.g. finished drywall, intermediate sheating
   mineral: {}, # e.g. light, semi-rigid rock wool insulation
   polyiso: {}, # e.g. polyisocyanurate panel (or similar)
 cellulose: {}, # e.g. blown, dry/stabilized fibre
      door: {}  # single composite material (45mm insulated steel door)
}.freeze
@@film =

default inside + outside air film resistances (m2.K/W)

{
    shading: 0.000, # NA
  partition: 0.150, # uninsulated wood- or steel-framed wall
       wall: 0.150, # un/insulated wall
       roof: 0.140, # un/insulated roof
      floor: 0.190, # un/insulated (exposed) floor
   basement: 0.120, # un/insulated basement wall
       slab: 0.160, # un/insulated basement slab or slab-on-grade
       door: 0.150, # standard, 45mm insulated steel (opaque) door
     window: 0.150, # vertical fenestration, e.g. glazed doors, windows
   skylight: 0.140  # e.g. domed 4' x 4' skylight
}.freeze
@@uo =

default (~1980s) envelope Uo (W/m2•K), based on surface type

{
    shading: nil,   # N/A
  partition: nil,   # N/A
       wall: 0.384, # rated R14.8 hr•ft2F/Btu
       roof: 0.327, # rated R17.6 hr•ft2F/Btu
      floor: 0.317, # rated R17.9 hr•ft2F/Btu (exposed floor)
   basement: nil,
       slab: nil,
       door: 1.800, # insulated, unglazed steel door (single layer)
     window: 2.800, # e.g. patio doors (simple glazing)
   skylight: 3.500  # all skylight technologies
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object

Callback when other modules extend OSlg

Parameters:

  • base (Object)

    instance or class object



7778
7779
7780
# File 'lib/osut/utils.rb', line 7778

def self.extended(base)
  base.send(:include, self)
end

Instance Method Details

#addSkyLights(spaces = [], opts = {}) ⇒ Float

Adds skylights to toplight selected OpenStudio (occupied, conditioned) spaces, based on requested skylight area, or a skylight-to-roof ratio (SRR%). If the user selects 0m2 as the requested :area (or 0 as the requested :srr), while setting the option :clear as true, the method simply purges all pre-existing roof fenestrated subsurfaces of selected spaces, and exits while returning 0 (without logging an error or warning). Pre-existing skylight wells are not cleared however. Pre-toplit spaces are otherwise ignored. Boolean options :attic, :plenum, :sloped and :sidelit further restrict candidate spaces to toplight. If applicable, options :attic and :plenum add skylight wells. Option :patterns restricts preset skylight allocation layouts in order of preference; if left empty, all preset patterns are considered, also in order of preference (see examples).

Examples:

(a) consider 2D array of individual skylights, e.g. n(1.22m x 1.22m)

opts[:patterns] = ["array"]

(b) consider ‘a’, then array of 1x(size) x n(size) skylight strips

opts[:patterns] = ["array", "strips"]

Parameters:

  • spaces (Array<OpenStudio::Model::Space>) (defaults to: [])

    space(s) to toplight

  • opts (Hash) (defaults to: {})

    requested skylight attributes

Options Hash (opts):

  • :area (#to_f)

    overall skylight area

  • :srr (#to_f)

    skylight-to-roof ratio (0.00, 0.90]

  • :size (#to_f) — default: 1.22

    template skylight width/depth (min 0.4m)

  • :frame (#frameWidth) — default: nil

    OpenStudio Frame & Divider (optional)

  • :clear (Bool) — default: true

    whether to first purge existing skylights

  • :ration (Bool) — default: true

    finer selection of candidates to toplight

  • :sidelit (Bool) — default: true

    whether to consider sidelit spaces

  • :sloped (Bool) — default: true

    whether to consider sloped roof surfaces

  • :plenum (Bool) — default: true

    whether to consider plenum wells

  • :attic (Bool) — default: true

    whether to consider attic wells

  • :patterns (Array<#to_s>)

    requested skylight allocation (3x)

Returns:

  • (Float)

    returns gross roof area if successful (see logs if 0m2)



6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
# File 'lib/osut/utils.rb', line 6234

def addSkyLights(spaces = [], opts = {})
  mth   = "OSut::#{__callee__}"
  clear = true
  srr   = nil
  area  = nil
  frame = nil   # FrameAndDivider object
  f     = 0.0   # FrameAndDivider frame width
  gap   = 0.1   # min 2" around well (2x == 4"), as well as max frame width
  gap2  = 0.2   # 2x gap
  gap4  = 0.4   # minimum skylight 16" width/depth (excluding frame width)
  bfr   = 0.005 # minimum array perimeter buffer (no wells)
  w     = 1.22  # default 48" x 48" skylight base
  w2    = w * w # m2

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Excerpts of ASHRAE 90.1 2022 definitions:
  #
  # "ROOF":
  #
  #   "the upper portion of the building envelope, including opaque areas and
  #   fenestration, that is horizontal or tilted at an angle of less than 60
  #   degrees from horizontal. For the purposes of determining building
  #   envelope requirements, the classifications are defined as follows
  #   (inter alia):
  #
  #     - attic and other roofs: all other roofs, including roofs with
  #       insulation ENTIRELY BELOW (inside of) the roof structure (i.e.,
  #       attics, cathedral ceilings, and single-rafter ceilings), roofs with
  #       insulation both above and BELOW the roof structure, and roofs
  #       without insulation but excluding metal building roofs. [...]"
  #
  # "ROOF AREA, GROSS":
  #
  #   "the area of the roof measured from the EXTERIOR faces of walls or from
  #   the centerline of party walls."
  #
  #
  # For the simple case below (steep 4-sided hip roof, UNENCLOSED ventilated
  # attic), 90.1 users typically choose between either:
  #   1. modelling the ventilated attic explicitly, or
  #   2. ignoring the ventilated attic altogether.
  #
  # If skylights were added to the model, option (1) would require one or more
  # skylight wells (light shafts leading to occupied spaces below), with
  # insulated well walls separating CONDITIONED spaces from an UNENCLOSED,
  # UNCONDITIONED space (i.e. attic).
  #
  # Determining which roof surfaces (or which portion of roof surfaces) need
  # to be considered when calculating "GROSS ROOF AREA" may be subject to some
  # interpretation. From the above definitions:
  #
  #   - the uninsulated, tilted hip-roof attic surfaces are considered "ROOF"
  #     surfaces, provided they 'shelter' insulation below (i.e. insulated
  #     attic floor).
  #   - however, only the 'projected' portion of such "ROOF" surfaces, i.e.
  #     areas between axes AA` and BB` (along exterior walls)) would be
  #     considered.
  #   - the portions above uninsulated soffits (illustrated on the right)
  #     would be excluded from the "GROSS ROOF AREA" as they are beyond the
  #     exterior wall projections.
  #
  #     A         B
  #     |         |
  #      _________
  #     /          \                  /|        |\
  #    /            \                / |        | \
  #   /_  ________  _\    = >       /_ |        | _\   ... excluded portions
  #     |          |
  #     |__________|
  #     .          .
  #     A`         B`
  #
  # If the unoccupied space (directly under the hip roof) were instead an
  # INDIRECTLY-CONDITIONED plenum (not an attic), then there would be no need
  # to exclude portions of any roof surface: all plenum roof surfaces (in
  # addition to soffit surfaces) would need to be insulated). The method takes
  # such circumstances into account, which requires vertically casting of
  # surfaces onto others, as well as overlap calculations. If successful, the
  # method returns the "GROSS ROOF AREA" (in m2), based on the above rationale.
  #
  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Excerpts of similar NECB requirements (unchanged from 2011 through 2020):
  #
  #   3.2.1.4. 2). "The total skylight area shall be less than 2% of the GROSS
  #   ROOF AREA as determined in Article 3.1.1.6." (5% in earlier versions)
  #
  #   3.1.1.6. 5). "In the calculation of allowable skylight area, the GROSS
  #   ROOF AREA shall be calculated as the sum of the areas of insulated
  #   roof including skylights."
  #
  # There are NO additional details or NECB appendix notes on the matter. It
  # is unclear if the NECB's looser definition of GROSS ROOF AREA includes
  # (uninsulated) sloped roof surfaces above (insulated) flat ceilings (e.g.
  # attics), as with 90.1. It would be definitely odd if it didn't. For
  # instance, if the GROSS ROOF AREA were based on insulated ceiling surfaces,
  # there would be a topological disconnect between flat ceiling and sloped
  # skylights above. Should NECB users first 'project' (sloped) skylight rough
  # openings onto flat ceilings when calculating SRR%? Without much needed
  # clarification, the (clearer) 90.1 rules equally apply here to NECB cases.

  # If skylight wells are indeed required, well wall edges are always vertical
  # (i.e. never splayed), requiring a vertical ray.
  origin = OpenStudio::Point3d.new(0,0,0)
  zenith = OpenStudio::Point3d.new(0,0,1)
  ray    = zenith - origin

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Accept a single 'OpenStudio::Model::Space' (vs an array of spaces).
  if spaces.respond_to?(:spaceType) || spaces.respond_to?(:to_a)
    spaces = spaces.respond_to?(:to_a) ? spaces.to_a : [spaces]
    spaces = spaces.select { |space| space.respond_to?(:spaceType) }
    spaces = spaces.select { |space| space.partofTotalFloorArea }
    spaces = spaces.reject { |space| unconditioned?(space) }
    return empty("spaces", mth, DBG, 0) if spaces.empty?
  else
    return mismatch("spaces", spaces, Array, mth, DBG, 0)
  end

  mdl = spaces.first.model

  # Exit if mismatched or invalid options.
  return mismatch("opts", opts, Hash, mth, DBG, 0) unless opts.is_a?(Hash)

  # Validate Frame & Divider object, if provided.
  if opts.key?(:frame)
    frame = opts[:frame]

    if frame.respond_to?(:frameWidth)
      frame = nil if v < 321
      frame = nil if f.frameWidth.round(2) < 0
      frame = nil if f.frameWidth.round(2) > gap

      f = f.frameWidth                            if frame
      log(WRN, "Skip Frame&Divider (#{mth})") unless frame
    else
      frame = nil
      log(ERR, "Skip invalid Frame&Divider object (#{mth})")
    end
  end

  # Validate skylight size, if provided.
  if opts.key?(:size)
    if opts[:size].respond_to?(:to_f)
      w  = opts[:size].to_f
      w2 = w * w
      return invalid(size, mth, 0, ERR, 0) if w.round(2) < gap4
    else
      return mismatch("size", opts[:size], Numeric, mth, DBG, 0)
    end
  end

  f2  = 2 * f
  w0  = w + f2
  w02 = w0 * w0
  wl  = w0 + gap
  wl2 = wl * wl

  # Validate requested skylight-to-roof ratio (or overall area).
  if opts.key?(:area)
    if opts[:area].respond_to?(:to_f)
      area = opts[:area].to_f
      log(WRN, "Area reset to 0.0m2 (#{mth})") if area < 0
    else
      return mismatch("area", opts[:area], Numeric, mth, DBG, 0)
    end
  elsif opts.key?(:srr)
    if opts[:srr].respond_to?(:to_f)
      srr = opts[:srr].to_f
      log(WRN, "SRR (#{srr.round(2)}) reset to 0% (#{mth})")  if srr < 0
      log(WRN, "SRR (#{srr.round(2)}) reset to 90% (#{mth})") if srr > 0.90
      srr = srr.clamp(0.00, 0.10)
    else
      return mismatch("srr", opts[:srr], Numeric, mth, DBG, 0)
    end
  else
    return hashkey("area", opts, :area, mth, ERR, 0)
  end

  # Validate purge request, if provided.
  if opts.key?(:clear)
    clear = opts[:clear]

    unless [true, false].include?(clear)
      log(WRN, "Purging existing skylights by default (#{mth})")
      clear = true
    end
  end

  # Purge if requested.
  getRoofs(spaces).each { |s| s.subSurfaces.map(&:remove) } if clear

  # Safely exit, e.g. if strictly called to purge existing roof subsurfaces.
  return 0 if area && area.round(2) == 0
  return 0 if srr  &&  srr.round(2) == 0

  m2  = 0 # total existing skylight rough opening area
  rm2 = grossRoofArea(spaces) # excludes e.g. overhangs

  # Tally existing skylight rough opening areas.
  spaces.each do |space|
    m = space.multiplier

    facets(space, "Outdoors", "RoofCeiling").each do |roof|
      roof.subSurfaces.each do |sub|
        next unless fenestration?(sub)

        id  = sub.nameString
        xm2 = sub.grossArea

        if sub.allowWindowPropertyFrameAndDivider
          unless sub.windowPropertyFrameAndDivider.empty?
            fw   = sub.windowPropertyFrameAndDivider.get.frameWidth
            vec  = offset(sub.vertices, fw, 300)
            aire = OpenStudio.getArea(vec)

            if aire.empty?
              log(ERR, "Skipping '#{id}': invalid Frame&Divider (#{mth})")
            else
              xm2 = aire.get
            end
          end
        end

        m2 += xm2 * sub.multiplier * m
      end
    end
  end

  # Required skylight area to add.
  sm2 = area ? area : rm2 * srr - m2

  # Warn/skip if existing skylights exceed or ~roughly match targets.
  if sm2.round(2) < w02.round(2)
    if m2 > 0
      log(INF, "Skipping: existing skylight area > request (#{mth})")
      return rm2
    else
      log(INF, "Requested skylight area < min size (#{mth})")
    end
  elsif 0.9 * rm2.round(2) < sm2.round(2)
    log(INF, "Skipping: requested skylight area > 90% of GRA (#{mth})")
    return rm2
  end

  opts[:ration] = true unless opts.key?(:ration)

  # By default, seek ideal candidate spaces/roofs. Bail out if unsuccessful.
  unless opts[:ration] == false
    spaces = toToplit(spaces, opts)
    return rm2 if spaces.empty?
  end

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # The method seeks to insert a skylight array within the largest rectangular
  # 'bounded box' that neatly 'fits' within a given roof surface. This equally
  # applies to any vertically-cast overlap between roof and plenum (or attic)
  # floor, which in turn generates skylight wells. Skylight arrays are
  # inserted from left-to-right & top-to-bottom (as illustrated below), once a
  # roof (or cast 3D overlap) is 'aligned' in 2D.
  #
  # Depending on geometric complexity (e.g. building/roof concavity,
  # triangulation), the total area of bounded boxes may be significantly less
  # than the calculated "GROSS ROOF AREA", which can make it challenging to
  # attain the requested skylight area. If :patterns are left unaltered, the
  # method will select those that maximize the likelihood of attaining the
  # requested target, to the detriment of spatial daylighting distribution.
  #
  # The default skylight module size is 1.22m x 1.22m (4' x 4'), which can be
  # overridden by the user, e.g. 2.44m x 2.44m (8' x 8'). However, skylight
  # sizes usually end up either contracted or inflated to exactly meet a
  # request skylight area or SRR%,
  #
  # Preset skylight allocation patterns (in order of precedence):
  #
  #    1. "array"
  #   _____________________
  #  |   _      _      _   |  - ?x columns ("cols") >= ?x rows (min 2x2)
  #  |  |_|    |_|    |_|  |  - SRR ~5% (1.22m x 1.22m), as illustrated
  #  |                     |  - SRR ~19% (2.44m x 2.44m)
  #  |   _      _      _   |  - +suitable for wide spaces (storage, retail)
  #  |  |_|    |_|    |_|  |  - ~1.4x height + skylight width 'ideal' rule
  #  |_____________________|  - better daylight distribution, many wells
  #
  #    2. "strips"
  #   _____________________
  #  |   _      _      _   |  - ?x columns (min 2), 1x row
  #  |  | |    | |    | |  |  - ~doubles %SRR ...
  #  |  | |    | |    | |  |  - SRR ~10% (1.22m x ?1.22m), as illustrated
  #  |  | |    | |    | |  |  - SRR ~19% (2.44m x ?1.22m)
  #  |  |_|    |_|    |_|  |  - ~roof monitor layout
  #  |_____________________|  - fewer wells
  #
  #    3. "strip"
  #    ____________________
  #   |                    |  - 1x column, 1x row (min 1x)
  #   |   ______________   |  - SRR ~11% (1.22m x ?1.22m)
  #   |  | ............ |  |  - SRR ~22% (2.44m x ?1.22m), as illustrated
  #   |  |______________|  |  - +suitable for elongated bounded boxes
  #   |                    |  - 1x well
  #   |____________________|
  #
  # @todo: Support strips/strip patterns along ridge of paired roof surfaces.
  layouts  = ["array", "strips", "strip"]
  patterns = []

  # Validate skylight placement patterns, if provided.
  if opts.key?(:patterns)
    if opts[:patterns].is_a?(Array)
      opts[:patterns].each_with_index do |pattern, i|
        pattern = trim(pattern).downcase

        if pattern.empty?
          invalid("pattern #{i+1}", mth, 0, ERR)
          next
        end

        patterns << pattern if layouts.include?(pattern)
      end
    else
      mismatch("patterns", opts[:patterns], Array, mth, DBG)
    end
  end

  patterns = layouts if patterns.empty?

  # The method first attempts to add skylights in ideal candidate spaces:
  #   - large roof surface areas (e.g. retail, classrooms ... not corridors)
  #   - not sidelit (favours core spaces)
  #   - having flat roofs (avoids sloped roofs)
  #   - neither under plenums, nor attics (avoids wells)
  #
  # This ideal (albeit stringent) set of conditions is "combo a".
  #
  # If the requested skylight area has not yet been achieved (after initially
  # applying "combo a"), the method decrementally drops selection criteria and
  # starts over, e.g.:
  #   - then considers sidelit spaces
  #   - then considers sloped roofs
  #   - then considers skylight wells
  #
  # A maximum number of skylights are allocated to roof surfaces matching a
  # given combo, all the while giving priority to larger roof areas. An error
  # message is logged if the target isn't ultimately achieved.
  #
  # Through filters, users may in advance restrict candidate roof surfaces:
  #   b. above occupied sidelit spaces ('false' restricts to core spaces)
  #   c. that are sloped ('false' restricts to flat roofs)
  #   d. above INDIRECTLY CONDITIONED spaces (e.g. plenums, uninsulated wells)
  #   e. above UNCONDITIONED spaces (e.g. attics, insulated wells)
  filters = ["a", "b", "bc", "bcd", "bcde"]

  # Prune filters, based on user-selected options.
  [:sidelit, :sloped, :plenum, :attic].each do |opt|
    next unless opts.key?(opt)
    next unless opts[opt] == false

    case opt
    when :sidelit then filters.map! { |f| f.include?("b") ? f.delete("b") : f }
    when :sloped  then filters.map! { |f| f.include?("c") ? f.delete("c") : f }
    when :plenum  then filters.map! { |f| f.include?("d") ? f.delete("d") : f }
    when :attic   then filters.map! { |f| f.include?("e") ? f.delete("e") : f }
    end
  end

  filters.reject! { |f| f.empty? }
  filters.uniq!

  # Remaining filters may be further pruned automatically after space/roof
  # processing, depending on geometry, e.g.:
  #  - if there are no sidelit spaces: filter "b" will be pruned away
  #  - if there are no sloped roofs  : filter "c" will be pruned away
  #  - if no plenums are identified  : filter "d" will be pruned away
  #  - if no attics are identified   : filter "e" will be pruned away

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Break down spaces (and connected spaces) into groups.
  sets     = [] # collection of skylight arrays to deploy
  rooms    = {} # occupied CONDITIONED spaces to toplight
  plenums  = {} # unoccupied (INDIRECTLY-) CONDITIONED spaces above rooms
  attics   = {} # unoccupied UNCONDITIONED spaces above rooms
  ceilings = {} # of occupied CONDITIONED space (if plenums/attics)

  # Candidate 'rooms' to toplit - excludes plenums/attics.
  spaces.each do |space|
    id = space.nameString

    if daylit?(space, false, true, false)
      log(WRN, "#{id} is already toplit, skipping (#{mth})")
      next
    end

    # When unoccupied spaces are involved (e.g. plenums, attics), the occupied
    # space (to toplight) may not share the same local transformation as its
    # unoccupied space(s) above. Fetching site transformation.
    t0 = transforms(space)
    next unless t0[:t]

    # Calculate space height.
    hMIN  = 10000
    hMAX  = 0
    surfs = facets(space)

    surfs.each { |surf| hMAX = [hMAX, surf.vertices.max_by(&:z).z].max }
    surfs.each { |surf| hMIN = [hMIN, surf.vertices.min_by(&:z).z].min }

    h = hMAX - hMIN

    unless h > 0
      log(ERR, "#{id} height? #{hMIN.round(2)} vs #{hMAX.round(2)} (#{mth})")
      next
    end

    rooms[space]           = {}
    rooms[space][:t0     ] = t0[:t]
    rooms[space][:m      ] = space.multiplier
    rooms[space][:h      ] = h
    rooms[space][:roofs  ] = facets(space, "Outdoors", "RoofCeiling")
    rooms[space][:sidelit] = daylit?(space, true, false, false)

    # Fetch and process room-specific outdoor-facing roof surfaces, the most
    # basic 'set' to track, e.g.:
    #   - no skylight wells (i.e. no leader lines)
    #   - 1x skylight array per roof surface
    #   - no need to consider site transformation
    rooms[space][:roofs].each do |roof|
      next unless roof?(roof)

      box = boundedBox(roof)
      next if box.empty?

      bm2 = OpenStudio.getArea(box)
      next if bm2.empty?

      bm2 = bm2.get
      next if bm2.round(2) < w02.round(2)

      width = alignedWidth(box, true)
      depth = alignedHeight(box, true)
      next if width < wl * 3
      next if depth < wl

      # A set is 'tight' if the area of its bounded box is significantly
      # smaller than that of its roof. A set is 'thin' if the depth of its
      # bounded box is (too) narrow. If either is true, some geometry rules
      # may be relaxed to maximize allocated skylight area. Neither apply to
      # cases with skylight wells.
      tight = bm2 < roof.grossArea / 2 ? true : false
      thin  = depth.round(2) < (1.5 * wl).round(2) ? true : false

      set           = {}
      set[:box    ] = box
      set[:bm2    ] = bm2
      set[:tight  ] = tight
      set[:thin   ] = thin
      set[:roof   ] = roof
      set[:space  ] = space
      set[:m      ] = space.multiplier
      set[:sidelit] = rooms[space][:sidelit]
      set[:t0     ] = rooms[space][:t0]
      set[:t      ] = OpenStudio::Transformation.alignFace(roof.vertices)
      sets << set
    end
  end

  # Process outdoor-facing roof surfaces of plenums and attics above.
  rooms.each do |space, room|
    t0   = room[:t0]
    rufs = getRoofs(space) - room[:roofs]

    rufs.each do |ruf|
      next unless roof?(ruf)

      espace = ruf.space
      next if espace.empty?

      espace = espace.get
      next if espace.partofTotalFloorArea

      m = espace.multiplier

      if m != space.multiplier
        log(ERR, "Skipping #{ruf.nameString} (multiplier mismatch) (#{mth})")
        next
      end

      ti = transforms(espace)
      next unless ti[:t]

      ti   = ti[:t]
      rpts = ti * ruf.vertices

      # Process occupied room ceilings, as 1x or more are overlapping roof
      # surfaces above. Vertically cast, then fetch overlap.
      facets(space, "Surface", "RoofCeiling").each do |tile|
        tpts = t0 * tile.vertices
        ci0  = cast(tpts, rpts, ray)
        next if ci0.empty?

        olap = overlap(rpts, ci0)
        next if olap.empty?

        om2 = OpenStudio.getArea(olap)
        next if om2.empty?

        om2 = om2.get
        next if om2.round(2) < w02.round(2)

        box = boundedBox(olap)
        next if box.empty?

        # Adding skylight wells (plenums/attics) is contingent to safely
        # linking new base roof 'inserts' (as well as new ceiling ones)
        # through 'leader lines'. This requires an offset to ensure no
        # conflicts with roof or (ceiling) tile edges.
        #
        # @todo: Expand the method to factor in cases where simple 'side'
        #        cutouts can be supported (no need for leader lines), e.g.
        #        skylight strips along roof ridges.
        box = offset(box, -gap, 300)
        next if box.empty?

        bm2 = OpenStudio.getArea(box)
        next if bm2.empty?

        bm2 = bm2.get
        next if bm2.round(2) < wl2.round(2)

        width = alignedWidth(box, true)
        depth = alignedHeight(box, true)
        next if width < wl * 3
        next if depth < wl * 2

        # Vertically cast box onto tile below.
        cbox = cast(box, tpts, ray)
        next if cbox.empty?

        cm2 = OpenStudio.getArea(cbox)
        next if cm2.empty?

        cm2  = cm2.get
        box  = ti.inverse * box
        cbox = t0.inverse * cbox

        unless ceilings.key?(tile)
          floor = tile.adjacentSurface

          if floor.empty?
            log(ERR, "#{tile.nameString} adjacent floor? (#{mth})")
            next
          end

          floor = floor.get

          if floor.space.empty?
            log(ERR, "#{floor.nameString} space? (#{mth})")
            next
          end

          espce = floor.space.get

          unless espce == espace
            log(ERR, "#{espce.nameString} != #{espace.nameString}? (#{mth})")
            next
          end

          ceilings[tile]          = {}
          ceilings[tile][:roofs ] = []
          ceilings[tile][:space ] = space
          ceilings[tile][:floor ] = floor
        end

        ceilings[tile][:roofs] << ruf

        # Skylight set key:values are more detailed with suspended ceilings.
        # The overlap (:olap) remains in 'transformed' site coordinates (with
        # regards to the roof). The :box polygon reverts to attic/plenum space
        # coordinates, while the :cbox polygon is reset with regards to the
        # occupied space coordinates.
        set           = {}
        set[:olap   ] = olap
        set[:box    ] = box
        set[:cbox   ] = cbox
        set[:om2    ] = om2
        set[:bm2    ] = bm2
        set[:cm2    ] = cm2
        set[:tight  ] = false
        set[:thin   ] = false
        set[:roof   ] = ruf
        set[:space  ] = space
        set[:m      ] = space.multiplier
        set[:clng   ] = tile
        set[:t0     ] = t0
        set[:ti     ] = ti
        set[:t      ] = OpenStudio::Transformation.alignFace(ruf.vertices)
        set[:sidelit] = room[:sidelit]

        if unconditioned?(espace) # e.g. attic
          unless attics.key?(espace)
            attics[espace] = {ti: ti, m: m, bm2: 0, roofs: []}
          end

          attics[espace][:bm2  ] += bm2
          attics[espace][:roofs] << ruf

          set[:attic] = espace

          ceilings[tile][:attic] = espace
        else # e.g. plenum
          unless plenums.key?(espace)
            plenums[espace] = {ti: ti, m: m, bm2: 0, roofs: []}
          end

          plenums[espace][:bm2  ] += bm2
          plenums[espace][:roofs] << ruf

          set[:plenum] = espace

          ceilings[tile][:plenum] = espace
        end

        sets << set
        break # only 1x unique ruf/ceiling pair.
      end
    end
  end

  # Ensure uniqueness of plenum roofs.
  attics.values.each do |attic|
    attic[:roofs ].uniq!
    attic[:ridges] = getHorizontalRidges(attic[:roofs]) # @todo
  end

  plenums.values.each do |plenum|
    plenum[:roofs ].uniq!
    plenum[:ridges] = getHorizontalRidges(plenum[:roofs]) # @todo
  end

  # Regardless of the selected skylight arrangement pattern, the solution only
  # considers attic/plenum sets that can be successfully linked to leader line
  # anchors, for both roof and ceiling surfaces. First, attic/plenum roofs.
  [attics, plenums].each do |greniers|
    k = greniers == attics ? :attic : :plenum

    greniers.each do |spce, grenier|
      grenier[:roofs].each do |roof|
        sts = sets

        sts = sts.select { |st| st.key?(k) }
        sts = sts.select { |st| st.key?(:box) }
        sts = sts.select { |st| st.key?(:bm2) }
        sts = sts.select { |st| st.key?(:roof) }
        sts = sts.select { |st| st.key?(:space) }
        sts = sts.select { |st| st[k    ] == spce }
        sts = sts.select { |st| st[:roof] == roof }
        next if sts.empty?

        sts = sts.sort_by { |st| st[:bm2] }.reverse

        genAnchors(roof, sts, :box)
      end
    end
  end

  # Delete voided sets.
  sets.reject! { |set| set.key?(:void) }

  # Repeat leader line loop for ceilings.
  ceilings.each do |tile, ceiling|
    k = ceiling.key?(:attic) ? :attic : :plenum
    next unless ceiling.key?(k)

    space = ceiling[:space]
    spce  = ceiling[k]
    next unless ceiling.key?(:roofs)
    next unless rooms.key?(space)

    stz = []

    ceiling[:roofs].each do |roof|
      sts = sets

      sts = sts.select { |st| st.key?(k) }
      sts = sts.select { |st| st.key?(:cbox) }
      stz = stz.select { |st| st.key?(:cm2) }
      sts = sts.select { |st| st.key?(:roof) }
      sts = sts.select { |st| st.key?(:clng) }
      sts = sts.select { |st| st.key?(:space) }
      sts = sts.select { |st| st[k     ] == spce }
      sts = sts.select { |st| st[:roof ] == roof }
      sts = sts.select { |st| st[:clng ] == tile }
      sts = sts.select { |st| st[:space] == space }
      next unless sts.size == 1

      stz << sts.first
    end

    next if stz.empty?

    stz = stz.sort_by { |st| st[:cm2] }.reverse
    genAnchors(tile, stz, :cbox)
  end

  # Delete voided sets.
  sets.reject! { |set| set.key?(:void) }

  return empty("sets", mth, WRN, rm2) if sets.empty?

  # Sort sets, from largest to smallest bounded box area.
  sets = sets.sort_by { |st| st[:bm2] * st[:m] }.reverse

  # Any sidelit and/or sloped roofs being targeted?
  # @todo: enable double-ridged, sloped roofs have double-sloped
  #        skylights/wells (patterns "strip"/"strips").
  sidelit = sets.any? { |set| set[:sidelit] }
  sloped  = sets.any? { |set| set[:sloped ] }

  # Average sandbox area + revised 'working' SRR%.
  sbm2 = sets.map { |set| set[:bm2] }.reduce(:+)
  avm2 = sbm2 / sets.size
  srr2 = sm2 / sets.size / avm2

  # Precalculate skylight rows + cols, for each selected pattern. In the case
  # of 'cols x rows' arrays of skylights, the method initially overshoots
  # with regards to 'ideal' skylight placement, e.g.:
  #
  #   aceee.org/files/proceedings/2004/data/papers/SS04_Panel3_Paper18.pdf
  #
  # Skylight areas are subsequently contracted to strictly meet the target.
  sets.each_with_index do |set, i|
    thin   = set[:thin ]
    tight  = set[:tight]
    factor = tight ? 1.75 : 1.25
    well   = set.key?(:clng)
    space  = set[:space]
    room   = rooms[space]
    h      = room[:h]
    width  = alignedWidth( set[:box], true)
    depth  = alignedHeight(set[:box], true)
    barea  = set.key?(:om2) ? set[:om2] : set[:bm2]
    rtio   = barea / avm2
    skym2  = srr2 * barea * rtio

    # Flag set if too narrow/shallow to hold a single skylight.
    if well
      if width.round(2) < wl.round(2)
        log(WRN, "set #{i+1} well: Too narrow (#{mth})")
        set[:void] = true
        next
      end

      if depth.round(2) < wl.round(2)
        log(WRN, "set #{i+1} well: Too shallow (#{mth})")
        set[:void] = true
        next
      end
    else
      if width.round(2) < w0.round(2)
        log(WRN, "set #{i+1}: Too narrow (#{mth})")
        set[:void] = true
        next
      end

      if depth.round(2) < w0.round(2)
        log(WRN, "set #{i+1}: Too shallow (#{mth})")
        set[:void] = true
        next
      end
    end

    # Estimate number of skylight modules per 'pattern'. Default spacing
    # varies based on bounded box size (i.e. larger vs smaller rooms).
    patterns.each do |pattern|
      cols = 1
      rows = 1
      wx   = w0
      wy   = w0
      wxl  = well ? wl : nil
      wyl  = well ? wl : nil
      dX   = nil
      dY   = nil

      case pattern
      when "array" # min 2x cols x min 2x rows
        cols = 2
        rows = 2
        next if thin

        if tight
          sp = 1.4 * h / 2
          lx = width - cols * wx
          ly = depth - rows * wy
          next if lx.round(2) < sp.round(2)
          next if ly.round(2) < sp.round(2)

          cols = ((width - wx) / (wx + sp)).round(2).to_i + 1
          rows = ((depth - wy) / (wy + sp)).round(2).to_i + 1
          next if cols < 2
          next if rows < 2

          dX = bfr + f
          dY = bfr + f
        else
          sp = 1.4 * h
          lx = well ? (width - cols * wxl) / cols : (width - cols * wx) / cols
          ly = well ? (depth - rows * wyl) / rows : (depth - rows * wy) / rows
          next if lx.round(2) < sp.round(2)
          next if ly.round(2) < sp.round(2)

          if well
            cols = (width / (wxl + sp)).round(2).to_i
            rows = (depth / (wyl + sp)).round(2).to_i
          else
            cols = (width / (wx + sp)).round(2).to_i
            rows = (depth / (wy + sp)).round(2).to_i
          end

          next if cols < 2
          next if rows < 2

          ly = well ? (depth - rows * wyl) / rows : (depth - rows * wy) / rows
          dY = ly / 2
        end

        # Default allocated skylight area. If undershooting, inflate skylight
        # width/depth (with reduced spacing). For geometrically-constrained
        # cases, undershooting means not reaching 1.75x the required target.
        # Otherwise, undershooting means not reaching 1.25x the required
        # target. Any consequent overshooting is later corrected.
        tm2 = wx * cols * wy * rows

        # Inflate skylight width/depth (and reduce spacing) to reach target.
        if tm2.round(2) < factor * skym2.round(2)
          ratio2 = 1 + (factor * skym2 - tm2) / tm2
          ratio  = Math.sqrt(ratio2)

          sp  = wl
          wx *= ratio
          wy *= ratio
          wxl = wx + gap if well
          wyl = wy + gap if well

          if tight
            lx = (width - 2 * (bfr + f) - cols * wx) / (cols - 1)
            ly = (depth - 2 * (bfr + f) - rows * wy) / (rows - 1)
            lx = lx.round(2) < sp.round(2) ? sp : lx
            ly = ly.round(2) < sp.round(2) ? sp : ly
            wx = (width - 2 * (bfr + f) - (cols - 1) * lx) / cols
            wy = (depth - 2 * (bfr + f) - (rows - 1) * ly) / rows
          else
            if well
              lx  = (width - cols * wxl) / cols
              ly  = (depth - rows * wyl) / rows
              lx  = lx.round(2) < sp.round(2) ? sp : lx
              ly  = ly.round(2) < sp.round(2) ? sp : ly
              wxl = (width - cols * lx) / cols
              wyl = (depth - rows * ly) / rows
              wx  = wxl - gap
              wy  = wyl - gap
              ly  = (depth - rows * wyl) / rows
            else
              lx  = (width - cols * wx) / cols
              ly  = (depth - rows * wy) / rows
              lx  = lx.round(2) < sp.round(2) ? sp : lx
              ly  = ly.round(2) < sp.round(2) ? sp : ly
              wx  = (width - cols * lx) / cols
              wy  = (depth - rows * ly) / rows
              ly  = (depth - rows * wy) / rows
            end

            dY = ly / 2
          end
        end
      when "strips" # min 2x cols x 1x row
        cols = 2

        if tight
          sp = h / 2
          dX = bfr + f
          lx = width - cols * wx
          next if lx.round(2) < sp.round(2)

          cols = ((width - wx) / (wx + sp)).round(2).to_i + 1
          next if cols < 2

          if thin
            dY = bfr + f
            wy = depth - 2 * dY
            next if wy.round(2) < gap4
          else
            ly = depth - wy
            next if ly.round(2) < wl.round(2)

            dY = ly / 2
          end
        else
          sp = h

          if well
            lx = (width - cols * wxl) / cols
            next if lx.round(2) < sp.round(2)

            cols = (width / (wxl + sp)).round(2).to_i
            next if cols < 2

            ly = depth - wyl
            dY = ly / 2
            next if ly.round(2) < wl.round(2)
          else
            lx = (width - cols * wx) / cols
            next if lx.round(2) < sp.round(2)

            cols = (width / (wx + sp)).round(2).to_i
            next if cols < 2

            if thin
              dY = bfr + f
              wy = depth - 2 * dY
              next if wy.round(2) < gap4
            else
              ly = depth - wy
              next if ly.round(2) < wl.round(2)

              dY = ly / 2
            end
          end
        end

        tm2 = wx * cols * wy

        # Inflate skylight depth to reach target.
        if tm2.round(2) < factor * skym2.round(2)
          sp = wl

          # Skip if already thin.
          unless thin
            ratio2 = 1 + (factor * skym2 - tm2) / tm2

            wy *= ratio2

            if well
              wyl = wy + gap
              ly  = depth - wyl
              ly  = ly.round(2) < sp.round(2) ? sp : ly
              wyl = depth - ly
              wy  = wyl - gap
            else
              ly = depth - wy
              ly = ly.round(2) < sp.round(2) ? sp : ly
              wy = depth - ly
            end

            dY = ly / 2
          end
        end

        tm2 = wx * cols * wy

        # Inflate skylight width (and reduce spacing) to reach target.
        if tm2.round(2) < factor * skym2.round(2)
          ratio2 = 1 + (factor * skym2 - tm2) / tm2

          wx *= ratio2
          wxl = wx + gap if well

          if tight
            lx = (width - 2 * (bfr + f) - cols * wx) / (cols - 1)
            lx = lx.round(2) < sp.round(2) ? sp : lx
            wx = (width - 2 * (bfr + f) - (cols - 1) * lx) / cols
          else
            if well
              lx  = (width - cols * wxl) / cols
              lx  = lx.round(2) < sp.round(2) ? sp : lx
              wxl = (width - cols * lx) / cols
              wx  = wxl - gap
            else
              lx  = (width - cols * wx) / cols
              lx  = lx.round(2) < sp.round(2) ? sp : lx
              wx  = (width - cols * lx) / cols
            end
          end
        end
      else # "strip" 1 (long?) row x 1 column
        if tight
          sp = gap4
          dX = bfr + f
          wx = width - 2 * dX
          next if wx.round(2) < sp.round(2)

          if thin
            dY = bfr + f
            wy = depth - 2 * dY
            next if wy.round(2) < sp.round(2)
          else
            ly = depth - wy
            dY = ly / 2
            next if ly.round(2) < sp.round(2)
          end
        else
          sp = wl
          lx = well ? width - wxl : width - wx
          ly = well ? depth - wyl : depth - wy
          dY = ly / 2
          next if lx.round(2) < sp.round(2)
          next if ly.round(2) < sp.round(2)
        end

        tm2 = wx * wy

        # Inflate skylight width (and reduce spacing) to reach target.
        if tm2.round(2) < factor * skym2.round(2)
          unless tight
            ratio2 = 1 + (factor * skym2 - tm2) / tm2

            wx *= ratio2

            if well
              wxl = wx + gap
              lx  = width - wxl
              lx  = lx.round(2) < sp.round(2) ? sp : lx
              wxl = width - lx
              wx  = wxl - gap
            else
              lx  = width - wx
              lx  = lx.round(2) < sp.round(2) ? sp : lx
              wx  = width - lx
            end
          end
        end

        tm2 = wx * wy

        # Inflate skylight depth to reach target. Skip if already tight thin.
        if tm2.round(2) < factor * skym2.round(2)
          unless thin
            ratio2 = 1 + (factor * skym2 - tm2) / tm2

            wy *= ratio2

            if well
              wyl = wy + gap
              ly  = depth - wyl
              ly  = ly.round(2) < sp.round(2) ? sp : ly
              wyl = depth - ly
              wy  = wyl - gap
            else
              ly = depth - wy
              ly = ly.round(2) < sp.round(2) ? sp : ly
              wy = depth - ly
            end

            dY = ly / 2
          end
        end
      end

      st         = {}
      st[:tight] = tight
      st[:cols ] = cols
      st[:rows ] = rows
      st[:wx   ] = wx
      st[:wy   ] = wy
      st[:wxl  ] = wxl
      st[:wyl  ] = wyl
      st[:dX   ] = dX if dX
      st[:dY   ] = dY if dY

      set[pattern] = st
    end

    set[:void] = true unless patterns.any? { |k| set.key?(k) }
  end

  # Delete voided sets.
  sets.reject! { |set| set.key?(:void) }
  return empty("sets (2)", mth, WRN, rm2) if sets.empty?

  # Final reset of filters.
  filters.map! { |f| f.include?("b") ? f.delete("b") : f } unless sidelit
  filters.map! { |f| f.include?("c") ? f.delete("c") : f } unless sloped
  filters.map! { |f| f.include?("d") ? f.delete("d") : f } if plenums.empty?
  filters.map! { |f| f.include?("e") ? f.delete("e") : f } if attics.empty?

  filters.reject! { |f| f.empty? }
  filters.uniq!

  # Initialize skylight area tally (to increment).
  skm2 = 0

  # Assign skylight pattern.
  filters.each do |filter|
    next if skm2.round(2) >= sm2.round(2)

    dm2 = sm2 - skm2 # differential (remaining skylight area to meet).
    sts = sets
    sts = sts.reject  { |st| st.key?(:pattern) }

    if filter.include?("a")
      # Start with the default (ideal) allocation selection:
        # - large roof surface areas (e.g. retail, classrooms not corridors)
        # - not sidelit (favours core spaces)
        # - having flat roofs (avoids sloped roofs)
        # - not under plenums, nor attics (avoids wells)
      sts = sts.reject { |st| st[:sidelit]   }
      sts = sts.reject { |st| st[:sloped ]   }
      sts = sts.reject { |st| st.key?(:clng) }
    else
      sts = sts.reject { |st| st[:sidelit]     } unless filter.include?("b")
      sts = sts.reject { |st| st[:sloped]      } unless filter.include?("c")
      sts = sts.reject { |st| st.key?(:plenum) } unless filter.include?("d")
      sts = sts.reject { |st| st.key?(:attic)  } unless filter.include?("e")
    end

    next if sts.empty?

    # Tally precalculated skylights per pattern (once filtered).
    fpm2 = {}

    patterns.each do |pattern|
      sts.each do |st|
        next unless st.key?(pattern)

        cols = st[pattern][:cols]
        rows = st[pattern][:rows]
        wx   = st[pattern][:wx  ]
        wy   = st[pattern][:wy  ]

        fpm2[pattern] = {m2: 0, tight: false} unless fpm2.key?(pattern)

        fpm2[pattern][:m2   ] += st[:m] * wx * wy * cols * rows
        fpm2[pattern][:tight] = true if st[:tight]
      end
    end

    pattern = nil
    next if fpm2.empty?

    # Favour (large) arrays if meeting residual target, unless constrained.
    if fpm2.keys.include?("array")
      if fpm2["array"][:m2].round(2) >= dm2.round(2)
        pattern = "array" unless fpm2[:tight]
      end
    end

    unless pattern
      fpm2   = fpm2.sort_by { |_, fm2| fm2[:m2] }.to_h
      min_m2 = fpm2.values.first[:m2]
      max_m2 = fpm2.values.last[:m2]

      if min_m2.round(2) >= dm2.round(2)
        # If not large array, then retain pattern generating smallest skylight
        # area if ALL patterns >= residual target (deterministic sorting).
        fpm2.keep_if { |_, fm2| fm2[:m2].round(2) == min_m2.round(2) }

        if fpm2.keys.include?("array")
          pattern = "array"
        elsif fpm2.keys.include?("strips")
          pattern = "strips"
        else fpm2.keys.include?("strip")
          pattern = "strip"
        end
      else
        # Pick pattern offering greatest skylight area (deterministic sorting).
        fpm2.keep_if { |_, fm2| fm2[:m2].round(2) == max_m2.round(2) }

        if fpm2.keys.include?("strip")
          pattern = "strip"
        elsif fpm2.keys.include?("strips")
          pattern = "strips"
        else fpm2.keys.include?("array")
          pattern = "array"
        end
      end
    end

    skm2 += fpm2[pattern][:m2]

    # Update matching sets.
    sts.each do |st|
      sets.each do |set|
        next unless set.key?(pattern)
        next unless st[:roof] == set[:roof]
        next unless same?(st[:box], set[:box])

        if st.key?(:clng)
          next unless set.key?(:clng)
          next unless st[:clng] == set[:clng]
        end

        set[:pattern] = pattern
        set[:cols   ] = set[pattern][:cols]
        set[:rows   ] = set[pattern][:rows]
        set[:w      ] = set[pattern][:wx  ]
        set[:d      ] = set[pattern][:wy  ]
        set[:w0     ] = set[pattern][:wxl ]
        set[:d0     ] = set[pattern][:wyl ]
        set[:dX     ] = set[pattern][:dX  ] if set[pattern][:dX]
        set[:dY     ] = set[pattern][:dY  ] if set[pattern][:dY]
      end
    end
  end

  # Delete incomplete sets (same as rejected if 'voided').
  sets.reject! { |set| set.key?(:void) }
  sets.select! { |set| set.key?(:pattern) }
  return empty("sets (3)", mth, WRN, rm2) if sets.empty?

  # Skylight size contraction if overshot (e.g. scale down by -13% if > +13%).
  # Applied on a surface/pattern basis: individual skylight sizes may vary
  # from one surface to the next, depending on respective patterns.

  # First, skip whole sets altogether if their total m2 < (skm2 - sm2). Only
  # considered if significant discrepancies vs average set skylight m2.
  sbm2 = 0

  sets.each do |set|
    sbm2 += set[:cols] * set[:w] * set[:rows] * set[:d] * set[:m]
  end

  avm2 = sbm2 / sets.size

  if skm2.round(2) > sm2.round(2)
    sets.reverse.each do |set|
      break unless skm2.round(2) > sm2.round(2)

      stm2 = set[:cols] * set[:w] * set[:rows] * set[:d] * set[:m]
      next unless stm2 < 0.75 * avm2
      next unless stm2.round(2) < (skm2 - sm2).round(2)

      skm2 -= stm2
      set[:void] = true
    end
  end

  sets.reject! { |set| set.key?(:void) }
  return empty("sets (4)", mth, WRN, rm2) if sets.empty?

  # Size contraction: round 1: low-hanging fruit.
  if skm2.round(2) > sm2.round(2)
    ratio2 = 1 - (skm2 - sm2) / skm2
    ratio  = Math.sqrt(ratio2)

    sets.each do |set|
      am2 = set[:cols] * set[:w] * set[:rows] * set[:d] * set[:m]
      xr  = set[:w]
      yr  = set[:d]

      if xr > w0
        xr = xr * ratio < w0 ? w0 : xr * ratio
      end

      if yr > w0
        yr = yr * ratio < w0 ? w0 : yr * ratio
      end

      xm2 = set[:cols] * xr * set[:rows] * yr * set[:m]
      next if xm2.round(2) == am2.round(2)

      set[:dY] += (set[:d] - yr) / 2
      set[:dX] += (set[:w] - xr) / 2 if set.key?(:dX)
      set[:w ]  = xr
      set[:d ]  = yr
      set[:w0]  = set[:w] + gap
      set[:d0]  = set[:d] + gap

      skm2 -= (am2 - xm2)
    end
  end

  # Size contraction: round 2: prioritize larger sets.
  adm2 = 0

  sets.each_with_index do |set, i|
    next if set[:w].round(2) <= w0
    next if set[:d].round(2) <= w0

    adm2 += set[:cols] * set[:w] * set[:rows] * set[:d] * set[:m]
  end

  if skm2.round(2) > sm2.round(2) && adm2.round(2) > sm2.round(2)
    ratio2 = 1 - (adm2 - sm2) / adm2
    ratio  = Math.sqrt(ratio2)

    sets.each do |set|
      next if set[:w].round(2) <= w0
      next if set[:d].round(2) <= w0

      am2 = set[:cols] * set[:w] * set[:rows] * set[:d] * set[:m]
      xr  = set[:w]
      yr  = set[:d]

      if xr > w0
        xr = xr * ratio < w0 ? w0 : xr * ratio
      end

      if yr > w0
        yr = yr * ratio < w0 ? w0 : yr * ratio
      end

      xm2 = set[:cols] * xr * set[:rows] * yr * set[:m]
      next if xm2.round(2) == am2.round(2)

      set[:dY] += (set[:d] - yr) / 2
      set[:dX] += (set[:w] - xr) / 2 if set.key?(:dX)
      set[:w ]  = xr
      set[:d ]  = yr
      set[:w0]  = set[:w] + gap
      set[:d0]  = set[:d] + gap

      skm2 -= (am2 - xm2)
      adm2 -= (am2 - xm2)
    end
  end

  # Size contraction: round 3: Resort to sizes < requested w0.
  if skm2.round(2) > sm2.round(2)
    ratio2 = 1 - (skm2 - sm2) / skm2
    ratio  = Math.sqrt(ratio2)

    sets.each do |set|
      break unless skm2.round(2) > sm2.round(2)

      am2 = set[:cols] * set[:w] * set[:rows] * set[:d] * set[:m]
      xr  = set[:w]
      yr  = set[:d]

      if xr > gap4
        xr = xr * ratio < gap4 ? gap4 : xr * ratio
      end

      if yr > gap4
        yr = yr * ratio < gap4 ? gap4 : yr * ratio
      end

      xm2 = set[:cols] * xr * set[:rows] * yr * set[:m]
      next if xm2.round(2) == am2.round(2)

      set[:dY] += (set[:d] - yr) / 2
      set[:dX] += (set[:w] - xr) / 2 if set.key?(:dX)
      set[:w ]  = xr
      set[:d ]  = yr
      set[:w0]  = set[:w] + gap
      set[:d0]  = set[:d] + gap

      skm2 -= (am2 - xm2)
    end
  end

  # Log warning if unable to entirely contract skylight dimensions.
  if skm2.round(2) > sm2.round(2)
    log(WRN, "Skylights slightly oversized (#{mth})")
  end

  # Generate skylight well vertices for roofs, attics & plenums.
  [attics, plenums].each do |greniers|
    k = greniers == attics ? :attic : :plenum

    greniers.each do |spce, grenier|
      grenier[:roofs].each do |roof|
        sts = sets
        sts = sts.select { |st| st.key?(k) }
        sts = sts.select { |st| st.key?(:pattern) }
        sts = sts.select { |st| st.key?(:clng) }
        sts = sts.select { |st| st.key?(:roof) }
        sts = sts.select { |st| st.key?(:space) }
        sts = sts.select { |st| st[:roof] == roof }
        sts = sts.select { |st| st[k    ] == spce }
        sts = sts.select { |st| st.key?(st[:pattern]) }
        sts = sts.select { |st| rooms.key?(st[:space]) }
        sts = sts.select { |st| st.key?(:ld) }
        sts = sts.select { |st| st[:ld].key?(roof) }
        next if sts.empty?

        # If successful, 'genInserts' returns extended ROOF surface vertices,
        # including leader lines to support cutouts. The method also generates
        # new roof inserts. See key:value pair :vts. The FINAL go/no-go is
        # contingent to successfully inserting corresponding room ceiling
        # inserts (vis-à-vis attic/plenum floor below).
        vz = genInserts(roof, sts)
        next if vz.empty?

        roof.setVertices(vz)
      end
    end
  end

  # Repeat for ceilings below attic/plenum floors.
  ceilings.each do |tile, ceiling|
    k = ceiling.key?(:attic) ? :attic : :plenum
    next unless ceiling.key?(k)
    next unless ceiling.key?(:roofs)

    greniers = ceiling.key?(:attic) ? attics : plenums
    space    = ceiling[:space]
    spce     = ceiling[k     ]
    floor    = ceiling[:floor]
    next unless rooms.key?(space)
    next unless greniers.key?(spce)

    room    = rooms[space]
    grenier = greniers[spce]
    ti      = grenier[:ti]
    t0      = room[:t0]
    stz     = []

    ceiling[:roofs].each do |roof|
      sts = sets

      sts = sts.select { |st| st.key?(k) }
      sts = sts.select { |st| st.key?(:pattern) }
      sts = sts.select { |st| st.key?(:clng) }
      sts = sts.select { |st| st.key?(:cm2) }
      sts = sts.select { |st| st.key?(:roof) }
      sts = sts.select { |st| st.key?(:space) }
      sts = sts.select { |st| st[:clng] == tile }
      sts = sts.select { |st| st[:roof] == roof }
      sts = sts.select { |st| st[k    ] == spce }
      sts = sts.select { |st| rooms.key?(st[:space]) }
      sts = sts.select { |st| st.key?(:ld) }
      sts = sts.select { |st| st.key?(:vtx) }
      sts = sts.select { |st| st.key?(:vts) }
      sts = sts.select { |st| st[:ld].key?(roof) }
      sts = sts.select { |st| st[:ld].key?(tile) }
      next unless sts.size == 1

      stz << sts.first
    end

    next if stz.empty?

    # Add new roof inserts & skylights for the (now) toplit space.
    stz.each_with_index do |st, i|
      sub         = {}
      sub[:type ] = "Skylight"
      sub[:frame] = frame if frame
      sub[:sill ] = gap / 2

      st[:vts].each do |id, vt|
        roof = OpenStudio::Model::Surface.new(t0.inverse * (ti * vt), mdl)
        roof.setSpace(space)
        roof.setName("#{id}:#{space.nameString}")

        # Generate well walls.
        vX = cast(roof, tile, ray)
        s0 = getSegments(t0 * roof.vertices)
        sX = getSegments(t0 * vX)

        s0.each_with_index do |sg, j|
          sg0 = sg.to_a
          sgX = sX[j].to_a
          vec = OpenStudio::Point3dVector.new
          vec << sg0.first
          vec << sg0.last
          vec << sgX.last
          vec << sgX.first

          v_grenier = ti.inverse * vec
          v_room    = (t0.inverse * vec).to_a.reverse

          grenier_wall = OpenStudio::Model::Surface.new(v_grenier, mdl)
          grenier_wall.setSpace(spce)
          grenier_wall.setName("#{id}:#{i}:#{j}:#{spce.nameString}")

          room_wall = OpenStudio::Model::Surface.new(v_room, mdl)
          room_wall.setSpace(space)
          room_wall.setName("#{id}:#{i}:#{j}:#{space.nameString}")

          grenier_wall.setAdjacentSurface(room_wall)
          room_wall.setAdjacentSurface(grenier_wall)
        end

        # Add individual skylights. Independently of the set layout (rows x
        # cols), individual roof inserts may be deeper than wider (or
        # vice-versa). Adapt skylight width vs depth accordingly.
        if st[:d].round(2) > st[:w].round(2)
          sub[:width ] = st[:d] - f2
          sub[:height] = st[:w] - f2
        else
          sub[:width ] = st[:w] - f2
          sub[:height] = st[:d] - f2
        end

        sub[:id] = roof.nameString
        addSubs(roof, sub, false, true, true)
      end
    end

    # Vertically-cast set roof :vtx onto ceiling.
    stz.each do |st|
      st[:cvtx] = t0.inverse * cast(ti * st[:vtx], t0 * tile.vertices, ray)
    end

    # Extended ceiling vertices.
    vertices = genExtendedVertices(tile, stz, :cvtx)
    next if vertices.empty?

    # Reset ceiling and adjacent floor vertices.
    tile.setVertices(vertices)
    floor.setVertices(ti.inverse * (t0 * vertices).to_a.reverse)
  end

  # Loop through 'direct' roof surfaces of rooms to toplit (no attics or
  # plenums). No overlaps, so no relative space coordinate adjustments.
  rooms.each do |space, room|
    room[:roofs].each do |roof|
      sets.each_with_index do |st, i|
        next unless st.key?(:roof)
        next unless st[:roof] == roof
        next     if st.key?(:clng)
        next unless st.key?(:box)
        next unless st.key?(:cols)
        next unless st.key?(:rows)
        next unless st.key?(:d)
        next unless st.key?(:w)
        next unless st.key?(:dY)

        w1 = st[:w ] - f2
        d1 = st[:d ] - f2
        dY = st[:dY]

        st[:rows].times.each do |j|
          sub            = {}
          sub[:type    ] = "Skylight"
          sub[:count   ] = st[:cols]
          sub[:width   ] = w1
          sub[:height  ] = d1
          sub[:frame   ] = frame if frame
          sub[:id      ] = "#{roof.nameString}:#{i}:#{j}"
          sub[:sill    ] = dY + j * (2 * dY + d1)
          sub[:r_buffer] = st[:dX] if st[:dX]
          sub[:l_buffer] = st[:dX] if st[:dX]

          addSubs(roof, sub, false, true, true)
        end
      end
    end
  end

  rm2
end

#addSubs(s = nil, subs = [], clear = false, bound = false, realign = false, bfr = 0.005) ⇒ Bool, false

Adds sub surfaces (e.g. windows, doors, skylights) to surface.

Parameters:

  • s (OpenStudio::Model::Surface) (defaults to: nil)

    a model surface

  • subs (Array<Hash>) (defaults to: [])

    requested attributes

  • clear (Bool) (defaults to: false)

    whether to remove current sub surfaces

  • bound (Bool) (defaults to: false)

    whether to add subs wrt surface’s bounded box

  • realign (Bool) (defaults to: false)

    whether to first realign bounded box

  • bfr (#to_f) (defaults to: 0.005)

    safety buffer, to maintain near other edges

Options Hash (subs):

  • :id (#to_s)

    identifier e.g. “Window 007”

  • :type (#to_s) — default: "FixedWindow"

    OpenStudio subsurface type

  • :count (#to_i) — default: 1

    number of individual subs per array

  • :multiplier (#to_i) — default: 1

    OpenStudio subsurface multiplier

  • :frame (#frameWidth) — default: nil

    OpenStudio frame & divider object

  • :assembly (#isFenestration) — default: nil

    OpenStudio construction

  • :ratio (#to_f)

    e.g. %FWR [0.0, 1.0]

  • :head (#to_f) — default: OSut::HEAD

    e.g. door height (incl frame)

  • :sill (#to_f) — default: OSut::SILL

    e.g. window sill (incl frame)

  • :height (#to_f)

    sill-to-head height

  • :width (#to_f)

    e.g. door width

  • :offset (#to_f)

    left-right centreline dX e.g. between doors

  • :centreline (#to_f)

    left-right dX (sub/array vs base)

  • :r_buffer (#to_f)

    gap between sub/array and right corner

  • :l_buffer (#to_f)

    gap between sub/array and left corner

Returns:

  • (Bool)

    whether addition is successful

  • (false)

    if invalid input (see logs)



5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
# File 'lib/osut/utils.rb', line 5284

def addSubs(s = nil, subs = [], clear = false, bound = false, realign = false, bfr = 0.005)
  mth = "OSut::#{__callee__}"
  v   = OpenStudio.openStudioVersion.split(".").join.to_i
  cl1 = OpenStudio::Model::Surface
  cl2 = Array
  cl3 = Hash
  min = 0.050 # minimum ratio value ( 5%)
  max = 0.950 # maximum ratio value (95%)
  no  = false

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Exit if mismatched or invalid argument classes.
  sbs = subs.is_a?(cl3) ? [subs] : subs
  sbs = sbs.respond_to?(:to_a) ? sbs.to_a : []
  return mismatch("surface",  s, cl1, mth, DBG, no) unless s.is_a?(cl1)
  return mismatch("subs",  subs, cl2, mth, DBG, no)     if sbs.empty?
  return empty("surface points",      mth, DBG, no)     if poly(s).empty?

  subs = sbs
  nom  = s.nameString
  mdl  = s.model

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Purge existing sub surfaces?
  unless [true, false].include?(clear)
    log(WRN, "#{nom}: Keeping existing sub surfaces (#{mth})")
    clear = false
  end

  s.subSurfaces.map(&:remove) if clear

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Add sub surfaces with respect to base surface's bounded box? This is
  # often useful (in some cases necessary) with irregular or concave surfaces.
  # If true, sub surface parameters (e.g. height, offset, centreline) no
  # longer apply to the original surface 'bounding' box, but instead to its
  # largest 'bounded' box. This can be combined with the 'realign' parameter.
  unless [true, false].include?(bound)
    log(WRN, "#{nom}: Ignoring bounded box (#{mth})")
    bound = false
  end

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Force re-alignment of base surface (or its 'bounded' box)? False by
  # default (ideal for vertical/tilted walls & sloped roofs). If set to true
  # for a narrow wall for instance, an array of sub surfaces will be added
  # from bottom to top (rather from left to right).
  unless [true, false].include?(realign)
    log(WRN, "#{nom}: Ignoring realignment (#{mth})")
    realign = false
  end

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Ensure minimum safety buffer.
  if bfr.respond_to?(:to_f)
    bfr = bfr.to_f
    return negative("safety buffer", mth, ERR, no) if bfr.round(2) < 0

    msg = "Safety buffer < 5mm may generate invalid geometry (#{mth})"
    log(WRN, msg) if bfr.round(2) < 0.005
  else
    log(ERR, "Setting safety buffer to 5mm (#{mth})")
    bfr = 0.005
  end

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Allowable sub surface types ... & Frame&Divider enabled
  #   - "FixedWindow"             | true
  #   - "OperableWindow"          | true
  #   - "Door"                    | false
  #   - "GlassDoor"               | true
  #   - "OverheadDoor"            | false
  #   - "Skylight"                | false if v < 321
  #   - "TubularDaylightDome"     | false
  #   - "TubularDaylightDiffuser" | false
  type  = "FixedWindow"
  types = OpenStudio::Model::SubSurface.validSubSurfaceTypeValues
  stype = s.surfaceType # Wall, RoofCeiling or Floor

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  t   = OpenStudio::Transformation.alignFace(s.vertices)
  s0  = poly(s, false, false, false, t, :ulc)
  s00 = nil

  # Adapt sandbox if user selects to 'bound' and/or 'realign'.
  if bound
    box = boundedBox(s0)

    if realign
      s00 = getRealignedFace(box, true)
      return invalid("bound realignment", mth, 0, DBG, false) unless s00[:set]
    end
  elsif realign
    s00 = getRealignedFace(s0, false)
    return invalid("unbound realignment", mth, 0, DBG, false) unless s00[:set]
  end

  max_x = s00 ? width( s00[:set]) :  width(s0)
  max_y = s00 ? height(s00[:set]) : height(s0)
  mid_x = max_x / 2
  mid_y = max_y / 2

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Assign default values to certain sub keys (if missing), +more validation.
  subs.each_with_index do |sub, index|
    return mismatch("sub", sub, cl4, mth, DBG, no) unless sub.is_a?(cl3)

    # Required key:value pairs (either set by the user or defaulted).
    sub[:frame     ] = nil  unless sub.key?(:frame     )
    sub[:assembly  ] = nil  unless sub.key?(:assembly  )
    sub[:count     ] = 1    unless sub.key?(:count     )
    sub[:multiplier] = 1    unless sub.key?(:multiplier)
    sub[:id        ] = ""   unless sub.key?(:id        )
    sub[:type      ] = type unless sub.key?(:type      )
    sub[:type      ] = trim(sub[:type])
    sub[:id        ] = trim(sub[:id])
    sub[:type      ] = type                   if sub[:type].empty?
    sub[:id        ] = "OSut:#{nom}:#{index}" if sub[:id  ].empty?
    sub[:count     ] = 1 unless sub[:count     ].respond_to?(:to_i)
    sub[:multiplier] = 1 unless sub[:multiplier].respond_to?(:to_i)
    sub[:count     ] = sub[:count     ].to_i
    sub[:multiplier] = sub[:multiplier].to_i
    sub[:count     ] = 1 if sub[:count     ] < 1
    sub[:multiplier] = 1 if sub[:multiplier] < 1

    id = sub[:id]

    # If sub surface type is invalid, log/reset. Additional corrections may
    # be enabled once a sub surface is actually instantiated.
    unless types.include?(sub[:type])
      log(WRN, "Reset invalid '#{id}' type to '#{type}' (#{mth})")
      sub[:type] = type
    end

    # Log/ignore (optional) frame & divider object.
    unless sub[:frame].nil?
      if sub[:frame].respond_to?(:frameWidth)
        sub[:frame] = nil if sub[:type] == "Skylight" && v < 321
        sub[:frame] = nil if sub[:type] == "Door"
        sub[:frame] = nil if sub[:type] == "OverheadDoor"
        sub[:frame] = nil if sub[:type] == "TubularDaylightDome"
        sub[:frame] = nil if sub[:type] == "TubularDaylightDiffuser"
        log(WRN, "Skip '#{id}' FrameDivider (#{mth})") if sub[:frame].nil?
      else
        sub[:frame] = nil
        log(WRN, "Skip '#{id}' invalid FrameDivider object (#{mth})")
      end
    end

    # The (optional) "assembly" must reference a valid OpenStudio
    # construction base, to explicitly assign to each instantiated sub
    # surface. If invalid, log/reset/ignore. Additional checks are later
    # activated once a sub surface is actually instantiated.
    unless sub[:assembly].nil?
      unless sub[:assembly].respond_to?(:isFenestration)
        log(WRN, "Skip invalid '#{id}' construction (#{mth})")
        sub[:assembly] = nil
      end
    end

    # Log/reset negative float values. Set ~0.0 values to 0.0.
    sub.each do |key, value|
      next if key == :count
      next if key == :multiplier
      next if key == :type
      next if key == :id
      next if key == :frame
      next if key == :assembly

      unless value.respond_to?(:to_f)
        return mismatch(key, value, Float, mth, DBG, no)
      end

      next if key == :centreline

      negative(key, mth, WRN) if value < 0
      value = 0.0             if value.abs < TOL
    end
  end

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Log/reset (or abandon) conflicting user-set geometry key:value pairs:
  #   :head       e.g. std 80" door + frame/buffers (+ m)
  #   :sill       e.g. std 30" sill + frame/buffers (+ m)
  #   :height     any sub surface height, below "head" (+ m)
  #   :width      e.g. 1.200 m
  #   :offset     if array (+ m)
  #   :centreline left or right of base surface centreline (+/- m)
  #   :r_buffer   buffer between sub/array and right-side corner (+ m)
  #   :l_buffer   buffer between sub/array and left-side corner (+ m)
  #
  # If successful, this will generate sub surfaces and add them to the model.
  subs.each do |sub|
    # Set-up unique sub parameters:
    #   - Frame & Divider "width"
    #   - minimum "clear glazing" limits
    #   - buffers, etc.
    id         = sub[:id]
    frame      = sub[:frame] ? sub[:frame].frameWidth : 0
    frames     = 2 * frame
    buffer     = frame + bfr
    buffers    = 2 * buffer
    dim        = 3 * frame > 0.200 ? 3 * frame : 0.200
    glass      = dim - frames
    min_sill   = buffer
    min_head   = buffers + glass
    max_head   = max_y - buffer
    max_sill   = max_head - (buffers + glass)
    min_ljamb  = buffer
    max_ljamb  = max_x - (buffers + glass)
    min_rjamb  = buffers + glass
    max_rjamb  = max_x - buffer
    max_height = max_y - buffers
    max_width  = max_x - buffers

    # Default sub surface "head" & "sill" height, unless user-specified.
    typ_head = HEAD
    typ_sill = SILL

    if sub.key?(:ratio)
      typ_head = mid_y * (1 + sub[:ratio])     if sub[:ratio] > 0.75
      typ_head = mid_y * (1 + sub[:ratio]) unless stype.downcase == "wall"
      typ_sill = mid_y * (1 - sub[:ratio])     if sub[:ratio] > 0.75
      typ_sill = mid_y * (1 - sub[:ratio]) unless stype.downcase == "wall"
    end

    # Log/reset "height" if beyond min/max.
    if sub.key?(:height)
      unless sub[:height].between?(glass - TOL2, max_height + TOL2)
        log(WRN, "Reset '#{id}' height #{sub[:height].round(3)}m (#{mth})")
        sub[:height] = sub[:height].clamp(glass, max_height)
        log(WRN, "Height '#{id}' reset to #{sub[:height].round(3)}m (#{mth})")
      end
    end

    # Log/reset "head" height if beyond min/max.
    if sub.key?(:head)
      unless sub[:head].between?(min_head - TOL2, max_head + TOL2)
        log(WRN, "Reset '#{id}' head #{sub[:head].round(3)}m (#{mth})")
        sub[:head] = sub[:head].clamp(min_head, max_head)
        log(WRN, "Head '#{id}' reset to #{sub[:head].round(3)}m (#{mth})")
      end
    end

    # Log/reset "sill" height if beyond min/max.
    if sub.key?(:sill)
      unless sub[:sill].between?(min_sill - TOL2, max_sill + TOL2)
        log(WRN, "Reset '#{id}' sill #{sub[:sill].round(3)}m (#{mth})")
        sub[:sill] = sub[:sill].clamp(min_sill, max_sill)
        log(WRN, "Sill '#{id}' reset to #{sub[:sill].round(3)}m (#{mth})")
      end
    end

    # At this point, "head", "sill" and/or "height" have been tentatively
    # validated (and/or have been corrected) independently from one another.
    # Log/reset "head" & "sill" heights if conflicting.
    if sub.key?(:head) && sub.key?(:sill) && sub[:head] < sub[:sill] + glass
      sill = sub[:head] - glass

      if sill < min_sill - TOL2
        sub[:ratio     ] = 0 if sub.key?(:ratio)
        sub[:count     ] = 0
        sub[:multiplier] = 0
        sub[:height    ] = 0 if sub.key?(:height)
        sub[:width     ] = 0 if sub.key?(:width)
        log(ERR, "Skip: invalid '#{id}' head/sill combo (#{mth})")
        next
      else
        log(WRN, "(Re)set '#{id}' sill #{sub[:sill].round(3)}m (#{mth})")
        sub[:sill] = sill
        log(WRN, "Sill '#{id}' (re)set to #{sub[:sill].round(3)}m (#{mth})")
      end
    end

    # Attempt to reconcile "head", "sill" and/or "height". If successful,
    # all 3x parameters are set (if missing), or reset if invalid.
    if sub.key?(:head) && sub.key?(:sill)
      height = sub[:head] - sub[:sill]

      if sub.key?(:height) && (sub[:height] - height).abs > TOL2
        log(WRN, "(Re)set '#{id}' height #{sub[:height].round(3)}m (#{mth})")
        log(WRN, "Height '#{id}' (re)set to #{height.round(3)}m (#{mth})")
      end

      sub[:height] = height
    elsif sub.key?(:head) # no "sill"
      if sub.key?(:height)
        sill = sub[:head] - sub[:height]

        if sill < min_sill - TOL2
          sill   = min_sill
          height = sub[:head] - sill

          if height < glass
            sub[:ratio     ] = 0 if sub.key?(:ratio)
            sub[:count     ] = 0
            sub[:multiplier] = 0
            sub[:height    ] = 0 if sub.key?(:height)
            sub[:width     ] = 0 if sub.key?(:width)
            log(ERR, "Skip: invalid '#{id}' head/height combo (#{mth})")
            next
          else
            log(WRN, "(Re)set '#{id}' height #{sub[:height].round(3)}m (#{mth})")
            sub[:sill  ] = sill
            sub[:height] = height
            log(WRN, "Height '#{id}' re(set) #{sub[:height].round(3)}m (#{mth})")
          end
        else
          sub[:sill] = sill
        end
      else
        sub[:sill  ] = typ_sill
        sub[:height] = sub[:head] - sub[:sill]
      end
    elsif sub.key?(:sill) # no "head"
      if sub.key?(:height)
        head = sub[:sill] + sub[:height]

        if head > max_head - TOL2
          head   = max_head
          height = head - sub[:sill]

          if height < glass
            sub[:ratio     ] = 0 if sub.key?(:ratio)
            sub[:count     ] = 0
            sub[:multiplier] = 0
            sub[:height    ] = 0 if sub.key?(:height)
            sub[:width     ] = 0 if sub.key?(:width)
            log(ERR, "Skip: invalid '#{id}' sill/height combo (#{mth})")
            next
          else
            log(WRN, "(Re)set '#{id}' height #{sub[:height].round(3)}m (#{mth})")
            sub[:head  ] = head
            sub[:height] = height
            log(WRN, "Height '#{id}' reset to #{sub[:height].round(3)}m (#{mth})")
          end
        else
          sub[:head] = head
        end
      else
        sub[:head  ] = typ_head
        sub[:height] = sub[:head] - sub[:sill]
      end
    elsif sub.key?(:height) # neither "head" nor "sill"
      head = s00 ? mid_y + sub[:height]/2 : typ_head
      sill = head - sub[:height]

      if sill < min_sill
        sill = min_sill
        head = sill + sub[:height]
      end

      sub[:head] = head
      sub[:sill] = sill
    else
      sub[:head  ] = typ_head
      sub[:sill  ] = typ_sill
      sub[:height] = sub[:head] - sub[:sill]
    end

    # Log/reset "width" if beyond min/max.
    if sub.key?(:width)
      unless sub[:width].between?(glass - TOL2, max_width + TOL2)
        log(WRN, "Reset '#{id}' width #{sub[:width].round(3)}m (#{mth})")
        sub[:width] = sub[:width].clamp(glass, max_width)
        log(WRN, "Width '#{id}' reset to #{sub[:width].round(3)}m (#{mth})")
      end
    end

    # Log/reset "count" if < 1 (or not an Integer)
    if sub[:count].respond_to?(:to_i)
      sub[:count] = sub[:count].to_i

      if sub[:count] < 1
        sub[:count] = 1
        log(WRN, "Reset '#{id}' count to min 1 (#{mth})")
      end
    else
      sub[:count] = 1
    end

    sub[:count] = 1 unless sub.key?(:count)

    # Log/reset if left-sided buffer under min jamb position.
    if sub.key?(:l_buffer)
      if sub[:l_buffer] < min_ljamb - TOL
        log(WRN, "Reset '#{id}' left buffer #{sub[:l_buffer].round(3)}m (#{mth})")
        sub[:l_buffer] = min_ljamb
        log(WRN, "Left buffer '#{id}' reset to #{sub[:l_buffer].round(3)}m (#{mth})")
      end
    end

    # Log/reset if right-sided buffer beyond max jamb position.
    if sub.key?(:r_buffer)
      if sub[:r_buffer] > max_rjamb - TOL
        log(WRN, "Reset '#{id}' right buffer #{sub[:r_buffer].round(3)}m (#{mth})")
        sub[:r_buffer] = min_rjamb
        log(WRN, "Right buffer '#{id}' reset to #{sub[:r_buffer].round(3)}m (#{mth})")
      end
    end

    centre  = mid_x
    centre += sub[:centreline] if sub.key?(:centreline)
    n       = sub[:count     ]
    h       = sub[:height    ] + frames
    w       = 0 # overall width of sub(s) bounding box (to calculate)
    x0      = 0 # left-side X-axis coordinate of sub(s) bounding box
    xf      = 0 # right-side X-axis coordinate of sub(s) bounding box

    # Log/reset "offset", if conflicting vs "width".
    if sub.key?(:ratio)
      if sub[:ratio] < TOL
        sub[:ratio     ] = 0
        sub[:count     ] = 0
        sub[:multiplier] = 0
        sub[:height    ] = 0 if sub.key?(:height)
        sub[:width     ] = 0 if sub.key?(:width)
        log(ERR, "Skip: ratio ~0 (#{mth})")
        next
      end

      # Log/reset if "ratio" beyond min/max?
      unless sub[:ratio].between?(min, max)
        log(WRN, "Reset ratio #{sub[:ratio].round(3)} (#{mth})")
        sub[:ratio] = sub[:ratio].clamp(min, max)
        log(WRN, "Ratio reset to #{sub[:ratio].round(3)} (#{mth})")
      end

      # Log/reset "count" unless 1.
      unless sub[:count] == 1
        sub[:count] = 1
        log(WRN, "Reset count (ratio) to 1 (#{mth})")
      end

      area  = s.grossArea * sub[:ratio] # sub m2, including (optional) frames
      w     = area / h
      width = w - frames
      x0    = centre - w/2
      xf    = centre + w/2

      if sub.key?(:l_buffer)
        if sub.key?(:centreline)
          log(WRN, "Skip '#{id}' left buffer (vs centreline) (#{mth})")
        else
          x0     = sub[:l_buffer] - frame
          xf     = x0 + w
          centre = x0 + w/2
        end
      elsif sub.key?(:r_buffer)
        if sub.key?(:centreline)
          log(WRN, "Skip '#{id}' right buffer (vs centreline) (#{mth})")
        else
          xf     = max_x - sub[:r_buffer] + frame
          x0     = xf - w
          centre = x0 + w/2
        end
      end

      # Too wide?
      if x0 < min_ljamb - TOL2 || xf > max_rjamb - TOL2
        sub[:ratio     ] = 0 if sub.key?(:ratio)
        sub[:count     ] = 0
        sub[:multiplier] = 0
        sub[:height    ] = 0 if sub.key?(:height)
        sub[:width     ] = 0 if sub.key?(:width)
        log(ERR, "Skip '#{id}': invalid (ratio) width/centreline (#{mth})")
        next
      end

      if sub.key?(:width) && (sub[:width] - width).abs > TOL
        log(WRN, "Reset '#{id}' width (ratio) #{sub[:width].round(2)}m (#{mth})")
        sub[:width] = width
        log(WRN, "Width (ratio) '#{id}' reset to #{sub[:width].round(2)}m (#{mth})")
      end

      sub[:width] = width unless sub.key?(:width)
    else
      unless sub.key?(:width)
        sub[:ratio     ] = 0 if sub.key?(:ratio)
        sub[:count     ] = 0
        sub[:multiplier] = 0
        sub[:height    ] = 0 if sub.key?(:height)
        sub[:width     ] = 0 if sub.key?(:width)
        log(ERR, "Skip: missing '#{id}' width (#{mth})")
        next
      end

      width  = sub[:width] + frames
      gap    = (max_x - n * width) / (n + 1)
      gap    = sub[:offset] - width if sub.key?(:offset)
      gap    = 0                    if gap < buffer
      offset = gap + width

      if sub.key?(:offset) && (offset - sub[:offset]).abs > TOL
        log(WRN, "Reset '#{id}' sub offset #{sub[:offset].round(2)}m (#{mth})")
        sub[:offset] = offset
        log(WRN, "Sub offset (#{id}) reset to #{sub[:offset].round(2)}m (#{mth})")
      end

      sub[:offset] = offset unless sub.key?(:offset)

      # Overall width (including frames) of bounding box around array.
      w  = n * width + (n - 1) * gap
      x0 = centre - w/2
      xf = centre + w/2

      if sub.key?(:l_buffer)
        if sub.key?(:centreline)
          log(WRN, "Skip '#{id}' left buffer (vs centreline) (#{mth})")
        else
          x0     = sub[:l_buffer] - frame
          xf     = x0 + w
          centre = x0 + w/2
        end
      elsif sub.key?(:r_buffer)
        if sub.key?(:centreline)
          log(WRN, "Skip '#{id}' right buffer (vs centreline) (#{mth})")
        else
          xf     = max_x - sub[:r_buffer] + frame
          x0     = xf - w
          centre = x0 + w/2
        end
      end

      # Too wide?
      if x0 < buffer - TOL2 || xf > max_x - buffer - TOL2
        sub[:ratio     ] = 0 if sub.key?(:ratio)
        sub[:count     ] = 0
        sub[:multiplier] = 0
        sub[:height    ] = 0 if sub.key?(:height)
        sub[:width     ] = 0 if sub.key?(:width)
        log(ERR, "Skip: invalid array width/centreline (#{mth})")
        next
      end
    end

    # Initialize left-side X-axis coordinate of only/first sub.
    pos = x0 + frame

    # Generate sub(s).
    sub[:count].times do |i|
      name = "#{id}:#{i}"
      fr   = 0
      fr   = sub[:frame].frameWidth if sub[:frame]
      vec  = OpenStudio::Point3dVector.new
      vec << OpenStudio::Point3d.new(pos,               sub[:head], 0)
      vec << OpenStudio::Point3d.new(pos,               sub[:sill], 0)
      vec << OpenStudio::Point3d.new(pos + sub[:width], sub[:sill], 0)
      vec << OpenStudio::Point3d.new(pos + sub[:width], sub[:head], 0)
      vec = s00 ? t * (s00[:r] * (s00[:t] * vec)) : t * vec

      # Log/skip if conflict between individual sub and base surface.
      vc = vec
      vc = offset(vc, fr, 300) if fr > 0

      unless fits?(vc, s)
        log(ERR, "Skip '#{name}': won't fit in '#{nom}' (#{mth})")
        break
      end

      # Log/skip if conflicts with existing subs (even if same array).
      conflict = false

      s.subSurfaces.each do |sb|
        nome = sb.nameString
        fd   = sb.windowPropertyFrameAndDivider
        fr   = fd.empty? ? 0 : fd.get.frameWidth
        vk   = sb.vertices
        vk   = offset(vk, fr, 300) if fr > 0

        if overlaps?(vc, vk)
          log(ERR, "Skip '#{name}': overlaps '#{nome}' (#{mth})")
          conflict = true
          break
        end
      end

      break if conflict

      sb = OpenStudio::Model::SubSurface.new(vec, mdl)
      sb.setName(name)
      sb.setSubSurfaceType(sub[:type])
      sb.setConstruction(sub[:assembly]) if sub[:assembly]
      sb.setMultiplier(sub[:multiplier]) if sub[:multiplier] > 1

      if sub[:frame] && sb.allowWindowPropertyFrameAndDivider
        sb.setWindowPropertyFrameAndDivider(sub[:frame])
      end

      sb.setSurface(s)

      # Reset "pos" if array.
      pos += sub[:offset] if sub.key?(:offset)
    end
  end

  true
end

#airLoopsHVAC?(model = nil) ⇒ Bool, false

Validates if model has zones with HVAC air loops.

Parameters:

  • model (OpenStudio::Model::Model) (defaults to: nil)

    a model

Returns:

  • (Bool)

    whether model has HVAC air loops

  • (false)

    if invalid input (see logs)



1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
# File 'lib/osut/utils.rb', line 1291

def airLoopsHVAC?(model = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Model
  return mismatch("model", model, cl, mth, DBG, false) unless model.is_a?(cl)

  model.getThermalZones.each do |zone|
    next            if zone.canBePlenum
    return true unless zone.airLoopHVACs.empty?
    return true     if zone.isPlenum
  end

  false
end

#alignedHeight(pts = nil, force = false) ⇒ Float, 0.0

Returns ‘height’ of a set of OpenStudio 3D points, once re/aligned.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points, once re/aligned

  • force (Bool) (defaults to: false)

    whether to force rotation of (narrow) bounded box

Returns:

  • (Float)

    height along Y-axis, once re/aligned

  • (0.0)

    if invalid inputs



4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
# File 'lib/osut/utils.rb', line 4470

def alignedHeight(pts = nil, force = false)
  mth = "OSut::#{__callee__}"
  pts = poly(pts, false, true, true, true)
  return 0 if pts.size < 2

  unless [true, false].include?(force)
    log(DBG, "Ignoring force input (#{mth})")
    force = false
  end

  pts = getRealignedFace(pts, force)[:set]
  return 0 if pts.size < 2

  pts.max_by(&:y).y - pts.min_by(&:y).y
end

#alignedWidth(pts = nil, force = false) ⇒ Float, 0.0

Returns ‘width’ of a set of OpenStudio 3D points, once re/aligned.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points, once re/aligned

  • force (Bool) (defaults to: false)

    whether to force rotation of (narrow) bounded box

Returns:

  • (Float)

    width al©ong X-axis, once re/aligned

  • (0.0)

    if invalid inputs



4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
# File 'lib/osut/utils.rb', line 4446

def alignedWidth(pts = nil, force = false)
  mth = "OSut::#{__callee__}"
  pts = poly(pts, false, true, true, true)
  return 0 if pts.size < 2

  unless [true, false].include?(force)
    log(DBG, "Ignoring force input (#{mth})")
    force = false
  end

  pts = getRealignedFace(pts, force)[:set]
  return 0 if pts.size < 2

  pts.max_by(&:x).x - pts.min_by(&:x).x
end

#availabilitySchedule(model = nil, avl = "") ⇒ OpenStudio::Model::Schedule?

Generates an HVAC availability schedule.

Parameters:

  • model (OpenStudio::Model::Model) (defaults to: nil)

    a model

  • avl (String) (defaults to: "")

    seasonal availability choice (optional, default “ON”)

Returns:

  • (OpenStudio::Model::Schedule)

    HVAC availability sched

  • (nil)

    if invalid input (see logs)



2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
# File 'lib/osut/utils.rb', line 2155

def availabilitySchedule(model = nil, avl = "")
  mth    = "OSut::#{__callee__}"
  cl     = OpenStudio::Model::Model
  limits = nil
  return mismatch("model",     model, cl, mth) unless model.is_a?(cl)
  return invalid("availability", avl,  2, mth) unless avl.respond_to?(:to_s)

  # Either fetch availability ScheduleTypeLimits object, or create one.
  model.getScheduleTypeLimitss.each do |l|
    break    if limits
    next     if l.lowerLimitValue.empty?
    next     if l.upperLimitValue.empty?
    next     if l.numericType.empty?
    next unless l.lowerLimitValue.get.to_i == 0
    next unless l.upperLimitValue.get.to_i == 1
    next unless l.numericType.get.downcase == "discrete"
    next unless l.unitType.downcase == "availability"
    next unless l.nameString.downcase == "hvac operation scheduletypelimits"

    limits = l
  end

  unless limits
    limits = OpenStudio::Model::ScheduleTypeLimits.new(model)
    limits.setName("HVAC Operation ScheduleTypeLimits")
    limits.setLowerLimitValue(0)
    limits.setUpperLimitValue(1)
    limits.setNumericType("Discrete")
    limits.setUnitType("Availability")
  end

  time = OpenStudio::Time.new(0,24)
  secs = time.totalSeconds
  on   = OpenStudio::Model::ScheduleDay.new(model, 1)
  off  = OpenStudio::Model::ScheduleDay.new(model, 0)

  # Seasonal availability start/end dates.
  year  = model.yearDescription
  return empty("yearDescription", mth, ERR) if year.empty?

  year  = year.get
  may01 = year.makeDate(OpenStudio::MonthOfYear.new("May"),  1)
  oct31 = year.makeDate(OpenStudio::MonthOfYear.new("Oct"), 31)

  case trim(avl).downcase
  when "winter" # available from November 1 to April 30 (6 months)
    val = 1
    sch = off
    nom = "WINTER Availability SchedRuleset"
    dft = "WINTER Availability dftDaySched"
    tag = "May-Oct WINTER Availability SchedRule"
    day = "May-Oct WINTER SchedRule Day"
  when "summer" # available from May 1 to October 31 (6 months)
    val = 0
    sch = on
    nom = "SUMMER Availability SchedRuleset"
    dft = "SUMMER Availability dftDaySched"
    tag = "May-Oct SUMMER Availability SchedRule"
    day = "May-Oct SUMMER SchedRule Day"
  when "off" # never available
    val = 0
    sch = on
    nom = "OFF Availability SchedRuleset"
    dft = "OFF Availability dftDaySched"
    tag = ""
    day = ""
  else # always available
    val = 1
    sch = on
    nom = "ON Availability SchedRuleset"
    dft = "ON Availability dftDaySched"
    tag = ""
    day = ""
  end

  # Fetch existing schedule.
  ok = true
  schedule = model.getScheduleByName(nom)

  unless schedule.empty?
    schedule = schedule.get.to_ScheduleRuleset

    unless schedule.empty?
      schedule = schedule.get
      default  = schedule.defaultDaySchedule
      ok = ok && default.nameString           == dft
      ok = ok && default.times.size           == 1
      ok = ok && default.values.size          == 1
      ok = ok && default.times.first          == time
      ok = ok && default.values.first         == val
      rules = schedule.scheduleRules
      ok = ok && rules.size < 2

      if rules.size == 1
        rule = rules.first
        ok = ok && rule.nameString            == tag
        ok = ok && !rule.startDate.empty?
        ok = ok && !rule.endDate.empty?
        ok = ok && rule.startDate.get         == may01
        ok = ok && rule.endDate.get           == oct31
        ok = ok && rule.applyAllDays

        d = rule.daySchedule
        ok = ok && d.nameString               == day
        ok = ok && d.times.size               == 1
        ok = ok && d.values.size              == 1
        ok = ok && d.times.first.totalSeconds == secs
        ok = ok && d.values.first.to_i        != val
      end

      return schedule if ok
    end
  end

  schedule = OpenStudio::Model::ScheduleRuleset.new(model)
  schedule.setName(nom)

  unless schedule.setScheduleTypeLimits(limits)
    log(ERR, "'#{nom}': Can't set schedule type limits (#{mth})")
    return nil
  end

  unless schedule.defaultDaySchedule.addValue(time, val)
    log(ERR, "'#{nom}': Can't set default day schedule (#{mth})")
    return nil
  end

  schedule.defaultDaySchedule.setName(dft)

  unless tag.empty?
    rule = OpenStudio::Model::ScheduleRule.new(schedule, sch)
    rule.setName(tag)

    unless rule.setStartDate(may01)
      log(ERR, "'#{tag}': Can't set start date (#{mth})")
      return nil
    end

    unless rule.setEndDate(oct31)
      log(ERR, "'#{tag}': Can't set end date (#{mth})")
      return nil
    end

    unless rule.setApplyAllDays(true)
      log(ERR, "'#{tag}': Can't apply to all days (#{mth})")
      return nil
    end

    rule.daySchedule.setName(day)
  end

  schedule
end

#blc(pts = nil) ⇒ OpenStudio::Point3dVector

Returns OpenStudio 3D points (min 3x) conforming to an BottomLeftCorner (BLC) convention. Points Z-axis values must be ~= 0. Points are returned counterclockwise.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

Returns:

  • (OpenStudio::Point3dVector)

    BLC points (see logs if empty)



3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
# File 'lib/osut/utils.rb', line 3121

def blc(pts = nil)
  mth = "OSut::#{__callee__}"
  v   = OpenStudio::Point3dVector.new
  pts = to_p3Dv(pts).to_a
  return invalid("points (3+)",      mth, 1, DBG, v)     if pts.size < 3
  return invalid("points (aligned)", mth, 1, DBG, v) unless xyz?(pts, :z)

  # Ensure counterclockwise sequence.
  pts  = pts.reverse if clockwise?(pts)
  minX = pts.min_by(&:x).x
  i0   = nearest(pts)
  p0   = pts[i0]

  pts_x = pts.select { |pt| pt.x.round(2) == minX.round(2) }.reverse

  return to_p3Dv(pts.rotate(i0)) if pts_x.include?(p0)

  p1 = pts_x.min_by { |pt| (pt - p0).length }
  i1 = pts.index(p1)

  to_p3Dv(pts.rotate(i1))
end

#boundedBox(pts = nil) ⇒ OpenStudio::Point3dVector

Generates a BLC bounded box within a polygon.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    OpenStudio 3D points

Returns:

  • (OpenStudio::Point3dVector)

    bounded box (see logs if empty)



4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
# File 'lib/osut/utils.rb', line 4133

def boundedBox(pts = nil)
  str = ".*(?<!utilities.geometry.join)$"
  OpenStudio::Logger.instance.standardOutLogger.setChannelRegex(str)

  mth = "OSut::#{__callee__}"
  bkp = OpenStudio::Point3dVector.new
  box = []
  pts = poly(pts, false, true, true)
  return bkp if pts.empty?

  t   = xyz?(pts, :z) ? nil : OpenStudio::Transformation.alignFace(pts)
  pts = t.inverse * pts if t
  return bkp if pts.empty?

  pts = to_p3Dv(pts.to_a.reverse) if clockwise?(pts)

  # PATH A : Return medial bounded box if polygon is a triangle.
  if pts.size == 3
    box = medialBox(pts)

    unless box.empty?
      box = to_p3Dv(t * box) if t
      return box
    end
  end

  # PATH B : Return polygon itself if already rectangular.
  if rectangular?(pts)
    box = t ? to_p3Dv(t * pts) : pts
    return box
  end

  aire = 0

  # PATH C : Right-angle, midpoint triad approach.
  getSegments(pts).each do |sg|
    m0 = midpoint(sg.first, sg.last)

    getSegments(pts).each do |seg|
      p1 = seg.first
      p2 = seg.last
      next if same?(p1, sg.first)
      next if same?(p1, sg.last)
      next if same?(p2, sg.first)
      next if same?(p2, sg.first)

      out = triadBox(OpenStudio::Point3dVector.new([m0, p1, p2]))
      next if out.empty?
      next unless fits?(out, pts)
      next if fits?(pts, out)

      area = OpenStudio.getArea(out)
      next if area.empty?

      area = area.get
      next if area < TOL
      next if area < aire

      aire = area
      box  = out
    end
  end

  # PATH D : Right-angle triad approach, may override PATH C boxes.
  getSegments(pts).each do |sg|
    p0 = sg.first
    p1 = sg.last

    pts.each do |p2|
      next if same?(p2, p0)
      next if same?(p2, p1)

      out = triadBox(OpenStudio::Point3dVector.new([p0, p1, p2]))
      next if out.empty?
      next unless fits?(out, pts)
      next if fits?(pts, out)

      area = OpenStudio.getArea(out)
      next if area.empty?

      area = area.get
      next if area < TOL
      next if area < aire

      aire = area
      box  = out
    end
  end

  unless aire < TOL
    box = to_p3Dv(t * box) if t
    return box
  end

  # PATH E : Medial box, segment approach.
  aire = 0

  getSegments(pts).each do |sg|
    p0 = sg.first
    p1 = sg.last

    pts.each do |p2|
      next if same?(p2, p0)
      next if same?(p2, p1)

      out = medialBox(OpenStudio::Point3dVector.new([p0, p1, p2]))
      next if out.empty?
      next unless fits?(out, pts)
      next if fits?(pts, out)

      area = OpenStudio.getArea(box)
      next if area.empty?

      area = area.get
      next if area < TOL
      next if area < aire

      aire = area
      box  = out
    end
  end

  unless aire < TOL
    box = to_p3Dv(t * box) if t
    return box
  end

  # PATH F : Medial box, triad approach.
  aire = 0

  getTriads(pts).each do |sg|
    p0 = sg[0]
    p1 = sg[1]
    p2 = sg[2]

    out = medialBox(OpenStudio::Point3dVector.new([p0, p1, p2]))
    next if out.empty?
    next unless fits?(out, pts)
    next if fits?(pts, out)

    area = OpenStudio.getArea(box)
    next if area.empty?

    area = area.get
    next if area < TOL
    next if area < aire

    aire = area
    box  = out
  end

  unless aire < TOL
    box = to_p3Dv(t * box) if t
    return box
  end

  # PATH G : Medial box, triangulated approach.
  aire  = 0
  outer = to_p3Dv(pts.to_a.reverse)
  holes = OpenStudio::Point3dVectorVector.new

  OpenStudio.computeTriangulation(outer, holes).each do |triangle|
    getSegments(triangle).each do |sg|
      p0 = sg.first
      p1 = sg.last

      pts.each do |p2|
        next if same?(p2, p0)
        next if same?(p2, p1)

        out = medialBox(OpenStudio::Point3dVector.new([p0, p1, p2]))
        next if out.empty?
        next unless fits?(out, pts)
        next if fits?(pts, out)

        area = OpenStudio.getArea(out)
        next if area.empty?

        area = area.get
        next if area < TOL
        next if area < aire

        aire = area
        box  = out
      end
    end
  end

  return bkp if aire < TOL

  box = to_p3Dv(t * box) if t

  box
end

#cast(p1 = nil, p2 = nil, ray = nil) ⇒ OpenStudio::Point3dVector

Casts an OpenStudio polygon onto the 3D plane of a 2nd polygon, relying on an independent 3D ray vector.

Parameters:

  • p1 (Set<OpenStudio::Point3d>) (defaults to: nil)

    1st set of 3D points

  • p2 (Set<OpenStudio::Point3d>) (defaults to: nil)

    2nd set of 3D points

  • ray (OpenStudio::Vector3d) (defaults to: nil)

    a vector

Returns:

  • (OpenStudio::Point3dVector)

    cast of p1 onto p2 (see logs if empty)



3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
# File 'lib/osut/utils.rb', line 3685

def cast(p1 = nil, p2 = nil, ray = nil)
  mth  = "OSut::#{__callee__}"
  cl   = OpenStudio::Vector3d
  face = OpenStudio::Point3dVector.new
  p1   = poly(p1)
  p2   = poly(p2)
  return face if p1.empty?
  return face if p2.empty?
  return mismatch("ray", ray, cl, mth) unless ray.is_a?(cl)

  # From OpenStudio SDK v3.7.0 onwards, one could/should rely on:
  #
  # s3.amazonaws.com/openstudio-sdk-documentation/cpp/OpenStudio-3.7.0-doc/
  # utilities/html/classopenstudio_1_1_plane.html
  # #abc4747b1b041a7f09a6887bc0e5abce1
  #
  #   e.g. p1.each { |pt| face << pl.rayIntersection(pt, ray) }
  #
  # The following +/- replicates the same solution, based on:
  #   https://stackoverflow.com/a/65832417
  p0 = p2.first
  pl = OpenStudio::Plane.new(p2)
  n  = pl.outwardNormal
  return face if n.dot(ray).abs < TOL

  p1.each do |pt|
    length = n.dot(pt - p0) / n.dot(ray.reverseVector)
    face << pt + scalar(ray, length)
  end

  face
end

#clockwise?(pts = nil) ⇒ Bool, false

Validates whether OpenStudio 3D points are listed clockwise, assuming points have been pre-‘aligned’ - not just flattened along XY (i.e. Z = 0).

Parameters:

  • pts (OpenStudio::Point3dVector) (defaults to: nil)

    pre-aligned 3D points

Returns:

  • (Bool)

    whether sequence is clockwise

  • (false)

    if invalid input (see logs)



3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
# File 'lib/osut/utils.rb', line 3072

def clockwise?(pts = nil)
  mth = "OSut::#{__callee__}"
  pts = to_p3Dv(pts)
  return invalid("3+ points"  , mth, 1, DBG, false)     if pts.size < 3
  return invalid("flat points", mth, 1, DBG, false) unless xyz?(pts, :z)

  n = OpenStudio.getOutwardNormal(pts)
  return invalid("polygon", mth, 1, DBG, false) if n.empty?

  n.get.z > 0 ? false : true
end

#coolingTemperatureSetpoints?(model = nil) ⇒ Bool, false

Validates if model has zones with valid cooling temperature setpoints.

Parameters:

  • model (OpenStudio::Model::Model) (defaults to: nil)

    a model

Returns:

  • (Bool)

    whether model holds valid cooling temperature setpoints

  • (false)

    if invalid input (see logs)



1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
# File 'lib/osut/utils.rb', line 1793

def coolingTemperatureSetpoints?(model = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Model
  return mismatch("model", model, cl, mth, DBG, false) unless model.is_a?(cl)

  model.getThermalZones.each do |zone|
    return true if minCoolScheduledSetpoint(zone)[:spt]
  end

  false
end

#daylit?(space = nil, sidelit = true, toplit = true, baselit = true) ⇒ Bool, false

Validates whether space has outdoor-facing surfaces with fenestration.

Parameters:

  • space (OpenStudio::Model::Space) (defaults to: nil)

    a space

  • sidelit (Bool) (defaults to: true)

    whether to check for sidelighting, e.g. windows

  • toplit (Bool) (defaults to: true)

    whether to check for toplighting, e.g. skylights

  • baselit (Bool) (defaults to: true)

    whether to check for baselighting, e.g. glazed floors

Returns:

  • (Bool)

    whether space is daylit

  • (false)

    if invalid input (see logs)



5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
# File 'lib/osut/utils.rb', line 5230

def daylit?(space = nil, sidelit = true, toplit = true, baselit = true)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Space
  ck1 = space.is_a?(cl)
  ck2 = [true, false].include?(sidelit)
  ck3 = [true, false].include?(toplit)
  ck4 = [true, false].include?(baselit)
  return mismatch("space", space, cl, mth,    DBG, false) unless ck1
  return invalid("sidelit"          , mth, 2, DBG, false) unless ck2
  return invalid("toplit"           , mth, 3, DBG, false) unless ck3
  return invalid("baselit"          , mth, 4, DBG, false) unless ck4

  walls  = sidelit ? facets(space, "Outdoors", "Wall")        : []
  roofs  =  toplit ? facets(space, "Outdoors", "RoofCeiling") : []
  floors = baselit ? facets(space, "Outdoors", "Floor")       : []

  (walls + roofs + floors).each do |surface|
    surface.subSurfaces.each do |sub|
      # All fenestrated subsurface types are considered, as user can set these
      # explicitly (e.g. skylight in a wall) in OpenStudio.
      return true if fenestration?(sub)
    end
  end

  false
end

#defaultConstructionSet(s = nil) ⇒ OpenStudio::Model::DefaultConstructionSet?

Returns a surface’s default construction set.

Parameters:

  • s (OpenStudio::Model::Surface) (defaults to: nil)

    a surface

Returns:

  • (OpenStudio::Model::DefaultConstructionSet)

    default set

  • (nil)

    if invalid input (see logs)



828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
# File 'lib/osut/utils.rb', line 828

def defaultConstructionSet(s = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Surface
  return invalid("surface", mth, 1) unless s.respond_to?(NS)

  id = s.nameString
  ok = s.isConstructionDefaulted
  m1 = "#{id} construction not defaulted (#{mth})"
  m2 = "#{id} construction"
  m3 = "#{id} space"
  return mismatch(id, s, cl, mth) unless s.is_a?(cl)

  log(ERR, m1)           unless ok
  return nil             unless ok
  return empty(m2, mth, ERR) if s.construction.empty?
  return empty(m3, mth, ERR) if s.space.empty?

  mdl      = s.model
  base     = s.construction.get
  space    = s.space.get
  type     = s.surfaceType
  ground   = false
  exterior = false

  if s.isGroundSurface
    ground = true
  elsif s.outsideBoundaryCondition.downcase == "outdoors"
    exterior = true
  end

  unless space.defaultConstructionSet.empty?
    set = space.defaultConstructionSet.get
    return set if holdsConstruction?(set, base, ground, exterior, type)
  end

  unless space.spaceType.empty?
    spacetype = space.spaceType.get

    unless spacetype.defaultConstructionSet.empty?
      set = spacetype.defaultConstructionSet.get
      return set if holdsConstruction?(set, base, ground, exterior, type)
    end
  end

  unless space.buildingStory.empty?
    story = space.buildingStory.get

    unless story.defaultConstructionSet.empty?
      set = story.defaultConstructionSet.get
      return set if holdsConstruction?(set, base, ground, exterior, type)
    end
  end

  building = mdl.getBuilding

  unless building.defaultConstructionSet.empty?
    set = building.defaultConstructionSet.get
    return set if holdsConstruction?(set, base, ground, exterior, type)
  end

  nil
end

#facets(spaces = [], boundary = "all", type = "all", sides = []) ⇒ Array<OpenStudio::Model::Surface>

Returns an array of OpenStudio space surfaces or subsurfaces that match criteria, e.g. exterior, north-east facing walls in hotel “lobby”. Note that ‘sides’ rely on space coordinates (not building or site coordinates). Also, ‘sides’ are exclusive (not inclusive), e.g. walls strictly north-facing or strictly east-facing would not be returned if ‘sides’ holds [:north, :east]. No outside boundary condition filters if ‘boundary’ argument == “all”. No surface type filters if ‘type’ argument == “all”.

Parameters:

  • spaces (Set<OpenStudio::Model::Space>) (defaults to: [])

    target spaces

  • boundary (#to_s) (defaults to: "all")

    OpenStudio outside boundary condition

  • type (#to_s) (defaults to: "all")

    OpenStudio surface (or subsurface) type

  • sides (Set<Symbols>) (defaults to: [])

    direction keys, e.g. :north (see OSut::SIDZ)

Returns:

  • (Array<OpenStudio::Model::Surface>)

    surfaces (may be empty, no logs)



4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
# File 'lib/osut/utils.rb', line 4984

def facets(spaces = [], boundary = "all", type = "all", sides = [])
  spaces = spaces.is_a?(OpenStudio::Model::Space) ? [spaces] : spaces
  spaces = spaces.respond_to?(:to_a) ? spaces.to_a : []
  return [] if spaces.empty?

  sides = sides.respond_to?(:to_sym) ? [sides] : sides
  sides = sides.respond_to?(:to_a) ? sides.to_a : []

  faces    = []
  boundary = trim(boundary).downcase
  type     = trim(type).downcase
  return [] if boundary.empty?
  return [] if type.empty?

  # Filter sides. If 'sides' is initially empty, return all surfaces of
  # matching type and outside boundary condition.
  unless sides.empty?
    sides = sides.select { |side| SIDZ.include?(side) }
    return [] if sides.empty?
  end

  spaces.each do |space|
    return [] unless space.respond_to?(:setSpaceType)

    space.surfaces.each do |s|
      unless boundary == "all"
        next unless s.outsideBoundaryCondition.downcase == boundary
      end

      unless type == "all"
        next unless s.surfaceType.downcase == type
      end

      if sides.empty?
        faces << s
      else
        orientations = []
        orientations << :top    if s.outwardNormal.z >  TOL
        orientations << :bottom if s.outwardNormal.z < -TOL
        orientations << :north  if s.outwardNormal.y >  TOL
        orientations << :east   if s.outwardNormal.x >  TOL
        orientations << :south  if s.outwardNormal.y < -TOL
        orientations << :west   if s.outwardNormal.x < -TOL

        faces << s if sides.all? { |o| orientations.include?(o) }
      end
    end
  end

  # SubSurfaces?
  spaces.each do |space|
    space.surfaces.each do |s|
      unless boundary == "all"
        next unless s.outsideBoundaryCondition.downcase == boundary
      end

      s.subSurfaces.each do |sub|
        unless type == "all"
          next unless sub.subSurfaceType.downcase == type
        end

        if sides.empty?
          faces << sub
        else
          orientations = []
          orientations << :top    if sub.outwardNormal.z >  TOL
          orientations << :bottom if sub.outwardNormal.z < -TOL
          orientations << :north  if sub.outwardNormal.y >  TOL
          orientations << :east   if sub.outwardNormal.x >  TOL
          orientations << :south  if sub.outwardNormal.y < -TOL
          orientations << :west   if sub.outwardNormal.x < -TOL

          faces << sub if sides.all? { |o| orientations.include?(o) }
        end
      end
    end
  end

  faces
end

#facingDown?(pts = nil) ⇒ Bool, false

Validates whether a polygon faces downwards, harmonized with OpenStudio Utilities’ “alignZPrime” function.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    OpenStudio 3D points

Returns:

  • (Bool)

    if facing downwards

  • (false)

    if invalid input (see logs)



3457
3458
3459
3460
3461
3462
3463
# File 'lib/osut/utils.rb', line 3457

def facingDown?(pts = nil)
  ray = OpenStudio::Point3d.new(0,0,-1) - OpenStudio::Point3d.new(0,0,0)
  pts = poly(pts, false, true, true)
  return false if pts.empty?

  OpenStudio.getOutwardNormal(pts).get.dot(ray) > 0.99
end

#facingUp?(pts = nil) ⇒ Bool, false

Validates whether a polygon faces upwards, harmonized with OpenStudio Utilities’ “alignZPrime” function.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    OpenStudio 3D points

Returns:

  • (Bool)

    if facing upwards

  • (false)

    if invalid input (see logs)



3441
3442
3443
3444
3445
3446
3447
# File 'lib/osut/utils.rb', line 3441

def facingUp?(pts = nil)
  ray = OpenStudio::Point3d.new(0,0,1) - OpenStudio::Point3d.new(0,0,0)
  pts = poly(pts, false, true, true)
  return false if pts.empty?

  OpenStudio.getOutwardNormal(pts).get.dot(ray) > 0.99
end

#farthest(pts = nil, p01 = nil) ⇒ Integer?

Returns OpenStudio 3D point (in a set) farthest from a point of reference, e.g. grid origin. If left unspecified, the method systematically returns the top-right corner (TRC) of any horizontal set. If more than one point fits the initial criteria, the method relies on deterministic sorting through triangulation.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

  • p01 (OpenStudio::Point3d) (defaults to: nil)

    point of reference

Returns:

  • (Integer)

    set index of farthest point from point of reference

  • (nil)

    if invalid input (see logs)



2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
# File 'lib/osut/utils.rb', line 2563

def farthest(pts = nil, p01 = nil)
  mth = "OSut::#{__callee__}"
  l   = 100
  d01 = 0
  d02 = 10000
  d03 = 10000
  idx = nil
  pts = to_p3Dv(pts)
  return idx if pts.empty?

  p03 = OpenStudio::Point3d.new( l,-l,-l)
  p02 = OpenStudio::Point3d.new( l, l, l)
  p01 = OpenStudio::Point3d.new(-l,-l,-l) unless p01
  return mismatch("point", p01, cl, mth) unless p01.is_a?(OpenStudio::Point3d)

  pts.each_with_index do |pt, i|
    next if same?(pt, p01)

    length01 = (pt - p01).length
    length02 = (pt - p02).length
    length03 = (pt - p03).length

    if length01.round(2) == d01.round(2)
      if length02.round(2) == d02.round(2)
        if length03.round(2) < d03.round(2)
          idx = i
          d03 = length03
        end
      elsif length02.round(2) < d02.round(2)
        idx = i
        d03 = length03
        d02 = length02
      end
    elsif length01.round(2) > d01.round(2)
      idx = i
      d01 = length01
      d02 = length02
      d03 = length03
    end
  end

  idx
end

#fenestration?(s = nil) ⇒ Bool, false

Validates whether a sub surface is fenestrated.

Parameters:

  • s (OpenStudio::Model::SubSurface) (defaults to: nil)

    a sub surface

Returns:

  • (Bool)

    whether subsurface can be considered ‘fenestrated’

  • (false)

    if invalid input (see logs)



1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
# File 'lib/osut/utils.rb', line 1126

def fenestration?(s = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::SubSurface
  return invalid("subsurface", mth, 1, DBG, false) unless s.respond_to?(NS)

  id = s.nameString
  return mismatch(id, s, cl, mth, false) unless s.is_a?(cl)

  # OpenStudio::Model::SubSurface.validSubSurfaceTypeValues
  # "FixedWindow"              : fenestration
  # "OperableWindow"           : fenestration
  # "Door"
  # "GlassDoor"                : fenestration
  # "OverheadDoor"
  # "Skylight"                 : fenestration
  # "TubularDaylightDome"      : fenestration
  # "TubularDaylightDiffuser"  : fenestration
  return false if s.subSurfaceType.downcase == "door"
  return false if s.subSurfaceType.downcase == "overheaddoor"

  true
end

#fits?(p1 = nil, p2 = nil, entirely = false) ⇒ Bool, false

Determines whether a 1st OpenStudio polygon fits in a 2nd polygon. Vertex sequencing of both polygons must be counterclockwise. If option ‘entirely’ is set to true, then the method returns false if point lies along any of the polygon edges, or is very near any of its vertices.

Parameters:

  • p1 (Set<OpenStudio::Point3d>) (defaults to: nil)

    1st set of 3D points

  • p2 (Set<OpenStudio::Point3d>) (defaults to: nil)

    2nd set of 3D points

  • entirely (Bool) (defaults to: false)

    whether point should be neatly within polygon limits

Returns:

  • (Bool)

    whether 1st polygon fits within the 2nd polygon

  • (false)

    if invalid input (see logs)



3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
# File 'lib/osut/utils.rb', line 3542

def fits?(p1 = nil, p2 = nil, entirely = false)
  pts = []
  p1  = poly(p1)
  p2  = poly(p2)
  return false if p1.empty?
  return false if p2.empty?

  p1.each { |p0| return false unless pointWithinPolygon?(p0, p2) }

  # Although p2 points may lie ALONG p1, none may lie entirely WITHIN p1.
  p2.each { |p0| return false if pointWithinPolygon?(p0, p1, true) }

  # p1 segment mid-points must not lie OUTSIDE of p2.
  getSegments(p1).each do |sg|
    mp = midpoint(sg.first, sg.last)
    return false unless pointWithinPolygon?(mp, p2)
  end

  entirely = false unless [true, false].include?(entirely)
  return true unless entirely

  p1.each { |p0| return false unless pointWithinPolygon?(p0, p2, entirely) }

  true
end

#flatten(pts = nil, axs = :z, val = 0) ⇒ OpenStudio::Point3dVector

Flattens OpenStudio 3D points vs X, Y or Z axes.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

  • axs (Symbol) (defaults to: :z)

    :x, :y or :z axis

  • val (#to_f) (defaults to: 0)

    axis value

Returns:

  • (OpenStudio::Point3dVector)

    flattened points (see logs if empty)



2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
# File 'lib/osut/utils.rb', line 2615

def flatten(pts = nil, axs = :z, val = 0)
  mth = "OSut::#{__callee__}"
  pts = to_p3Dv(pts)
  v   = OpenStudio::Point3dVector.new
  ok1 = val.respond_to?(:to_f)
  ok2 = [:x, :y, :z].include?(axs)
  return mismatch("val", val, Numeric, mth,    DBG, v) unless ok1
  return invalid("axis (XYZ?)",        mth, 2, DBG, v) unless ok2

  val = val.to_f

  case axs
  when :x
    pts.each { |pt| v << OpenStudio::Point3d.new(val, pt.y, pt.z) }
  when :y
    pts.each { |pt| v << OpenStudio::Point3d.new(pt.x, val, pt.z) }
  else
    pts.each { |pt| v << OpenStudio::Point3d.new(pt.x, pt.y, val) }
  end

  v
end

#genAnchors(s = nil, set = [], tag = :box) ⇒ Integer

Identifies ‘leader line anchors’, i.e. specific 3D points of a (larger) set (e.g. delineating a larger, parent polygon), each anchor linking the BLC corner of one or more (smaller) subsets (free-floating within the parent)

  • see follow-up ‘genInserts’. Subsets may hold several ‘tagged’ vertices

(e.g. :box, :cbox). By default, the solution seeks to anchor subset :box vertices. Users can select other tags, e.g. tag == :cbox. The solution minimally validates individual subsets (e.g. no self-intersecting polygons, coplanarity, no inter-subset conflicts, must fit within larger set). Potential leader lines cannot intersect each other, similarly tagged subsets or (parent) polygon edges. For highly-articulated cases (e.g. a narrow parent polygon with multiple concavities, holding multiple subsets), such leader line conflicts are likely unavoidable. It is recommended to first sort subsets (e.g. areas), given the solution’s ‘first-come-first-served’ policy. Subsets without valid leader lines are ultimately ignored (check for new set :void keys, see error logs). The larger set of points is expected to be in space coordinates - not building or site coordinates, while subset points are expected to ‘fit?’ in the larger set.

Parameters:

  • s (Set<OpenStudio::Point3d>) (defaults to: nil)

    a (larger) parent set of points

  • set (Array<Hash>) (defaults to: [])

    a collection of (smaller) sequenced points

  • [Symbol] (Hash)

    a customizable set of options

Returns:

  • (Integer)

    number of successfully anchored subsets (see logs)



4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
# File 'lib/osut/utils.rb', line 4510

def genAnchors(s = nil, set = [], tag = :box)
  mth = "OSut::#{__callee__}"
  n   = 0
  id  = s.respond_to?(:nameString) ? "#{s.nameString}: " : ""
  pts = poly(s)
  return invalid("#{id} polygon", mth, 1, DBG, n) if pts.empty?
  return mismatch("set", set, Array, mth, DBG, n) unless set.respond_to?(:to_a)

  origin = OpenStudio::Point3d.new(0,0,0)
  zenith = OpenStudio::Point3d.new(0,0,1)
  ray    = zenith - origin
  set    = set.to_a

  # Validate individual subsets. Purge surface-specific leader line anchors.
  set.each_with_index do |st, i|
    str1 = id + "subset ##{i+1}"
    str2 = str1 + " #{tag.to_s}"
    return mismatch(str1, st, Hash,  mth, DBG, n) unless st.respond_to?(:key?)
    return hashkey( str1, st,  tag,  mth, DBG, n) unless st.key?(tag)
    return empty("#{str2} vertices", mth, DBG, n) if st[tag].empty?

    if st.key?(:out)
      return hashkey( str1, st,   :t,  mth, DBG, n) unless st.key?(:t)
      return hashkey( str1, st,  :ti,  mth, DBG, n) unless st.key?(:ti)
      return hashkey( str1, st,  :t0,  mth, DBG, n) unless st.key?(:t0)
    end

    stt = poly(st[tag])
    return invalid("#{str2} polygon", mth, 0, DBG, n) if stt.empty?
    return invalid("#{str2} gap", mth, 0, DBG, n) unless fits?(stt, pts, true)

    if st.key?(:ld)
      ld = st[:ld]
      return invalid("#{str1} leaders", mth, 0, DBG, n) unless ld.is_a?(Hash)

      ld.reject! { |k, _| k == s }
    else
      st[:ld] = {}
    end
  end

  set.each_with_index do |st, i|
    # When a subset already holds a leader line anchor (from an initial call
    # to 'genAnchors'), it inherits key :out - a Hash holding (among others) a
    # 'realigned' set of points (by default a 'realigned' :box). The latter is
    # typically generated from an outdoor-facing roof (e.g. when called from
    # 'lights'). Subsequent calls to 'genAnchors' may send (as first
    # argument) a corresponding ceiling tile below (also from 'addSkylights').
    # Roof vs ceiling may neither share alignment transformation nor space
    # site transformation identities. All subsequent calls to 'genAnchors'
    # shall recover the :out points, apply a succession of de/alignments and
    # transformations in sync , and overwrite tagged points.
    #
    # Although 'genAnchors' and 'genInserts' have both been developed to
    # support anchor insertions in other cases (e.g. bay window in a wall),
    # variables and terminology here continue pertain to roofs, ceilings,
    # skylights and wells - less abstract, simpler to follow.
    if st.key?(:out)
      ti   = st[:ti ] # unoccupied attic/plenum space site transformation
      t0   = st[:t0 ] # occupied space site transformation
      t    = st[:t  ] # initial alignment transformation of roof surface
      o    = st[:out]
      tpts = t0.inverse * (ti * (t * (o[:r] * (o[:t] * o[:set]))))
      tpts = cast(tpts, pts, ray)

      st[tag] = tpts
    else
      st[:t] = OpenStudio::Transformation.alignFace(pts) unless st.key?(:t)
      tpts   = st[:t].inverse * st[tag]
      o      = getRealignedFace(tpts, true)
      tpts   = st[:t] * (o[:r] * (o[:t] * o[:set]))

      st[:out] = o
      st[tag ] = tpts
    end
  end

  # Identify candidate leader line anchors for each subset.
  set.each_with_index do |st, i|
    candidates = []
    tpts = st[tag]

    pts.each do |pt|
      ld = [pt, tpts.first]
      nb = 0

      # Check for intersections between leader line and larger polygon edges.
      getSegments(pts).each do |sg|
        break unless nb.zero?
        next if holds?(sg, pt)

        nb += 1 if lineIntersects?(sg, ld)
      end

      # Check for intersections between candidate leader line vs other subsets.
      set.each do |other|
        break unless nb.zero?
        next if st == other

        ost = other[tag]

        getSegments(ost).each { |sg| nb += 1 if lineIntersects?(ld, sg) }
      end

      # ... and previous leader lines (first come, first serve basis).
      set.each do |other|
        break unless nb.zero?
        next if st == other
        next unless other.key?(:ld)
        next unless other[:ld].key?(s)

        ost = other[tag]
        pld = other[:ld][s]
        next if same?(pld, pt)

        nb += 1 if lineIntersects?(ld, [pld, ost.first])
      end

      # Finally, check for self-intersections.
      getSegments(tpts).each do |sg|
        break unless nb.zero?
        next if holds?(sg, tpts.first)

        nb += 1 if lineIntersects?(sg, ld)
        nb += 1 if (sg.first - sg.last).cross(ld.first - ld.last).length < TOL
      end

      candidates << pt if nb.zero?
    end

    if candidates.empty?
      str = id + "set ##{i+1}"
      log(WRN, "#{str}: unable to anchor #{tag} leader line (#{mth})")
      st[:void] = true
    else
      p0 = candidates.sort_by { |pt| (pt - tpts.first).length }.first
      n += 1

      st[:ld][s] = p0
    end
  end

  n
end

#genConstruction(model = nil, specs = {}) ⇒ OpenStudio::Model::Construction?

Generates an OpenStudio multilayered construction, + materials if needed.

Parameters:

  • model (OpenStudio::Model::Model) (defaults to: nil)

    a model

  • specs (Hash) (defaults to: {})

    OpenStudio construction specifications

Options Hash (specs):

  • :id (#to_s) — default: ""

    construction identifier

  • :type (Symbol) — default: :wall

    , see @@uo

  • :uo (Numeric)

    assembly clear-field Uo, in W/m2•K, see @@uo

  • :clad (Symbol) — default: :light

    exterior cladding, see @@mass

  • :frame (Symbol) — default: :light

    assembly framing, see @@mass

  • :finish (Symbol) — default: :light

    interior finishing, see @@mass

Returns:

  • (OpenStudio::Model::Construction)

    generated construction

  • (nil)

    if invalid inputs (see logs)



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'lib/osut/utils.rb', line 208

def genConstruction(model = nil, specs = {})
  mth = "OSut::#{__callee__}"
  cl1 = OpenStudio::Model::Model
  cl2 = Hash
  return mismatch("model", model, cl1, mth) unless model.is_a?(cl1)
  return mismatch("specs", specs, cl2, mth) unless specs.is_a?(cl2)

  specs[:id] = "" unless specs.key?(:id)
  id = trim(specs[:id])
  id = "OSut|CON|#{specs[:type]}" if id.empty?

  specs[:type] = :wall unless specs.key?(:type)
  chk = @@uo.keys.include?(specs[:type])
  return invalid("surface type", mth, 2, ERR) unless chk

  specs[:uo] = @@uo[ specs[:type] ] unless specs.key?(:uo)
  u = specs[:uo]

  if u
    return mismatch("#{id} Uo", u, Numeric, mth)  unless u.is_a?(Numeric)
    return invalid("#{id} Uo (> 5.678)", mth, 2, ERR) if u > 5.678
    return negative("#{id} Uo"         , mth,    ERR) if u < 0
  end

  # Optional specs. Log/reset if invalid.
  specs[:clad  ] = :light             unless specs.key?(:clad  ) # exterior
  specs[:frame ] = :light             unless specs.key?(:frame )
  specs[:finish] = :light             unless specs.key?(:finish) # interior
  log(WRN, "Reset to light cladding") unless @@mass.include?(specs[:clad  ])
  log(WRN, "Reset to light framing" ) unless @@mass.include?(specs[:frame ])
  log(WRN, "Reset to light finish"  ) unless @@mass.include?(specs[:finish])
  specs[:clad  ] = :light             unless @@mass.include?(specs[:clad  ])
  specs[:frame ] = :light             unless @@mass.include?(specs[:frame ])
  specs[:finish] = :light             unless @@mass.include?(specs[:finish])

  film = @@film[ specs[:type] ]

  # Layered assembly (max 4 layers):
  #   - cladding
  #   - intermediate sheathing
  #   - composite insulating/framing
  #   - interior finish
  a = {clad: {}, sheath: {}, compo: {}, finish: {}, glazing: {}}

  case specs[:type]
  when :shading
    mt = :material
    d  = 0.015
    a[:compo][:mat] = @@mats[mt]
    a[:compo][:d  ] = d
    a[:compo][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
  when :partition
    unless specs[:clad] == :none
      d  = 0.015
      mt = :drywall
      a[:clad][:mat] = @@mats[mt]
      a[:clad][:d  ] = d
      a[:clad][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end

    d  = 0.015
    d  = 0.100      if specs[:frame] == :medium
    d  = 0.200      if specs[:frame] == :heavy
    d  = 0.100      if u
    mt = :concrete
    mt = :material  if specs[:frame] == :light
    mt = :mineral   if u
    a[:compo][:mat] = @@mats[mt]
    a[:compo][:d  ] = d
    a[:compo][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

    unless specs[:finish] == :none
      d  = 0.015
      mt = :drywall
      a[:finish][:mat] = @@mats[mt]
      a[:finish][:d  ] = d
      a[:finish][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end
  when :wall
    unless specs[:clad] == :none
      mt = :material
      mt = :brick    if specs[:clad] == :medium
      mt = :concrete if specs[:clad] == :heavy
      d  = 0.100
      d  = 0.015     if specs[:clad] == :light
      a[:clad][:mat] = @@mats[mt]
      a[:clad][:d  ] = d
      a[:clad][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end

    mt = :drywall
    mt = :mineral    if specs[:frame] == :medium
    mt = :polyiso    if specs[:frame] == :heavy
    d  = 0.100
    d  = 0.015       if specs[:frame] == :light
    a[:sheath][:mat] = @@mats[mt]
    a[:sheath][:d  ] = d
    a[:sheath][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

    mt = :mineral
    mt = :cellulose if specs[:frame] == :medium
    mt = :concrete  if specs[:frame] == :heavy
    mt = :material  unless u
    d  = 0.100
    d  = 0.200      if specs[:frame] == :heavy
    d  = 0.015      unless u

    a[:compo][:mat] = @@mats[mt]
    a[:compo][:d  ] = d
    a[:compo][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

    unless specs[:finish] == :none
      mt = :concrete
      mt = :drywall   if specs[:finish] == :light
      d  = 0.015
      d  = 0.100      if specs[:finish] == :medium
      d  = 0.200      if specs[:finish] == :heavy
      a[:finish][:mat] = @@mats[mt]
      a[:finish][:d  ] = d
      a[:finish][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end
  when :roof
    unless specs[:clad] == :none
      mt = :concrete
      mt = :material if specs[:clad] == :light
      d  = 0.015
      d  = 0.100     if specs[:clad] == :medium # e.g. terrace
      d  = 0.200     if specs[:clad] == :heavy  # e.g. parking garage
      a[:clad][:mat] = @@mats[mt]
      a[:clad][:d  ] = d
      a[:clad][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end

    mt = :mineral
    mt = :polyiso   if specs[:frame] == :medium
    mt = :cellulose if specs[:frame] == :heavy
    mt = :material  unless u
    d  = 0.100
    d  = 0.015      unless u
    a[:compo][:mat] = @@mats[mt]
    a[:compo][:d  ] = d
    a[:compo][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

    unless specs[:finish] == :none
      mt = :concrete
      mt = :drywall   if specs[:finish] == :light
      d  = 0.015
      d  = 0.100      if specs[:finish] == :medium # proxy for steel decking
      d  = 0.200      if specs[:finish] == :heavy
      a[:finish][:mat] = @@mats[mt]
      a[:finish][:d  ] = d
      a[:finish][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end
  when :floor
    unless specs[:clad] == :none
      mt = :material
      d  = 0.015
      a[:clad][:mat] = @@mats[mt]
      a[:clad][:d  ] = d
      a[:clad][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end

    mt = :mineral
    mt = :polyiso   if specs[:frame] == :medium
    mt = :cellulose if specs[:frame] == :heavy
    mt = :material  unless u
    d  = 0.100
    d  = 0.015      unless u
    a[:compo][:mat] = @@mats[mt]
    a[:compo][:d  ] = d
    a[:compo][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

    unless specs[:finish] == :none
      mt = :concrete
      mt = :material  if specs[:finish] == :light
      d  = 0.015
      d  = 0.100      if specs[:finish] == :medium
      d  = 0.200      if specs[:finish] == :heavy
      a[:finish][:mat] = @@mats[mt]
      a[:finish][:d  ] = d
      a[:finish][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end
  when :slab
    mt = :sand
    d  = 0.100
    a[:clad][:mat] = @@mats[mt]
    a[:clad][:d  ] = d
    a[:clad][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

    unless specs[:frame] == :none
      mt = :polyiso
      d  = 0.025
      a[:sheath][:mat] = @@mats[mt]
      a[:sheath][:d  ] = d
      a[:sheath][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end

    mt = :concrete
    d  = 0.100
    d  = 0.200      if specs[:frame] == :heavy
    a[:compo][:mat] = @@mats[mt]
    a[:compo][:d  ] = d
    a[:compo][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

    unless specs[:finish] == :none
      mt = :material
      d  = 0.015
      a[:finish][:mat] = @@mats[mt]
      a[:finish][:d  ] = d
      a[:finish][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    end
  when :basement
    unless specs[:clad] == :none
      mt = :concrete
      mt = :material if specs[:clad] == :light
      d  = 0.100
      d  = 0.015     if specs[:clad] == :light
      a[:clad][:mat] = @@mats[mt]
      a[:clad][:d  ] = d
      a[:clad][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

      mt = :polyiso
      d  = 0.025
      a[:sheath][:mat] = @@mats[mt]
      a[:sheath][:d  ] = d
      a[:sheath][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

      mt = :concrete
      d  = 0.200
      a[:compo][:mat] = @@mats[mt]
      a[:compo][:d  ] = d
      a[:compo][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
    else
      mt = :concrete
      d  = 0.200
      a[:sheath][:mat] = @@mats[mt]
      a[:sheath][:d  ] = d
      a[:sheath][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

      unless specs[:finish] == :none
        mt = :mineral
        d  = 0.075
        a[:compo][:mat] = @@mats[mt]
        a[:compo][:d  ] = d
        a[:compo][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"

        mt = :drywall
        d  = 0.015
        a[:finish][:mat] = @@mats[mt]
        a[:finish][:d  ] = d
        a[:finish][:id ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
      end
    end
  when :door
    mt = :door
    d  = 0.045

    a[:compo  ][:mat ] = @@mats[mt]
    a[:compo  ][:d   ] = d
    a[:compo  ][:id  ] = "OSut|#{mt}|#{format('%03d', d*1000)[-3..-1]}"
  when :window
    a[:glazing][:u   ]  = specs[:uo  ]
    a[:glazing][:shgc]  = 0.450
    a[:glazing][:shgc]  = specs[:shgc] if specs.key?(:shgc)
    a[:glazing][:id  ]  = "OSut|window"
    a[:glazing][:id  ] += "|U#{format('%.1f', a[:glazing][:u])}"
    a[:glazing][:id  ] += "|SHGC#{format('%d', a[:glazing][:shgc]*100)}"
  when :skylight
    a[:glazing][:u   ] = specs[:uo  ]
    a[:glazing][:shgc] = 0.450
    a[:glazing][:shgc] = specs[:shgc] if specs.key?(:shgc)
    a[:glazing][:id  ]  = "OSut|skylight"
    a[:glazing][:id  ] += "|U#{format('%.1f', a[:glazing][:u])}"
    a[:glazing][:id  ] += "|SHGC#{format('%d', a[:glazing][:shgc]*100)}"
  end

  # Initiate layers.
  glazed = true
  glazed = false if a[:glazing].empty?
  layers = OpenStudio::Model::OpaqueMaterialVector.new   unless glazed
  layers = OpenStudio::Model::FenestrationMaterialVector.new if glazed

  if glazed
    u    = a[:glazing][:u   ]
    shgc = a[:glazing][:shgc]
    lyr  = model.getSimpleGlazingByName(a[:glazing][:id])

    if lyr.empty?
      lyr = OpenStudio::Model::SimpleGlazing.new(model, u, shgc)
      lyr.setName(a[:glazing][:id])
    else
      lyr = lyr.get
    end

    layers << lyr
  else
    # Loop through each layer spec, and generate construction.
    a.each do |i, l|
      next if l.empty?

      lyr = model.getStandardOpaqueMaterialByName(l[:id])

      if lyr.empty?
        lyr = OpenStudio::Model::StandardOpaqueMaterial.new(model)
        lyr.setName(l[:id])
        lyr.setThickness(l[:d])
        lyr.setRoughness(         l[:mat][:rgh]) if l[:mat].key?(:rgh)
        lyr.setConductivity(      l[:mat][:k  ]) if l[:mat].key?(:k  )
        lyr.setDensity(           l[:mat][:rho]) if l[:mat].key?(:rho)
        lyr.setSpecificHeat(      l[:mat][:cp ]) if l[:mat].key?(:cp )
        lyr.setThermalAbsorptance(l[:mat][:thm]) if l[:mat].key?(:thm)
        lyr.setSolarAbsorptance(  l[:mat][:sol]) if l[:mat].key?(:sol)
        lyr.setVisibleAbsorptance(l[:mat][:vis]) if l[:mat].key?(:vis)
      else
        lyr = lyr.get
      end

      layers << lyr
    end
  end

  c  = OpenStudio::Model::Construction.new(layers)
  c.setName(id)

  # Adjust insulating layer thickness or conductivity to match requested Uo.
  unless glazed
    ro = 0
    ro = 1 / specs[:uo] - @@film[ specs[:type] ] if specs[:uo]

    if specs[:type] == :door # 1x layer, adjust conductivity
      layer = c.getLayer(0).to_StandardOpaqueMaterial
      return invalid("#{id} standard material?", mth, 0) if layer.empty?

      layer = layer.get
      k     = layer.thickness / ro
      layer.setConductivity(k)
    elsif ro > 0 # multiple layers, adjust insulating layer thickness
      lyr = insulatingLayer(c)
      return invalid("#{id} construction", mth, 0) if lyr[:index].nil?
      return invalid("#{id} construction", mth, 0) if lyr[:type ].nil?
      return invalid("#{id} construction", mth, 0) if lyr[:r    ].zero?

      index = lyr[:index]
      layer = c.getLayer(index).to_StandardOpaqueMaterial
      return invalid("#{id} material @#{index}", mth, 0) if layer.empty?

      layer = layer.get
      k     = layer.conductivity
      d     = (ro - rsi(c) + lyr[:r]) * k
      return invalid("#{id} adjusted m", mth, 0) if d < 0.03

      nom   = "OSut|"
      nom  += layer.nameString.gsub(/[^a-z]/i, "").gsub("OSut", "")
      nom  += "|"
      nom  += format("%03d", d*1000)[-3..-1]
      layer.setName(nom) if model.getStandardOpaqueMaterialByName(nom).empty?
      layer.setThickness(d)
    end
  end

  c
end

#genExtendedVertices(s = nil, set = [], tag = :vtx) ⇒ OpenStudio::Point3dVector

Extends (larger) polygon vertices to circumscribe one or more (smaller) subsets of vertices, based on previously-generated ‘leader line’ anchors. The solution minimally validates individual subsets (e.g. no self-intersecting polygons, coplanarity, no inter-subset conflicts, must fit within larger set). Valid leader line anchors (set key :ld) need to be generated prior to calling the method - see ‘genAnchors’. Subsets may hold several ‘tag’ged vertices (e.g. :box, :vtx). By default, the solution seeks to anchor subset :vtx vertices. Users can select other tags, e.g. tag == :box).

Parameters:

  • s (Set<OpenStudio::Point3d>) (defaults to: nil)

    a larger (parent) set of points

  • set (Array<Hash>) (defaults to: [])

    a collection of (smaller) sequenced vertices

  • [Symbol] (Hash)

    a customizable set of options

Options Hash (set):

  • :ld (Hash)

    a polygon-specific leader line anchors

Returns:

  • (OpenStudio::Point3dVector)

    extended vertices (see logs if empty)



4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
# File 'lib/osut/utils.rb', line 4672

def genExtendedVertices(s = nil, set = [], tag = :vtx)
  mth = "OSut::#{__callee__}"
  id  = s.respond_to?(:nameString) ? "#{s.nameString}: " : ""
  f   = false
  pts = poly(s)
  cl  = OpenStudio::Point3d
  a   = OpenStudio::Point3dVector.new
  v   = []
  return a if pts.empty?
  return mismatch("set", set, Array, mth, DBG, a) unless set.respond_to?(:to_a)

  set = set.to_a

  # Validate individual sets.
  set.each_with_index do |st, i|
    str1 = id + "subset ##{i+1}"
    str2 = str1 + " #{tag.to_s}"
    next if st.key?(:void) && st[:void]
    return mismatch(str1, st,  Hash, mth, DBG, a) unless st.respond_to?(:key?)
    return hashkey( str1, st,   tag, mth, DBG, a) unless st.key?(tag)
    return empty("#{str2} vertices", mth, DBG, a) if st[tag].empty?
    return hashkey( str1, st,   :ld, mth, DBG, a) unless st.key?(:ld)

    stt = poly(st[tag])
    return invalid("#{str2} polygon", mth, 0, DBG, a) if stt.empty?

    ld = st[:ld]
    return mismatch(str, ld,  Hash, mth, DBG, a) unless ld.is_a?(Hash)
    return hashkey( str, ld,     s, mth, DBG, a) unless ld.key?(s)
    return mismatch(str, ld[s], cl, mth, DBG, a) unless ld[s].is_a?(cl)
  end

  # Re-sequence polygon vertices.
  pts.each do |pt|
    v << pt

    # Loop through each valid set; concatenate circumscribing vertices.
    set.each do |st|
      next if st.key?(:void) && st[:void]
      next unless same?(st[:ld][s], pt)
      next unless st.key?(tag)

      v += st[tag].to_a
      v << pt
    end
  end

  to_p3Dv(v)
end

#genInserts(s = nil, set = []) ⇒ OpenStudio::Point3dVector

Generates (1D or 2D) arrays of (smaller) rectangular collection of points, (e.g. arrays of polygon inserts) from subset parameters, within a (larger) set (e.g. parent polygon). If successful, each subset inherits additional key:value pairs: namely :vtx (collection of circumscribing vertices), and :vts (collection of individual insert vertices). Valid leader line anchors (set key :ld) need to be generated prior to calling the solution

  • see ‘genAnchors’.

Parameters:

  • s (Set<OpenStudio::Point3d>) (defaults to: nil)

    a larger (parent) set of points

  • set (Array<Hash>) (defaults to: [])

    a collection of (smaller) sequenced vertices

Options Hash (set):

  • :box (Set<OpenStudio::Point3d>)

    bounding box of each subset

  • :ld (Hash)

    a collection of leader line anchors

  • :rows (Integer) — default: 1

    number of rows of inserts

  • :cols (Integer) — default: 1

    number of columns of inserts

  • :w0 (Numeric)

    width of individual inserts (wrt cols) min 0.4

  • :d0 (Numeric)

    depth of individual inserts (wrt rows) min 0.4

  • :dX (Numeric) — default: 0

    optional left/right X-axis buffer

  • :dY (Numeric) — default: 0

    optional top/bottom Y-axis buffer

Returns:

  • (OpenStudio::Point3dVector)

    new polygon vertices (see logs if empty)



4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
# File 'lib/osut/utils.rb', line 4743

def genInserts(s = nil, set = [])
  mth = "OSut::#{__callee__}"
  id  = s.respond_to?(:nameString) ? "#{s.nameString}:" : ""
  pts = poly(s)
  cl  = OpenStudio::Point3d
  a   = OpenStudio::Point3dVector.new
  return a if pts.empty?
  return mismatch("set", set, Array, mth, DBG, a) unless set.respond_to?(:to_a)

  set  = set.to_a
  gap  = 0.1
  gap4 = 0.4 # minimum insert width/depth

  # Validate/reset individual set collections.
  set.each_with_index do |st, i|
    str1 = id + "subset ##{i+1}"
    next if st.key?(:void) && st[:void]
    return mismatch(str1, st, Hash, mth, DBG, a) unless st.respond_to?(:key?)
    return hashkey( str1, st, :box, mth, DBG, a) unless st.key?(:box)
    return hashkey( str1, st,  :ld, mth, DBG, a) unless st.key?(:ld)
    return hashkey( str1, st, :out, mth, DBG, a) unless st.key?(:out)

    str2 = str1 + " anchor"
    ld = st[:ld]
    return mismatch(str2, ld,  Hash, mth, DBG, a) unless ld.respond_to?(:key?)
    return hashkey( str2, ld,     s, mth, DBG, a) unless ld.key?(s)
    return mismatch(str2, ld[s], cl, mth, DBG, a) unless ld[s].is_a?(cl)

    # Ensure each set bounding box is safely within larger polygon boundaries.
    # @todo: In line with related addSkylights' @todo, expand solution to
    #        safely handle 'side' cutouts (i.e. no need for leader lines). In
    #        so doing, boxes could eventually align along surface edges.
    str3 = str1 + " box"
    bx = poly(st[:box])
    return invalid(str3, mth, 0, DBG, a) if bx.empty?
    return invalid("#{str3} rectangle", mth, 0, DBG, a) unless rectangular?(bx)
    return invalid("#{str3} box", mth, 0, DBG, a) unless fits?(bx, pts, true)

    if st.key?(:rows)
      rws = st[:rows]
      return invalid("#{id} rows", mth, 0, DBG, a) unless rws.is_a?(Integer)
      return zero(   "#{id} rows", mth,    DBG, a)     if rws < 1
    else
      st[:rows] = 1
    end

    if st.key?(:cols)
      cls = st[:cols]
      return invalid("#{id} cols", mth, 0, DBG, a) unless cls.is_a?(Integer)
      return zero(   "#{id} cols", mth,    DBG, a)     if cls < 1
    else
      st[:cols] = 1
    end

    if st.key?(:w0)
      w0 = st[:w0]
      return invalid("#{id} width", mth, 0, DBG, a) unless w0.is_a?(Numeric)

      w0 = w0.to_f
      return zero("#{id} width", mth, DBG, a) if w0.round(2) < gap4
    else
      st[:w0] = 1.4
    end

    if st.key?(:d0)
      d0 = st[:d0]
      return invalid("#{id} depth", mth, 0, DBG, a) unless d0.is_a?(Numeric)

      d0 = d0.to_f
      return zero("#{id} depth", mth, DBG, a) if d0.round(2) < gap4
    else
      st[:d0] = 1.4
    end

    if st.key?(:dX)
      dX = st[:dX]
      return invalid( "#{id} dX", mth, 0, DBG, a) unless dX.is_a?(Numeric)
    else
      st[:dX] = nil
    end

    if st.key?(:dY)
      dY = st[:dY]
      return invalid( "#{id} dY", mth, 0, DBG, a) unless dY.is_a?(Numeric)
    else
      st[:dY] = nil
    end
  end

  # Flag conflicts between set bounding boxes. @todo: ease up for ridges.
  set.each_with_index do |st, i|
    bx = st[:box]
    next if st.key?(:void) && st[:void]

    set.each_with_index do |other, j|
      next if i == j

      bx2  = other[:box]
      str4 = id + "set boxes ##{i+1}:##{j+1}"
      next unless overlaps?(bx, bx2)
      return invalid("#{str4} (overlapping)", mth, 0, DBG, a)
    end
  end

  t    = OpenStudio::Transformation.alignFace(pts)
  rpts = t.inverse * pts

  # Loop through each 'valid' subset (i.e. linking a valid leader line anchor),
  # generate subset vertex array based on user-provided specs.
  set.each_with_index do |st, i|
    str = id + "subset ##{i+1}"
    next if st.key?(:void) && st[:void]

    o    = st[:out]
    vts  = {} # collection of individual (named) polygon insert vertices
    vtx  = [] # sequence of circumscribing polygon vertices
    bx   = o[:set]
    w    = width(bx)  # overall sandbox width
    d    = height(bx) # overall sandbox depth
    dX   = st[:dX  ]  # left/right buffer (array vs bx)
    dY   = st[:dY  ]  # top/bottom buffer (array vs bx)
    cols = st[:cols]  # number of array columns
    rows = st[:rows]  # number of array rows
    x    = st[:w0  ]  # width of individual insert
    y    = st[:d0  ]  # depth of individual insert
    gX   = 0          # gap between insert columns
    gY   = 0          # gap between insert rows

    # Gap between insert columns.
    if cols > 1
      dX = ( (w - cols * x) / cols) / 2 unless dX
      gX = (w - 2 * dX - cols * x) / (cols - 1)
      gX = gap if gX.round(2) < gap
      dX = (w - cols * x - (cols - 1) * gX) / 2
    else
      dX = (w - x) / 2
    end

    if dX.round(2) < 0
      log(ERR, "Skipping #{str}: Negative dX {#{mth}}")
      next
    end

    # Gap between insert rows.
    if rows > 1
      dY = ( (d - rows * y) / rows) / 2 unless dY
      gY = (d - 2 * dY - rows * y) / (rows - 1)
      gY = gap if gY.round(2) < gap
      dY = (d - rows * y - (rows - 1) * gY) / 2
    else
      dY = (d - y) / 2
    end

    if dY.round(2) < 0
      log(ERR, "Skipping #{str}: Negative dY {#{mth}}")
      next
    end

    st[:dX] = dX
    st[:gX] = gX
    st[:dY] = dY
    st[:gY] = gY

    x0 = bx.min_by(&:x).x + dX # X-axis starting point
    y0 = bx.min_by(&:y).y + dY # X-axis starting point
    xC = x0                    # current X-axis position
    yC = y0                    # current Y-axis position

    # BLC of array.
    vtx << OpenStudio::Point3d.new(xC, yC, 0)

    # Move up incrementally along left side of sandbox.
    rows.times.each do |iY|
      unless iY.zero?
        yC += gY
        vtx << OpenStudio::Point3d.new(xC, yC, 0)
      end

      yC += y
      vtx << OpenStudio::Point3d.new(xC, yC, 0)
    end

    # Loop through each row: left-to-right, then right-to-left.
    rows.times.each do |iY|
      (cols - 1).times.each do |iX|
        xC += x
        vtx << OpenStudio::Point3d.new(xC, yC, 0)

        xC += gX
        vtx << OpenStudio::Point3d.new(xC, yC, 0)
      end

      # Generate individual polygon inserts, left-to-right.
      cols.times.each do |iX|
        nom  = "#{i}:#{iX}:#{iY}"
        vec  = []
        vec << OpenStudio::Point3d.new(xC    , yC    , 0)
        vec << OpenStudio::Point3d.new(xC    , yC - y, 0)
        vec << OpenStudio::Point3d.new(xC + x, yC - y, 0)
        vec << OpenStudio::Point3d.new(xC + x, yC    , 0)

        # Store.
        vts[nom] = to_p3Dv(t * ulc(o[:r] * (o[:t] * vec)))

        # Add reverse vertices, circumscribing each insert.
        vec.reverse!
        vec.pop if iX == cols - 1
        vtx += vec

        xC -= gX + x unless iX == cols - 1
      end

      unless iY == rows - 1
        yC -= gY + y
        vtx << OpenStudio::Point3d.new(xC, yC, 0)
      end
    end

    st[:vts] = vts
    st[:vtx] = to_p3Dv(t * (o[:r] * (o[:t] * vtx)))
  end

  # Extended vertex sequence of the larger polygon.
  genExtendedVertices(s, set)
end

#genMass(sps = OpenStudio::Model::SpaceVector.new, ratio = 2.0) ⇒ Bool, false

Generates an internal mass definition and instances for target spaces.

Parameters:

  • sps (OpenStudio::Model::SpaceVector) (defaults to: OpenStudio::Model::SpaceVector.new)

    target spaces

  • ratio (Numeric) (defaults to: 2.0)

    internal mass surface / floor areas

Returns:

  • (Bool)

    whether successfully generated

  • (false)

    if invalid input (see logs)



675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# File 'lib/osut/utils.rb', line 675

def genMass(sps = OpenStudio::Model::SpaceVector.new, ratio = 2.0)
  # This is largely adapted from OpenStudio-Standards:
  #
  #   https://github.com/NREL/openstudio-standards/blob/
  #   d332605c2f7a35039bf658bf55cad40a7bcac317/lib/openstudio-standards/
  #   prototypes/common/objects/Prototype.Model.rb#L786
  mth = "OSut::#{__callee__}"
  cl1 = OpenStudio::Model::SpaceVector
  cl2 = Numeric
  no  = false
  return mismatch("spaces",   sps, cl1, mth, DBG, no) unless sps.is_a?(cl1)
  return mismatch( "ratio", ratio, cl2, mth, DBG, no) unless ratio.is_a?(cl2)
  return empty(   "spaces",             mth, WRN, no)     if sps.empty?
  return negative( "ratio",             mth, ERR, no)     if ratio < 0

  # A single material.
  mdl = sps.first.model
  id  = "OSut|MASS|Material"
  mat = mdl.getOpaqueMaterialByName(id)

  if mat.empty?
    mat = OpenStudio::Model::StandardOpaqueMaterial.new(mdl)
    mat.setName(id)
    mat.setRoughness("MediumRough")
    mat.setThickness(0.15)
    mat.setConductivity(1.12)
    mat.setDensity(540)
    mat.setSpecificHeat(1210)
    mat.setThermalAbsorptance(0.9)
    mat.setSolarAbsorptance(0.7)
    mat.setVisibleAbsorptance(0.17)
  else
    mat = mat.get
  end

  # A single, 1x layered construction.
  id  = "OSut|MASS|Construction"
  con = mdl.getConstructionByName(id)

  if con.empty?
    con = OpenStudio::Model::Construction.new(mdl)
    con.setName(id)
    layers = OpenStudio::Model::MaterialVector.new
    layers << mat
    con.setLayers(layers)
  else
    con = con.get
  end

  id = "OSut|InternalMassDefinition|" + (format "%.2f", ratio)
  df = mdl.getInternalMassDefinitionByName(id)

  if df.empty?
    df = OpenStudio::Model::InternalMassDefinition.new(mdl)
    df.setName(id)
    df.setConstruction(con)
    df.setSurfaceAreaperSpaceFloorArea(ratio)
  else
    df = df.get
  end

  sps.each do |sp|
    mass = OpenStudio::Model::InternalMass.new(df)
    mass.setName("OSut|InternalMass|#{sp.nameString}")
    mass.setSpace(sp)
  end

  true
end

#genShade(subs = OpenStudio::Model::SubSurfaceVector.new) ⇒ Bool, false

Generates a solar shade (e.g. roller, textile) for glazed OpenStudio SubSurfaces (v351+), controlled to minimize overheating in cooling months (May to October in Northern Hemisphere), when outdoor dry bulb temperature is above 18°C and impinging solar radiation is above 100 W/m2.

Parameters:

  • subs (OpenStudio::Model::SubSurfaceVector) (defaults to: OpenStudio::Model::SubSurfaceVector.new)

    sub surfaces

Returns:

  • (Bool)

    whether successfully generated

  • (false)

    if invalid input (see logs)



581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
# File 'lib/osut/utils.rb', line 581

def genShade(subs = OpenStudio::Model::SubSurfaceVector.new)
  # Filter OpenStudio warnings for ShadingControl:
  #   ref: https://github.com/NREL/OpenStudio/issues/4911
  str = ".*(?<!ShadingControl)$"
  OpenStudio::Logger.instance.standardOutLogger.setChannelRegex(str)

  mth = "OSut::#{__callee__}"
  v   = OpenStudio.openStudioVersion.split(".").join.to_i
  cl  = OpenStudio::Model::SubSurfaceVector
  return mismatch("subs ", subs,  cl2, mth, DBG, false) unless subs.is_a?(cl)
  return empty(   "subs",              mth, WRN, false)     if subs.empty?
  return false                                              if v < 321

  # Shading availability period.
  mdl   = subs.first.model
  id    = "onoff"
  onoff = mdl.getScheduleTypeLimitsByName(id)

  if onoff.empty?
    onoff = OpenStudio::Model::ScheduleTypeLimits.new(mdl)
    onoff.setName(id)
    onoff.setLowerLimitValue(0)
    onoff.setUpperLimitValue(1)
    onoff.setNumericType("Discrete")
    onoff.setUnitType("Availability")
  else
    onoff = onoff.get
  end

  # Shading schedule.
  id  = "OSut|SHADE|Ruleset"
  sch = mdl.getScheduleRulesetByName(id)

  if sch.empty?
    sch = OpenStudio::Model::ScheduleRuleset.new(mdl, 0)
    sch.setName(id)
    sch.setScheduleTypeLimits(onoff)
    sch.defaultDaySchedule.setName("OSut|Shade|Ruleset|Default")
  else
    sch = sch.get
  end

  # Summer cooling rule.
  id   = "OSut|SHADE|ScheduleRule"
  rule = mdl.getScheduleRuleByName(id)

  if rule.empty?
    may     = OpenStudio::MonthOfYear.new("May")
    october = OpenStudio::MonthOfYear.new("Oct")
    start   = OpenStudio::Date.new(may, 1)
    finish  = OpenStudio::Date.new(october, 31)

    rule = OpenStudio::Model::ScheduleRule.new(sch)
    rule.setName(id)
    rule.setStartDate(start)
    rule.setEndDate(finish)
    rule.setApplyAllDays(true)
    rule.daySchedule.setName("OSut|Shade|Rule|Default")
    rule.daySchedule.addValue(OpenStudio::Time.new(0,24,0,0), 1)
  else
    rule = rule.get
  end

  # Shade object.
  id  = "OSut|Shade"
  shd = mdl.getShadeByName(id)

  if shd.empty?
    shd = OpenStudio::Model::Shade.new(mdl)
    shd.setName(id)
  else
    shd = shd.get
  end

  # Shading control (unique to each call).
  id  = "OSut|ShadingControl"
  ctl = OpenStudio::Model::ShadingControl.new(shd)
  ctl.setName(id)
  ctl.setSchedule(sch)
  ctl.setShadingControlType("OnIfHighOutdoorAirTempAndHighSolarOnWindow")
  ctl.setSetpoint(18)   # °C
  ctl.setSetpoint2(100) # W/m2
  ctl.setMultipleSurfaceControlType("Group")
  ctl.setSubSurfaces(subs)
end

#genSlab(pltz = [], z = 0) ⇒ OpenStudio::Point3dVector

Generates an OpenStudio 3D point vector of a composite floor “slab”, a ‘union’ of multiple rectangular, horizontal floor “plates”. Each plate must either share an edge with (or encompass or overlap) any of the preceding plates in the array. The generated slab may not be convex.

Parameters:

  • pltz (Array<Hash>) (defaults to: [])

    individual floor plates, each holding:

  • z (Numeric) (defaults to: 0)

    Z-axis coordinate

Options Hash (pltz):

  • :x (Numeric)

    left corner of plate origin (bird’s eye view)

  • :y (Numeric)

    bottom corner of plate origin (bird’s eye view)

  • :dx (Numeric)

    plate width (bird’s eye view)

  • :dy (Numeric)

    plate depth (bird’s eye view)

Returns:

  • (OpenStudio::Point3dVector)

    slab vertices (see logs if empty)



5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
# File 'lib/osut/utils.rb', line 5079

def genSlab(pltz = [], z = 0)
  mth = "OSut::#{__callee__}"
  slb = OpenStudio::Point3dVector.new
  bkp = OpenStudio::Point3dVector.new
  cl1 = Array
  cl2 = Hash
  cl3 = Numeric

  # Input validation.
  return mismatch("plates", pltz, cl1, mth, DBG, slb) unless pltz.is_a?(cl1)
  return mismatch(     "Z",    z, cl3, mth, DBG, slb) unless z.is_a?(cl3)

  pltz.each_with_index do |plt, i|
    id = "plate # #{i+1} (index #{i})"

    return mismatch(id, plt, cl1, mth, DBG, slb) unless plt.is_a?(cl2)
    return hashkey( id, plt,  :x, mth, DBG, slb) unless plt.key?(:x )
    return hashkey( id, plt,  :y, mth, DBG, slb) unless plt.key?(:y )
    return hashkey( id, plt, :dx, mth, DBG, slb) unless plt.key?(:dx)
    return hashkey( id, plt, :dy, mth, DBG, slb) unless plt.key?(:dy)

    x  = plt[:x ]
    y  = plt[:y ]
    dx = plt[:dx]
    dy = plt[:dy]

    return mismatch("#{id} X",   x, cl3, mth, DBG, slb) unless  x.is_a?(cl3)
    return mismatch("#{id} Y",   y, cl3, mth, DBG, slb) unless  y.is_a?(cl3)
    return mismatch("#{id} dX", dx, cl3, mth, DBG, slb) unless dx.is_a?(cl3)
    return mismatch("#{id} dY", dy, cl3, mth, DBG, slb) unless dy.is_a?(cl3)
    return zero(    "#{id} dX",          mth, ERR, slb)     if dx.abs < TOL
    return zero(    "#{id} dY",          mth, ERR, slb)     if dy.abs < TOL
  end

  # Join plates.
  pltz.each_with_index do |plt, i|
    id = "plate # #{i+1} (index #{i})"
    x  = plt[:x ]
    y  = plt[:y ]
    dx = plt[:dx]
    dy = plt[:dy]

    # Adjust X if dX < 0.
    x -= -dx if dx < 0
    dx = -dx if dx < 0

    # Adjust Y if dY < 0.
    y -= -dy if dy < 0
    dy = -dy if dy < 0

    vtx  = []
    vtx << OpenStudio::Point3d.new(x + dx, y + dy, 0)
    vtx << OpenStudio::Point3d.new(x + dx, y,      0)
    vtx << OpenStudio::Point3d.new(x,      y,      0)
    vtx << OpenStudio::Point3d.new(x,      y + dy, 0)

    if slb.empty?
      slb = vtx
    else
      slab = OpenStudio.join(slb, vtx, TOL2)
      slb  = slab.get                  unless slab.empty?
      return invalid(id, mth, 0, ERR, bkp) if slab.empty?
    end
  end

  # Once joined, re-adjust Z-axis coordinates.
  unless z.zero?
    vtx = OpenStudio::Point3dVector.new
    slb.each { |pt| vtx << OpenStudio::Point3d.new(pt.x, pt.y, z) }
    slb = vtx
  end

  slb
end

#getCollinears(pts = nil, n = 0) ⇒ OpenStudio::Point3dVector

Returns sequential collinear points in an OpenStudio 3D point vector.

Parameters:

  • pts (Set<OpenStudio::Point3d] 3D points) (defaults to: nil)

    ts [Set<OpenStudio::Point3d] 3D points

  • n (#to_i) (defaults to: 0)

    requested number of collinears (0 returns all)

Returns:

  • (OpenStudio::Point3dVector)

    collinears (see logs if empty)



3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
# File 'lib/osut/utils.rb', line 3192

def getCollinears(pts = nil, n = 0)
  mth = "OSut::#{__callee__}"
  pts = getUniques(pts)
  ok  = n.respond_to?(:to_i)
  v   = OpenStudio::Point3dVector.new
  return pts if pts.size < 3
  return mismatch("n collinears", n, Integer, mth, DBG, v) unless ok

  ncolls = getNonCollinears(pts)
  return pts if ncolls.empty?

  to_p3Dv( pts.delete_if { |pt| holds?(ncolls, pt) } )
end

#getHorizontalRidges(roofs = []) ⇒ Array

Identifies horizontal ridges along 2x sloped (roof?) surfaces (same space). The concept of ‘sloped’ is harmonized with OpenStudio’s “alignZPrime”. If successful, the returned Array holds ‘ridge’ Hashes. Each Hash holds: an :edge (OpenStudio::Point3dVector), the edge :length (Numeric), and :roofs (Array of 2x linked surfaces). Each surface may be linked to more than one horizontal ridge.

Parameters:

  • roofs (Array<OpenStudio::Model::Surface>) (defaults to: [])

    target surfaces

Returns:

  • (Array)

    horizontal ridges (see logs if empty)



6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
# File 'lib/osut/utils.rb', line 6019

def getHorizontalRidges(roofs = [])
  mth    = "OSut::#{__callee__}"
  ridges = []
  return ridges unless roofs.is_a?(Array)

  roofs = roofs.select { |s| s.is_a?(OpenStudio::Model::Surface) }
  roofs = roofs.select { |s| sloped?(s) }

  roofs.each do |roof|
    maxZ = roof.vertices.max_by(&:z).z
    next if roof.space.empty?

    space = roof.space.get

    getSegments(roof).each do |edge|
      next unless xyz?(edge, :z, maxZ)

      # Skip if already tracked.
      match = false

      ridges.each do |ridge|
        break if match

        edg   = ridge[:edge]
        match = same?(edge, edg) || same?(edge, edg.reverse)
      end

      next if match

      ridge = { edge: edge, length: (edge[1] - edge[0]).length, roofs: [roof] }

      # Links another roof (same space)?
      match = false

      roofs.each do |ruf|
        break if match
        next  if ruf == roof
        next  if ruf.space.empty?
        next  unless ruf.space.get == space

        getSegments(ruf).each do |edg|
          break    if match
          next unless same?(edge, edg) || same?(edge, edg.reverse)

          ridge[:roofs] << ruf
          ridges << ridge
          match = true
        end
      end
    end
  end

  ridges
end

#getLineIntersection(s1 = [], s2 = []) ⇒ OpenStudio::Point3d?

Returns point of intersection of 2x 3D line segments.

Parameters:

  • s1 (Set<OpenStudio::Point3d] 1st 3D line segment) (defaults to: [])

    1 [Set<OpenStudio::Point3d] 1st 3D line segment

  • s2 (Set<OpenStudio::Point3d] 2nd 3D line segment) (defaults to: [])

    2 [Set<OpenStudio::Point3d] 2nd 3D line segment

Returns:

  • (OpenStudio::Point3d)

    point of intersection of both lines

  • (nil)

    if no intersection, equal, or invalid input (see logs)



2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
# File 'lib/osut/utils.rb', line 2961

def getLineIntersection(s1 = [], s2 = [])
  s1  = getSegments(s1)
  s2  = getSegments(s2)
  return nil if s1.empty?
  return nil if s2.empty?

  s1 = s1.first
  s2 = s2.first

  # Matching segments?
  return nil if same?(s1, s2)
  return nil if same?(s1, s2.to_a.reverse)

  a1 = s1[0]
  a2 = s1[1]
  b1 = s2[0]
  b2 = s2[1]

  # Matching segment endpoints?
  return a1 if same?(a1, b1)
  return a2 if same?(a2, b1)
  return a1 if same?(a1, b2)
  return a2 if same?(a2, b2)

  # Segment endpoint along opposite segment?
  return a1 if pointAlongSegments?(a1, s2)
  return a2 if pointAlongSegments?(a2, s2)
  return b1 if pointAlongSegments?(b1, s1)
  return b2 if pointAlongSegments?(b2, s1)

  # Line segments as vectors. Skip if colinear.
  a   = a2 - a1
  b   = b2 - b1
  xab = a.cross(b)
  return nil if xab.length.round(4) < TOL2

  # Link 1st point to other segment endpoints as vectors. Must be coplanar.
  a1b1  = b1 - a1
  a1b2  = b2 - a1
  xa1b1 = a.cross(a1b1)
  xa1b2 = a.cross(a1b2)
  xa1b1.normalize
  xa1b2.normalize
  xab.normalize
  return nil unless xab.cross(xa1b1).length.round(4) < TOL2
  return nil unless xab.cross(xa1b2).length.round(4) < TOL2

  # Reset.
  xa1b1 = a.cross(a1b1)
  xa1b2 = a.cross(a1b2)

  # Both segment endpoints can't be 'behind' point.
  return nil if a.dot(a1b1) < 0 && a.dot(a1b2) < 0

  # Both in 'front' of point? Pick farthest from 'a'.
  if a.dot(a1b1) > 0 && a.dot(a1b2) > 0
    lxa1b1 = xa1b1.length
    lxa1b2 = xa1b2.length

    c1 = lxa1b1.round(4) < lxa1b2.round(4) ? b1 : b2
  else
    c1 = a.dot(a1b1) > 0 ? b1 : b2
  end

  c1a1  = a1 - c1
  xc1a1 = a.cross(c1a1)
  d1    = a1 + xc1a1
  n     = a.cross(xc1a1)
  dot   = b.dot(n)
  n     = n.reverseVector if dot < 0
  f     = c1a1.dot(n) / b.dot(n)
  p0    = c1 + scalar(b, f)

  # Intersection can't be 'behind' point.
  return nil if a.dot(p0 - a1) < 0

  # Ensure intersection is sandwiched between endpoints.
  return nil unless pointAlongSegments?(p0, s2) && pointAlongSegments?(p0, s1)

  p0
end

#getNonCollinears(pts = nil, n = 0) ⇒ OpenStudio::Point3dVector

Returns sequential non-collinear points in an OpenStudio 3D point vector.

Parameters:

  • pts (Set<OpenStudio::Point3d] 3D points) (defaults to: nil)

    ts [Set<OpenStudio::Point3d] 3D points

  • n (#to_i) (defaults to: 0)

    requested number of non-collinears (0 returns all)

Returns:

  • (OpenStudio::Point3dVector)

    non-collinears (see logs if empty)



3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
# File 'lib/osut/utils.rb', line 3151

def getNonCollinears(pts = nil, n = 0)
  mth = "OSut::#{__callee__}"
  pts = getUniques(pts)
  ok  = n.respond_to?(:to_i)
  v   = OpenStudio::Point3dVector.new
  a   = []
  return pts if pts.size < 3
  return mismatch("n non-collinears", n, Integer, mth, DBG, v) unless ok

  # Evaluate cross product of vectors of 3x sequential points.
  pts.each_with_index do |p2, i2|
    i1  = i2 - 1
    i3  = i2 + 1
    i3  = 0 if i3 == pts.size
    p1  = pts[i1]
    p3  = pts[i3]
    v13 = p3 - p1
    v12 = p2 - p1
    next if v12.cross(v13).length < TOL2

    a << p2
  end

  if holds?(a, pts[0])
    a = a.rotate(-1) unless same?(a[0], pts[0])
  end

  n = n.to_i
  a = a[0..n-1]  if n > 0
  a = a[n-1..-1] if n < 0

  to_p3Dv(a)
end

#getRealignedFace(pts = nil, force = false) ⇒ Hash

Generates re-‘aligned’ polygon vertices wrt main axis of symmetry of its largest bounded box. Input polygon vertex Z-axis values must equal 0, and be counterclockwise. A Hash is returned with 6x key:value pairs … set: realigned (cloned) polygon vertices, box: its bounded box (wrt to :set), bbox: its bounding box, t: its translation transformation, r: its rotation transformation, and o: the origin coordinates of its axis of rotation. First, cloned polygon vertices are rotated so the longest axis of symmetry of its bounded box lies parallel to the X-axis; :o being the midpoint of the narrow side (of the bounded box) nearest to grid origin (0,0,0). If the axis of symmetry of the bounded box is already parallel to the X-axis, then the rotation step is skipped (unless force == true). Whether rotated or not, polygon vertices are then translated as to ensure one or more vertices are aligned along the X-axis and one or more vertices are aligned along the Y-axis (no vertices with negative X or Y coordinate values). To unalign the returned set of vertices (or its bounded box, or its bounding box), first inverse the translation transformation, then inverse the rotation transformation.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    OpenStudio 3D points

  • force (Bool) (defaults to: false)

    whether to force rotation for aligned yet narrow boxes

Returns:

  • (Hash)

    :set, :box, :bbox, :t, :r & :o

  • (Hash)

    :set, :box, :bbox, :t, :r & :o (nil) if invalid (see logs)



4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
# File 'lib/osut/utils.rb', line 4352

def getRealignedFace(pts = nil, force = false)
  mth = "OSut::#{__callee__}"
  out = { set: nil, box: nil, bbox: nil, t: nil, r: nil, o: nil }
  pts = poly(pts, false, true)
  return out if pts.empty?
  return invalid("aligned plane", mth, 1, DBG, out) unless xyz?(pts, :z)
  return invalid("clockwise pts", mth, 1, DBG, out)     if clockwise?(pts)

  # Optionally force rotation so bounded box ends up wider than taller.
  # Strongly suggested for flat surfaces like roofs (see 'sloped?').
  unless [true, false].include?(force)
    log(DBG, "Ignoring force input (#{mth})")
    force = false
  end

  o   = OpenStudio::Point3d.new(0, 0, 0)
  w   = width(pts)
  h   = height(pts)
  d   = h > w ? h : w
  sgs = {}
  box = boundedBox(pts)
  return invalid("bounded box", mth, 0, DBG, out) if box.empty?

  segments = getSegments(box)
  return invalid("bounded box segments", mth, 0, DBG, out) if segments.empty?

  # Deterministic ID of box rotation/translation 'origin'.
  segments.each_with_index do |sg, idx|
    sgs[sg]       = {}
    sgs[sg][:idx] = idx
    sgs[sg][:mid] = midpoint(sg[0], sg[1])
    sgs[sg][:l  ] = (sg[1] - sg[0]).length
    sgs[sg][:mo ] = (sgs[sg][:mid] - o).length
  end

  sgs = sgs.sort_by { |sg, s| s[:mo] }.first(2).to_h     if square?(box)
  sgs = sgs.sort_by { |sg, s| s[:l ] }.first(2).to_h unless square?(box)
  sgs = sgs.sort_by { |sg, s| s[:mo] }.first(2).to_h unless square?(box)
  sg0 = sgs.values[0]
  sg1 = sgs.values[1]

  if (sg0[:mo]).round(2) == (sg1[:mo]).round(2)
    i = sg1[:mid].y.round(2) < sg0[:mid].y.round(2) ? sg1[:idx] : sg0[:idx]
  else
    i = sg0[:idx]
  end

  k = i + 2 < segments.size ? i + 2 : i - 2

  origin   = midpoint(segments[i][0], segments[i][1])
  terminal = midpoint(segments[k][0], segments[k][1])
  seg      = terminal - origin
  right    = OpenStudio::Point3d.new(origin.x + d, origin.y    , 0) - origin
  north    = OpenStudio::Point3d.new(origin.x,     origin.y + d, 0) - origin
  axis     = OpenStudio::Point3d.new(origin.x,     origin.y    , d) - origin
  angle    = OpenStudio::getAngle(right, seg)
  angle    = -angle if north.dot(seg) < 0

  # Skip rotation if bounded box is already aligned along XY grid (albeit
  # 'narrow'), i.e. if the angle is 90°.
  if angle.round(3) == (Math::PI/2).round(3)
    angle = 0 unless force
  end

  r        = OpenStudio.createRotation(origin, axis, angle)
  pts      = to_p3Dv(r.inverse * pts)
  box      = to_p3Dv(r.inverse * box)
  dX       = pts.min_by(&:x).x
  dY       = pts.min_by(&:y).y
  xy       = OpenStudio::Point3d.new(origin.x + dX, origin.y + dY, 0)
  origin2  = xy - origin
  t        = OpenStudio.createTranslation(origin2)
  set      = to_p3Dv(t.inverse * pts)
  box      = to_p3Dv(t.inverse * box)
  bbox     = outline([set])

  out[:set ] = blc(set)
  out[:box ] = blc(box)
  out[:bbox] = blc(bbox)
  out[:t   ] = t
  out[:r   ] = r
  out[:o   ] = origin

  out
end

#getRoofs(spaces = []) ⇒ Array<OpenStudio::Model::Surface>

Returns outdoor-facing, space-related roof surfaces. These include outdoor-facing roofs of each space per se, as well as any outdoor-facing roof surface of unoccupied spaces immediately above (e.g. plenums, attics) overlapping any of the ceiling surfaces of each space. It does not include surfaces labelled as ‘RoofCeiling’, which do not comply with ASHRAE 90.1 or NECB tilt criteria - see ‘roof?’.

Parameters:

  • spaces (Set<OpenStudio::Model::Space>) (defaults to: [])

    target spaces

Returns:

  • (Array<OpenStudio::Model::Surface>)

    roofs (may be empty)



5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
# File 'lib/osut/utils.rb', line 5165

def getRoofs(spaces = [])
  mth    = "OSut::#{__callee__}"
  up     = OpenStudio::Point3d.new(0,0,1) - OpenStudio::Point3d.new(0,0,0)
  roofs  = []
  spaces = spaces.is_a?(OpenStudio::Model::Space) ? [spaces] : spaces
  spaces = spaces.respond_to?(:to_a) ? spaces.to_a : []

  spaces = spaces.select { |space| space.is_a?(OpenStudio::Model::Space) }

  # Space-specific outdoor-facing roof surfaces.
  roofs = facets(spaces, "Outdoors", "RoofCeiling")
  roofs = roofs.select { |roof| roof?(roof) }

  spaces.each do |space|
    # When unoccupied spaces are involved (e.g. plenums, attics), the target
    # space may not share the same local transformation as the space(s) above.
    # Fetching site transformation.
    t0 = transforms(space)
    next unless t0[:t]

    t0 = t0[:t]

    facets(space, "Surface", "RoofCeiling").each do |ceiling|
      cv0 = t0 * ceiling.vertices

      floor = ceiling.adjacentSurface
      next if floor.empty?

      other = floor.get.space
      next if other.empty?

      other = other.get
      next if other.partofTotalFloorArea

      ti = transforms(other)
      next unless ti[:t]

      ti = ti[:t]

      # @todo: recursive call for stacked spaces as atria (via AirBoundaries).
      facets(other, "Outdoors", "RoofCeiling").each do |ruf|
        next unless roof?(ruf)

        rvi = ti * ruf.vertices
        cst = cast(cv0, rvi, up)
        next unless overlaps?(cst, rvi, false)

        roofs << ruf unless roofs.include?(ruf)
      end
    end
  end

  roofs
end

#getSegments(pts = nil) ⇒ OpenStudio::Point3dVectorVector

Returns paired sequential points as (non-zero length) line segments. If the set strictly holds 2x unique points, a single segment is returned. Otherwise, the returned number of segments equals the number of unique points.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

Returns:

  • (OpenStudio::Point3dVectorVector)

    line segments (see logs if empty)



2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
# File 'lib/osut/utils.rb', line 2806

def getSegments(pts = nil)
  mth = "OSut::#{__callee__}"
  vv  = OpenStudio::Point3dVectorVector.new
  pts = getUniques(pts)
  return vv if pts.size < 2

  pts.each_with_index do |p1, i1|
    i2 = i1 + 1
    i2 = 0 if i2 == pts.size
    p2 = pts[i2]

    line = OpenStudio::Point3dVector.new
    line << p1
    line << p2
    vv   << line
    break if pts.size == 2
  end

  vv
end

#getTriads(pts = nil, co = false) ⇒ OpenStudio::Point3dVectorVector

Returns points as (non-zero length) ‘triads’, i.e. 3x sequential points. If the set holds less than 3x unique points, an empty triad is returned. Otherwise, the returned number of triads equals the number of unique points. If non-collinearity is requested, then the number of returned triads equals the number of non-collinear points.

Parameters:

  • pts (OpenStudio::Point3dVector) (defaults to: nil)

    3D points

Returns:

  • (OpenStudio::Point3dVectorVector)

    triads (see logs if empty)



2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
# File 'lib/osut/utils.rb', line 2853

def getTriads(pts = nil, co = false)
  mth = "OSut::#{__callee__}"
  vv  = OpenStudio::Point3dVectorVector.new
  pts = getUniques(pts)
  return vv if pts.size < 2

  pts.each_with_index do |p1, i1|
    i2 = i1 + 1
    i2 = 0 if i2 == pts.size
    i3 = i2 + 1
    i3 = 0 if i3 == pts.size
    p2 = pts[i2]
    p3 = pts[i3]

    tri = OpenStudio::Point3dVector.new
    tri << p1
    tri << p2
    tri << p3
    vv  << tri
  end

  vv
end

#getUniques(pts = nil, n = 0) ⇒ OpenStudio::Point3dVector

Returns unique OpenStudio 3D points from an OpenStudio 3D point vector.

Parameters:

  • pts (Set<OpenStudio::Point3d] 3D points) (defaults to: nil)

    ts [Set<OpenStudio::Point3d] 3D points

  • n (#to_i) (defaults to: 0)

    requested number of unique points (0 returns all)

Returns:

  • (OpenStudio::Point3dVector)

    unique points (see logs if empty)



2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
# File 'lib/osut/utils.rb', line 2779

def getUniques(pts = nil, n = 0)
  mth = "OSut::#{__callee__}"
  pts = to_p3Dv(pts)
  ok  = n.respond_to?(:to_i)
  v   = OpenStudio::Point3dVector.new
  return v if pts.empty?
  return mismatch("n unique points", n, Integer, mth, DBG, v) unless ok

  pts.each { |pt| v << pt unless holds?(v, pt) }

  n = n.to_i
  n = 0    unless n.abs < v.size
  v = v[0..n]  if n > 0
  v = v[n..-1] if n < 0

  v
end

#glazingAirFilmRSi(usi = 5.85) ⇒ Float, 0.1216

Returns total air film resistance of a fenestrated construction (m2•K/W)

Parameters:

  • usi (Numeric) (defaults to: 5.85)

    a fenestrated construction’s U-factor (W/m2•K)

Returns:

  • (Float)

    total air film resistances

  • (0.1216)

    if invalid input (see logs)



941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
# File 'lib/osut/utils.rb', line 941

def glazingAirFilmRSi(usi = 5.85)
  # The sum of thermal resistances of calculated exterior and interior film
  # coefficients under standard winter conditions are taken from:
  #
  #   https://bigladdersoftware.com/epx/docs/9-6/engineering-reference/
  #   window-calculation-module.html#simple-window-model
  #
  # These remain acceptable approximations for flat windows, yet likely
  # unsuitable for subsurfaces with curved or projecting shapes like domed
  # skylights. The solution here is considered an adequate fix for reporting,
  # awaiting eventual OpenStudio (and EnergyPlus) upgrades to report NFRC 100
  # (or ISO) air film resistances under standard winter conditions.
  #
  # For U-factors above 8.0 W/m2•K (or invalid input), the function returns
  # 0.1216 m2•K/W, which corresponds to a construction with a single glass
  # layer thickness of 2mm & k = ~0.6 W/m.K.
  #
  # The EnergyPlus Engineering calculations were designed for vertical
  # windows - not horizontal, slanted or domed surfaces - use with caution.
  mth = "OSut::#{__callee__}"
  cl  = Numeric
  return mismatch("usi", usi, cl, mth,    DBG, 0.1216)  unless usi.is_a?(cl)
  return invalid("usi",           mth, 1, WRN, 0.1216)      if usi > 8.0
  return negative("usi",          mth,    WRN, 0.1216)      if usi < 0
  return zero("usi",              mth,    WRN, 0.1216)      if usi.abs < TOL

  rsi = 1 / (0.025342 * usi + 29.163853) # exterior film, next interior film
  return rsi + 1 / (0.359073 * Math.log(usi) + 6.949915) if usi < 5.85
  return rsi + 1 / (1.788041 * usi - 2.886625)
end

#grossRoofArea(spaces = []) ⇒ Object

Returns the “gross roof area” above selected conditioned, occupied spaces. This includes all roof surfaces of indirectly-conditioned, unoccupied spaces like plenums (if located above any of the selected spaces). This also includes roof surfaces of unconditioned or unenclosed spaces like attics, if vertically-overlapping any ceiling of occupied spaces below; attic roof sections above uninsulated soffits are excluded, for instance. It does not include surfaces labelled as ‘RoofCeiling’, which do not comply with ASHRAE 90.1 or NECB tilt criteria - see ‘roof?’.



5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
# File 'lib/osut/utils.rb', line 5892

def grossRoofArea(spaces = [])
  mth = "OSut::#{__callee__}"
  up  = OpenStudio::Point3d.new(0,0,1) - OpenStudio::Point3d.new(0,0,0)
  rm2 = 0
  rfs = {}

  spaces = spaces.is_a?(OpenStudio::Model::Space) ? [spaces] : spaces
  spaces = spaces.respond_to?(:to_a) ? spaces.to_a : []
  spaces = spaces.select { |space| space.is_a?(OpenStudio::Model::Space) }
  spaces = spaces.select { |space| space.partofTotalFloorArea }
  spaces = spaces.reject { |space| unconditioned?(space) }
  return invalid("spaces", mth, 1, DBG, 0) if spaces.empty?

  # The method is very similar to OpenStudio-Standards' :
  #   find_exposed_conditioned_roof_surfaces(model)
  #
  # github.com/NREL/openstudio-standards/blob/
  # be81bd88dc55a44d8cce3ee6daf29c768032df6a/lib/openstudio-standards/
  # standards/Standards.Surface.rb#L99
  #
  # ... yet differs with regards to attics with overhangs/soffits.

  # Start with roof surfaces of occupied, conditioned spaces.
  spaces.each do |space|
    facets(space, "Outdoors", "RoofCeiling").each do |roof|
      next if rfs.key?(roof)
      next unless roof?(roof)

      rfs[roof] = {m2: roof.grossArea, m: space.multiplier}
    end
  end

  # Roof surfaces of unoccupied, conditioned spaces above (e.g. plenums)?
  # @todo: recursive call for stacked spaces as atria (via AirBoundaries).
  spaces.each do |space|
    facets(space, "Surface", "RoofCeiling").each do |ceiling|
      floor = ceiling.adjacentSurface
      next if floor.empty?

      other = floor.get.space
      next if other.empty?

      other = other.get
      next if other.partofTotalFloorArea
      next if unconditioned?(other)

      facets(other, "Outdoors", "RoofCeiling").each do |roof|
        next if rfs.key?(roof)
        next unless roof?(roof)

        rfs[roof] = {m2: roof.grossArea, m: other.multiplier}
      end
    end
  end

  # Roof surfaces of unoccupied, unconditioned spaces above (e.g. attics)?
  # @todo: recursive call for stacked spaces as atria (via AirBoundaries).
  spaces.each do |space|
    # When taking overlaps into account, the target space may not share the
    # same local transformation as the space(s) above.
    t0 = transforms(space)
    next unless t0[:t]

    t0 = t0[:t]

    facets(space, "Surface", "RoofCeiling").each do |ceiling|
      cv0 = t0 * ceiling.vertices

      floor = ceiling.adjacentSurface
      next if floor.empty?

      other = floor.get.space
      next if other.empty?

      other = other.get
      next if other.partofTotalFloorArea
      next unless unconditioned?(other)

      ti = transforms(other)
      next unless ti[:t]

      ti = ti[:t]

      facets(other, "Outdoors", "RoofCeiling").each do |roof|
        next unless roof?(roof)

        rvi  = ti * roof.vertices
        cst  = cast(cv0, rvi, up)
        next if cst.empty?

        # The overlap calculation fails for roof and ceiling surfaces with
        # previously-added leader lines.
        #
        # @todo: revise approach for attics ONCE skylight wells have been added.
        olap = nil
        olap = overlap(cst, rvi, false)
        next if olap.empty?

        m2 = OpenStudio.getArea(olap)
        next if m2.empty?

        m2 = m2.get
        next unless m2.round(2) > 0

        rfs[roof] = {m2: 0, m: other.multiplier} unless rfs.key?(roof)

        rfs[roof][:m2] += m2
      end
    end
  end

  rfs.values.each { |rf| rm2 += rf[:m2] * rf[:m] }

  rm2
end

#heatingTemperatureSetpoints?(model = nil) ⇒ Bool, false

Validates if model has zones with valid heating temperature setpoints.

Parameters:

  • model (OpenStudio::Model::Model) (defaults to: nil)

    a model

Returns:

  • (Bool)

    whether model holds valid heating temperature setpoints

  • (false)

    if invalid input (see logs)



1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
# File 'lib/osut/utils.rb', line 1615

def heatingTemperatureSetpoints?(model = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Model
  return mismatch("model", model, cl, mth, DBG, false) unless model.is_a?(cl)

  model.getThermalZones.each do |zone|
    return true if maxHeatScheduledSetpoint(zone)[:spt]
  end

  false
end

#height(pts = nil) ⇒ Float, 0.0

Returns ‘height’ of a set of OpenStudio 3D points.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

Returns:

  • (Float)

    height along Z-axis, or Y-axis if flat

  • (0.0)

    if invalid inputs



2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
# File 'lib/osut/utils.rb', line 2711

def height(pts = nil)
  pts = to_p3Dv(pts)
  return 0 if pts.size < 2

  min = pts.min_by(&:z).z
  max = pts.max_by(&:z).z
  return max - min if (max - min).abs > TOL

  pts.max_by(&:y).y - pts.min_by(&:y).y
end

#holds?(pts = nil, p1 = nil) ⇒ Bool, false

Returns true if an OpenStudio 3D point is part of a set of 3D points.

Parameters:

  • pts (Set<OpenStudio::Point3dVector>) (defaults to: nil)

    3d points

  • p1 (OpenStudio::Point3d) (defaults to: nil)

    a 3D point

Returns:

  • (Bool)

    whether part of a set of 3D points

  • (false)

    if invalid input (see logs)



2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
# File 'lib/osut/utils.rb', line 2484

def holds?(pts = nil, p1 = nil)
  mth = "OSut::#{__callee__}"
  pts = to_p3Dv(pts)
  cl  = OpenStudio::Point3d
  return mismatch("point", p1, cl, mth, DBG, false) unless p1.is_a?(cl)

  pts.each { |pt| return true if same?(p1, pt) }

  false
end

#holdsConstruction?(set = nil, bse = nil, gr = false, ex = false, tp = "") ⇒ Bool, false

Validates if a default construction set holds a base construction.

Parameters:

  • set (OpenStudio::Model::DefaultConstructionSet) (defaults to: nil)

    a default set

  • bse (OpensStudio::Model::ConstructionBase) (defaults to: nil)

    a construction base

  • gr (Bool) (defaults to: false)

    if ground-facing surface

  • ex (Bool) (defaults to: false)

    if exterior-facing surface

  • tp (#to_s) (defaults to: "")

    a surface type

Returns:

  • (Bool)

    whether default set holds construction

  • (false)

    if invalid input (see logs)



756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
# File 'lib/osut/utils.rb', line 756

def holdsConstruction?(set = nil, bse = nil, gr = false, ex = false, tp = "")
  mth = "OSut::#{__callee__}"
  cl1 = OpenStudio::Model::DefaultConstructionSet
  cl2 = OpenStudio::Model::ConstructionBase
  ck1 = set.respond_to?(NS)
  ck2 = bse.respond_to?(NS)
  return invalid("set" , mth, 1, DBG, false) unless ck1
  return invalid("base", mth, 2, DBG, false) unless ck2

  id1 = set.nameString
  id2 = bse.nameString
  ck1 = set.is_a?(cl1)
  ck2 = bse.is_a?(cl2)
  ck3 = [true, false].include?(gr)
  ck4 = [true, false].include?(ex)
  ck5 = tp.respond_to?(:to_s)
  return mismatch(id1, set, cl1, mth,    DBG, false) unless ck1
  return mismatch(id2, bse, cl2, mth,    DBG, false) unless ck2
  return invalid("ground"      , mth, 3, DBG, false) unless ck3
  return invalid("exterior"    , mth, 4, DBG, false) unless ck4
  return invalid("surface type", mth, 5, DBG, false) unless ck5

  type = trim(tp).downcase
  ck1  = ["floor", "wall", "roofceiling"].include?(type)
  return invalid("surface type", mth, 5, DBG, false) unless ck1

  constructions = nil

  if gr
    unless set.defaultGroundContactSurfaceConstructions.empty?
      constructions = set.defaultGroundContactSurfaceConstructions.get
    end
  elsif ex
    unless set.defaultExteriorSurfaceConstructions.empty?
      constructions = set.defaultExteriorSurfaceConstructions.get
    end
  else
    unless set.defaultInteriorSurfaceConstructions.empty?
      constructions = set.defaultInteriorSurfaceConstructions.get
    end
  end

  return false unless constructions

  case type
  when "roofceiling"
    unless constructions.roofCeilingConstruction.empty?
      construction = constructions.roofCeilingConstruction.get
      return true if construction == bse
    end
  when "floor"
    unless constructions.floorConstruction.empty?
      construction = constructions.floorConstruction.get
      return true if construction == bse
    end
  else
    unless constructions.wallConstruction.empty?
      construction = constructions.wallConstruction.get
      return true if construction == bse
    end
  end

  false
end

#insulatingLayer(lc = nil) ⇒ Hash

Identifies a layered construction’s (opaque) insulating layer. The method returns a 3-keyed hash :index, the insulating layer index [0, n layers) within the layered construction; :type, either :standard or :massless; and :r, material thermal resistance in m2•K/W.

Parameters:

  • lc (OpenStudio::Model::LayeredConstruction) (defaults to: nil)

    a layered construction

Returns:

  • (Hash)

    index: (Integer), type: (Symbol), r: (Float)

  • (Hash)

    index: nil, type: nil, r: 0 if invalid input (see logs)



1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
# File 'lib/osut/utils.rb', line 1043

def insulatingLayer(lc = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::LayeredConstruction
  res = { index: nil, type: nil, r: 0.0 }
  i   = 0  # iterator
  return invalid("lc", mth, 1, DBG, res) unless lc.respond_to?(NS)

  id   = lc.nameString
  return mismatch(id, lc, cl1, mth, DBG, res) unless lc.is_a?(cl)

  lc.layers.each do |m|
    unless m.to_MasslessOpaqueMaterial.empty?
      m             = m.to_MasslessOpaqueMaterial.get

      if m.thermalResistance < 0.001 || m.thermalResistance < res[:r]
        i += 1
        next
      else
        res[:r    ] = m.thermalResistance
        res[:index] = i
        res[:type ] = :massless
      end
    end

    unless m.to_StandardOpaqueMaterial.empty?
      m             = m.to_StandardOpaqueMaterial.get
      k             = m.thermalConductivity
      d             = m.thickness

      if d < 0.003 || k > 3.0 || d / k < res[:r]
        i += 1
        next
      else
        res[:r    ] = d / k
        res[:index] = i
        res[:type ] = :standard
      end
    end

    i += 1
  end

  res
end

#lineIntersects?(l = [], s = []) ⇒ Bool, false

Validates whether 3D line segment intersects 3D segments (e.g. polygon).

Parameters:

  • l (Set<OpenStudio::Point3d] 3D line segment) (defaults to: [])
    Set<OpenStudio::Point3d

    3D line segment

  • s (Set<OpenStudio::Point3d] 3D segments) (defaults to: [])
    Set<OpenStudio::Point3d

    3D segments

Returns:

  • (Bool)

    whether 3D line intersects 3D segments

  • (false)

    if invalid input (see logs)



3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
# File 'lib/osut/utils.rb', line 3051

def lineIntersects?(l = [], s = [])
  l   = getSegments(l)
  s   = getSegments(s)
  return nil if l.empty?
  return nil if s.empty?

  l = l.first

  s.each { |segment| return true if getLineIntersection(l, segment) }

  false
end

#maxHeatScheduledSetpoint(zone = nil) ⇒ Hash

Returns MAX zone heating temperature schedule setpoint [°C] and whether zone has an active dual setpoint thermostat.

Parameters:

  • zone (OpenStudio::Model::ThermalZone) (defaults to: nil)

    a thermal zone

Returns:

  • (Hash)

    spt: (Float), dual: (Bool)

  • (Hash)

    spt: nil, dual: false if invalid input (see logs)



1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
# File 'lib/osut/utils.rb', line 1441

def maxHeatScheduledSetpoint(zone = nil)
  # Largely inspired from Parker & Marrec's "thermal_zone_heated?" procedure.
  # The solution here is a tad more relaxed to encompass SEMIHEATED zones as
  # per Canadian NECB criteria (basically any space with at least 10 W/m2 of
  # installed heating equipement, i.e. below freezing in Canada).
  #
  # github.com/NREL/openstudio-standards/blob/
  # 58964222d25783e9da4ae292e375fb0d5c902aa5/lib/openstudio-standards/
  # standards/Standards.ThermalZone.rb#L910
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::ThermalZone
  res = { spt: nil, dual: false }
  return invalid("zone", mth, 1, DBG, res) unless zone.respond_to?(NS)

  id = zone.nameString
  return mismatch(id, zone, cl, mth, DBG, res) unless zone.is_a?(cl)

  # Zone radiant heating? Get schedule from radiant system.
  zone.equipment.each do |equip|
    sched = nil

    unless equip.to_ZoneHVACHighTemperatureRadiant.empty?
      equip = equip.to_ZoneHVACHighTemperatureRadiant.get

      unless equip.heatingSetpointTemperatureSchedule.empty?
        sched = equip.heatingSetpointTemperatureSchedule.get
      end
    end

    unless equip.to_ZoneHVACLowTemperatureRadiantElectric.empty?
      equip = equip.to_ZoneHVACLowTemperatureRadiantElectric.get
      sched = equip.heatingSetpointTemperatureSchedule
    end

    unless equip.to_ZoneHVACLowTempRadiantConstFlow.empty?
      equip = equip.to_ZoneHVACLowTempRadiantConstFlow.get
      coil = equip.heatingCoil

      unless coil.to_CoilHeatingLowTempRadiantConstFlow.empty?
        coil = coil.to_CoilHeatingLowTempRadiantConstFlow.get

        unless coil.heatingHighControlTemperatureSchedule.empty?
          sched = c.heatingHighControlTemperatureSchedule.get
        end
      end
    end

    unless equip.to_ZoneHVACLowTempRadiantVarFlow.empty?
      equip = equip.to_ZoneHVACLowTempRadiantVarFlow.get
      coil = equip.heatingCoil

      unless coil.to_CoilHeatingLowTempRadiantVarFlow.empty?
        coil = coil.to_CoilHeatingLowTempRadiantVarFlow.get

        unless coil.heatingControlTemperatureSchedule.empty?
          sched = coil.heatingControlTemperatureSchedule.get
        end
      end
    end

    next unless sched

    unless sched.to_ScheduleRuleset.empty?
      sched = sched.to_ScheduleRuleset.get
      max = scheduleRulesetMinMax(sched)[:max]

      if max
        res[:spt] = max unless res[:spt]
        res[:spt] = max     if res[:spt] < max
      end
    end

    unless sched.to_ScheduleConstant.empty?
      sched = sched.to_ScheduleConstant.get
      max = scheduleConstantMinMax(sched)[:max]

      if max
        res[:spt] = max unless res[:spt]
        res[:spt] = max     if res[:spt] < max
      end
    end

    unless sched.to_ScheduleCompact.empty?
      sched = sched.to_ScheduleCompact.get
      max = scheduleCompactMinMax(sched)[:max]

      if max
        res[:spt] = max unless res[:spt]
        res[:spt] = max     if res[:spt] < max
      end
    end
  end

  return res if zone.thermostat.empty?

  tstat = zone.thermostat.get
  res[:spt] = nil

  unless tstat.to_ThermostatSetpointDualSetpoint.empty? &&
         tstat.to_ZoneControlThermostatStagedDualSetpoint.empty?

    unless tstat.to_ThermostatSetpointDualSetpoint.empty?
      tstat = tstat.to_ThermostatSetpointDualSetpoint.get
    else
      tstat = tstat.to_ZoneControlThermostatStagedDualSetpoint.get
    end

    unless tstat.heatingSetpointTemperatureSchedule.empty?
      res[:dual] = true
      sched = tstat.heatingSetpointTemperatureSchedule.get

      unless sched.to_ScheduleRuleset.empty?
        sched = sched.to_ScheduleRuleset.get
        max = scheduleRulesetMinMax(sched)[:max]

        if max
          res[:spt] = max unless res[:spt]
          res[:spt] = max     if res[:spt] < max
        end

        dd = sched.winterDesignDaySchedule

        unless dd.values.empty?
          res[:spt] = dd.values.max unless res[:spt]
          res[:spt] = dd.values.max     if res[:spt] < dd.values.max
        end
      end

      unless sched.to_ScheduleConstant.empty?
        sched = sched.to_ScheduleConstant.get
        max = scheduleConstantMinMax(sched)[:max]

        if max
          res[:spt] = max unless res[:spt]
          res[:spt] = max     if res[:spt] < max
        end
      end

      unless sched.to_ScheduleCompact.empty?
        sched = sched.to_ScheduleCompact.get
        max = scheduleCompactMinMax(sched)[:max]

        if max
          res[:spt] = max unless res[:spt]
          res[:spt] = max     if res[:spt] < max
        end
      end

      unless sched.to_ScheduleYear.empty?
        sched = sched.to_ScheduleYear.get

        sched.getScheduleWeeks.each do |week|
          next if week.winterDesignDaySchedule.empty?

          dd = week.winterDesignDaySchedule.get
          next unless dd.values.empty?

          res[:spt] = dd.values.max unless res[:spt]
          res[:spt] = dd.values.max     if res[:spt] < dd.values.max
        end
      end
    end
  end

  res
end

#medialBox(pts = nil) ⇒ OpenStudio::Point3dVector

Generates a BLC box bounded within a triangle (midpoint theorem).

pts [Set<OpenStudio::Point3d>] triangular polygon

Returns:

  • (OpenStudio::Point3dVector)

    medial bounded box (see logs if empty)



4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
# File 'lib/osut/utils.rb', line 4085

def medialBox(pts = nil)
  mth = "OSut::#{__callee__}"
  bkp = OpenStudio::Point3dVector.new
  box = []
  pts = poly(pts, true, true, true)
  return bkp if pts.empty?
  return invalid("triangle", mth, 1, ERR, bkp) unless pts.size == 3

  t   = xyz?(pts, :z) ? nil : OpenStudio::Transformation.alignFace(pts)
  pts = poly(pts, false, false, false, t) if t
  return bkp if pts.empty?

  pts = to_p3Dv(pts.to_a.reverse) if clockwise?(pts)

  # Generate vertical plane along longest segment.
  mpoints = []
  sgs     = getSegments(pts)
  longest = sgs.max_by { |s| OpenStudio.getDistanceSquared(s.first, s.last) }
  plane   = verticalPlane(longest.first, longest.last)

  # Fetch midpoints of other 2 segments.
  sgs.each { |s| mpoints << midpoint(s.first, s.last) unless s == longest }

  return bkp unless mpoints.size == 2

  # Generate medial bounded box.
  box << plane.project(mpoints.first)
  box << mpoints.first
  box << mpoints.last
  box << plane.project(mpoints.last)
  box = getNonCollinears(box).to_a
  return bkp unless box.size == 4

  box = clockwise?(box) ? blc(box.reverse) : blc(box)
  return bkp unless rectangular?(box)
  return bkp unless fits?(box, pts)

  box = to_p3Dv(t * box) if t

  box
end

#midpoint(p1 = nil, p2 = nil) ⇒ OpenStudio::Point3d?

Returns midpoint coordinates of line segment.

Parameters:

  • p1 (OpenStudio::Point3d) (defaults to: nil)

    1st 3D point of a line segment

  • p2 (OpenStudio::Point3d) (defaults to: nil)

    2nd 3D point of a line segment

Returns:

  • (OpenStudio::Point3d)

    midpoint

  • (nil)

    if invalid input (see logs)



2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
# File 'lib/osut/utils.rb', line 2730

def midpoint(p1 = nil, p2 = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Point3d
  return mismatch("point 1", p1, cl, mth) unless p1.is_a?(cl)
  return mismatch("point 2", p2, cl, mth) unless p2.is_a?(cl)
  return invalid("same points", mth, 0)       if same?(p1, p2)

  midX = p1.x + (p2.x - p1.x)/2
  midY = p1.y + (p2.y - p1.y)/2
  midZ = p1.z + (p2.z - p1.z)/2

  OpenStudio::Point3d.new(midX, midY, midZ)
end

#minCoolScheduledSetpoint(zone = nil) ⇒ Hash

Returns MIN zone cooling temperature schedule setpoint [°C] and whether zone has an active dual setpoint thermostat.

Parameters:

  • zone (OpenStudio::Model::ThermalZone) (defaults to: nil)

    a thermal zone

Returns:

  • (Hash)

    spt: (Float), dual: (Bool)

  • (Hash)

    spt: nil, dual: false if invalid input (see logs)



1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
# File 'lib/osut/utils.rb', line 1635

def minCoolScheduledSetpoint(zone = nil)
  # Largely inspired from Parker & Marrec's "thermal_zone_cooled?" procedure.
  #
  # github.com/NREL/openstudio-standards/blob/
  # 99cf713750661fe7d2082739f251269c2dfd9140/lib/openstudio-standards/
  # standards/Standards.ThermalZone.rb#L1058
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::ThermalZone
  res = { spt: nil, dual: false }
  return invalid("zone", mth, 1, DBG, res) unless zone.respond_to?(NS)

  id = zone.nameString
  return mismatch(id, zone, cl, mth, DBG, res) unless zone.is_a?(cl)

  # Zone radiant cooling? Get schedule from radiant system.
  zone.equipment.each do |equip|
    sched = nil

    unless equip.to_ZoneHVACLowTempRadiantConstFlow.empty?
      equip = equip.to_ZoneHVACLowTempRadiantConstFlow.get
      coil = equip.coolingCoil

      unless coil.to_CoilCoolingLowTempRadiantConstFlow.empty?
        coil = coil.to_CoilCoolingLowTempRadiantConstFlow.get

        unless coil.coolingLowControlTemperatureSchedule.empty?
          sched = coil.coolingLowControlTemperatureSchedule.get
        end
      end
    end

    unless equip.to_ZoneHVACLowTempRadiantVarFlow.empty?
      equip = equip.to_ZoneHVACLowTempRadiantVarFlow.get
      coil = equip.coolingCoil

      unless coil.to_CoilCoolingLowTempRadiantVarFlow.empty?
        coil = coil.to_CoilCoolingLowTempRadiantVarFlow.get

        unless coil.coolingControlTemperatureSchedule.empty?
          sched = coil.coolingControlTemperatureSchedule.get
        end
      end
    end

    next unless sched

    unless sched.to_ScheduleRuleset.empty?
      sched = sched.to_ScheduleRuleset.get
      min = scheduleRulesetMinMax(sched)[:min]

      if min
        res[:spt] = min unless res[:spt]
        res[:spt] = min     if res[:spt] > min
      end
    end

    unless sched.to_ScheduleConstant.empty?
      sched = sched.to_ScheduleConstant.get
      min = scheduleConstantMinMax(sched)[:min]

      if min
        res[:spt] = min unless res[:spt]
        res[:spt] = min     if res[:spt] > min
      end
    end

    unless sched.to_ScheduleCompact.empty?
      sched = sched.to_ScheduleCompact.get
      min = scheduleCompactMinMax(sched)[:min]

      if min
        res[:spt] = min unless res[:spt]
        res[:spt] = min     if res[:spt] > min
      end
    end
  end

  return res if zone.thermostat.empty?

  tstat     = zone.thermostat.get
  res[:spt] = nil

  unless tstat.to_ThermostatSetpointDualSetpoint.empty? &&
         tstat.to_ZoneControlThermostatStagedDualSetpoint.empty?

    unless tstat.to_ThermostatSetpointDualSetpoint.empty?
      tstat = tstat.to_ThermostatSetpointDualSetpoint.get
    else
      tstat = tstat.to_ZoneControlThermostatStagedDualSetpoint.get
    end

    unless tstat.coolingSetpointTemperatureSchedule.empty?
      res[:dual] = true
      sched = tstat.coolingSetpointTemperatureSchedule.get

      unless sched.to_ScheduleRuleset.empty?
        sched = sched.to_ScheduleRuleset.get
        min = scheduleRulesetMinMax(sched)[:min]

        if min
          res[:spt] = min unless res[:spt]
          res[:spt] = min     if res[:spt] > min
        end

        dd = sched.summerDesignDaySchedule

        unless dd.values.empty?
          res[:spt] = dd.values.min unless res[:spt]
          res[:spt] = dd.values.min     if res[:spt] > dd.values.min
        end
      end

      unless sched.to_ScheduleConstant.empty?
        sched = sched.to_ScheduleConstant.get
        min = scheduleConstantMinMax(sched)[:min]

        if min
          res[:spt] = min unless res[:spt]
          res[:spt] = min     if res[:spt] > min
        end
      end

      unless sched.to_ScheduleCompact.empty?
        sched = sched.to_ScheduleCompact.get
        min = scheduleCompactMinMax(sched)[:min]

        if min
          res[:spt] = min unless res[:spt]
          res[:spt] = min     if res[:spt] > min
        end
      end

      unless sched.to_ScheduleYear.empty?
        sched = sched.to_ScheduleYear.get

        sched.getScheduleWeeks.each do |week|
          next if week.summerDesignDaySchedule.empty?

          dd = week.summerDesignDaySchedule.get
          next unless dd.values.empty?

          res[:spt] = dd.values.min unless res[:spt]
          res[:spt] = dd.values.min     if res[:spt] > dd.values.min
        end
      end
    end
  end

  res
end

#nearest(pts = nil, p01 = nil) ⇒ Integer?

Returns OpenStudio 3D point (in a set) nearest to a point of reference, e.g. grid origin. If left unspecified, the method systematically returns the bottom-left corner (BLC) of any horizontal set. If more than one point fits the initial criteria, the method relies on deterministic sorting through triangulation.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

  • p01 (OpenStudio::Point3d) (defaults to: nil)

    point of reference

Returns:

  • (Integer)

    set index of nearest point to point of reference

  • (nil)

    if invalid input (see logs)



2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
# File 'lib/osut/utils.rb', line 2507

def nearest(pts = nil, p01 = nil)
  mth = "OSut::#{__callee__}"
  l   = 100
  d01 = 10000
  d02 = 0
  d03 = 0
  idx = nil
  pts = to_p3Dv(pts)
  return idx if pts.empty?

  p03 = OpenStudio::Point3d.new( l,-l,-l)
  p02 = OpenStudio::Point3d.new( l, l, l)
  p01 = OpenStudio::Point3d.new(-l,-l,-l) unless p01
  return mismatch("point", p01, cl, mth) unless p01.is_a?(OpenStudio::Point3d)

  pts.each_with_index { |pt, i| return i if same?(pt, p01) }

  pts.each_with_index do |pt, i|
    length01 = (pt - p01).length
    length02 = (pt - p02).length
    length03 = (pt - p03).length

    if length01.round(2) == d01.round(2)
      if length02.round(2) == d02.round(2)
        if length03.round(2) > d03.round(2)
          idx = i
          d03 = length03
        end
      elsif length02.round(2) > d02.round(2)
        idx = i
        d03 = length03
        d02 = length02
      end
    elsif length01.round(2) < d01.round(2)
      idx = i
      d01 = length01
      d02 = length02
      d03 = length03
    end
  end

  idx
end

#nextUp(pts = nil, pt = nil) ⇒ OpenStudio::Point3d?

Returns next sequential point in an OpenStudio 3D point vector.

Parameters:

  • pts (OpenStudio::Point3dVector) (defaults to: nil)

    3D points

  • pt (OpenStudio::Point3d) (defaults to: nil)

    a given 3D point

Returns:

  • (OpenStudio::Point3d)

    the next sequential point

  • (nil)

    if invalid input (see logs)



2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
# File 'lib/osut/utils.rb', line 2678

def nextUp(pts = nil, pt = nil)
  mth = "OSut::#{__callee__}"
  pts = to_p3Dv(pts)
  cl  = OpenStudio::Point3d
  return mismatch("point", pt, cl, mth)  unless pt.is_a?(cl)
  return invalid("points (2+)", mth, 1, WRN) if pts.size < 2

  pair = pts.each_cons(2).find { |p1, _| same?(p1, pt) }

  pair.nil? ? pts.first : pair.last
end

#offset(p1 = nil, w = 0, v = 0) ⇒ OpenStudio::Point3dVector

Generates offset vertices (by width) for a 3- or 4-sided, convex polygon. If width is negative, the vertices are contracted inwards.

Parameters:

  • p1 (Set<OpenStudio::Point3d>) (defaults to: nil)

    OpenStudio 3D points

  • w (#to_f) (defaults to: 0)

    offset width (absolute min: 0.0254m)

  • v (#to_i) (defaults to: 0)

    OpenStudio SDK version, eg ‘321’ for “v3.2.1” (optional)

Returns:

  • (OpenStudio::Point3dVector)

    offset points (see logs if unaltered)



3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
# File 'lib/osut/utils.rb', line 3727

def offset(p1 = nil, w = 0, v = 0)
  mth = "OSut::#{__callee__}"
  pts = poly(p1, true, true, false, true, :cw)
  return invalid("points", mth, 1, DBG, p1) unless [3, 4].include?(pts.size)

  mismatch("width",   w, Numeric, mth) unless w.respond_to?(:to_f)
  mismatch("version", v, Integer, mth) unless v.respond_to?(:to_i)

  iv = pts.size == 4 ? true : false
  vs = OpenStudio.openStudioVersion.split(".").join.to_i
  v  = v.respond_to?(:to_i) ? v.to_i : vs
  w  = w.respond_to?(:to_f) ? w.to_f : 0
  return p1 if w.abs < 0.0254

  unless v < 340
    t      = OpenStudio::Transformation.alignFace(p1)
    offset = OpenStudio.buffer(pts, w, TOL)
    return p1 if offset.empty?

    return to_p3Dv(t * offset.get.reverse)
  else # brute force approach
    pz     = {}
    pz[:A] = {}
    pz[:B] = {}
    pz[:C] = {}
    pz[:D] = {}                                                          if iv

    pz[:A][:p] = OpenStudio::Point3d.new(p1[0].x, p1[0].y, p1[0].z)
    pz[:B][:p] = OpenStudio::Point3d.new(p1[1].x, p1[1].y, p1[1].z)
    pz[:C][:p] = OpenStudio::Point3d.new(p1[2].x, p1[2].y, p1[2].z)
    pz[:D][:p] = OpenStudio::Point3d.new(p1[3].x, p1[3].y, p1[3].z)      if iv

    pzAp = pz[:A][:p]
    pzBp = pz[:B][:p]
    pzCp = pz[:C][:p]
    pzDp = pz[:D][:p]                                                    if iv

    # Generate vector pairs, from next point & from previous point.
    # :f_n : "from next"
    # :f_p : "from previous"
    #
    #
    #
    #
    #
    #
    #             A <---------- B
    #              ^
    #               \
    #                \
    #                 C (or D)
    #
    pz[:A][:f_n] = pzAp - pzBp
    pz[:A][:f_p] = pzAp - pzCp                                       unless iv
    pz[:A][:f_p] = pzAp - pzDp                                           if iv

    pz[:B][:f_n] = pzBp - pzCp
    pz[:B][:f_p] = pzBp - pzAp

    pz[:C][:f_n] = pzCp - pzAp                                       unless iv
    pz[:C][:f_n] = pzCp - pzDp                                           if iv
    pz[:C][:f_p] = pzCp - pzBp

    pz[:D][:f_n] = pzDp - pzAp                                           if iv
    pz[:D][:f_p] = pzDp - pzCp                                           if iv

    # Generate 3D plane from vectors.
    #
    #
    #             |  <<< 3D plane ... from point A, with normal B>A
    #             |
    #             |
    #             |
    # <---------- A <---------- B
    #             |\
    #             | \
    #             |  \
    #             |   C (or D)
    #
    pz[:A][:pl_f_n] = OpenStudio::Plane.new(pzAp, pz[:A][:f_n])
    pz[:A][:pl_f_p] = OpenStudio::Plane.new(pzAp, pz[:A][:f_p])

    pz[:B][:pl_f_n] = OpenStudio::Plane.new(pzBp, pz[:B][:f_n])
    pz[:B][:pl_f_p] = OpenStudio::Plane.new(pzBp, pz[:B][:f_p])

    pz[:C][:pl_f_n] = OpenStudio::Plane.new(pzCp, pz[:C][:f_n])
    pz[:C][:pl_f_p] = OpenStudio::Plane.new(pzCp, pz[:C][:f_p])

    pz[:D][:pl_f_n] = OpenStudio::Plane.new(pzDp, pz[:D][:f_n])          if iv
    pz[:D][:pl_f_p] = OpenStudio::Plane.new(pzDp, pz[:D][:f_p])          if iv

    # Project an extended point (pC) unto 3D plane.
    #
    #             pC   <<< projected unto extended B>A 3D plane
    #        eC   |
    #          \  |
    #           \ |
    #            \|
    # <---------- A <---------- B
    #             |\
    #             | \
    #             |  \
    #             |   C (or D)
    #
    pz[:A][:p_n_pl] = pz[:A][:pl_f_n].project(pz[:A][:p] + pz[:A][:f_p])
    pz[:A][:n_p_pl] = pz[:A][:pl_f_p].project(pz[:A][:p] + pz[:A][:f_n])

    pz[:B][:p_n_pl] = pz[:B][:pl_f_n].project(pz[:B][:p] + pz[:B][:f_p])
    pz[:B][:n_p_pl] = pz[:B][:pl_f_p].project(pz[:B][:p] + pz[:B][:f_n])

    pz[:C][:p_n_pl] = pz[:C][:pl_f_n].project(pz[:C][:p] + pz[:C][:f_p])
    pz[:C][:n_p_pl] = pz[:C][:pl_f_p].project(pz[:C][:p] + pz[:C][:f_n])

    pz[:D][:p_n_pl] = pz[:D][:pl_f_n].project(pz[:D][:p] + pz[:D][:f_p]) if iv
    pz[:D][:n_p_pl] = pz[:D][:pl_f_p].project(pz[:D][:p] + pz[:D][:f_n]) if iv

    # Generate vector from point (e.g. A) to projected extended point (pC).
    #
    #             pC
    #        eC   ^
    #          \  |
    #           \ |
    #            \|
    # <---------- A <---------- B
    #             |\
    #             | \
    #             |  \
    #             |   C (or D)
    #
    pz[:A][:n_p_n_pl] = pz[:A][:p_n_pl] - pzAp
    pz[:A][:n_n_p_pl] = pz[:A][:n_p_pl] - pzAp

    pz[:B][:n_p_n_pl] = pz[:B][:p_n_pl] - pzBp
    pz[:B][:n_n_p_pl] = pz[:B][:n_p_pl] - pzBp

    pz[:C][:n_p_n_pl] = pz[:C][:p_n_pl] - pzCp
    pz[:C][:n_n_p_pl] = pz[:C][:n_p_pl] - pzCp

    pz[:D][:n_p_n_pl] = pz[:D][:p_n_pl] - pzDp                           if iv
    pz[:D][:n_n_p_pl] = pz[:D][:n_p_pl] - pzDp                           if iv

    # Fetch angle between both extended vectors (A>pC & A>pB),
    # ... then normalize (Cn).
    #
    #             pC
    #        eC   ^
    #          \  |
    #           \ Cn
    #            \|
    # <---------- A <---------- B
    #             |\
    #             | \
    #             |  \
    #             |   C (or D)
    #
    a1 = OpenStudio.getAngle(pz[:A][:n_p_n_pl], pz[:A][:n_n_p_pl])
    a2 = OpenStudio.getAngle(pz[:B][:n_p_n_pl], pz[:B][:n_n_p_pl])
    a3 = OpenStudio.getAngle(pz[:C][:n_p_n_pl], pz[:C][:n_n_p_pl])
    a4 = OpenStudio.getAngle(pz[:D][:n_p_n_pl], pz[:D][:n_n_p_pl])       if iv

    # Generate new 3D points A', B', C' (and D') ... zigzag.
    #
    #
    #
    #
    #     A' ---------------------- B'
    #      \
    #       \      A <---------- B
    #        \      \
    #         \      \
    #          \      \
    #           C'      C
    pz[:A][:f_n].normalize
    pz[:A][:n_p_n_pl].normalize
    pzAp = pzAp + scalar(pz[:A][:n_p_n_pl], w)
    pzAp = pzAp + scalar(pz[:A][:f_n], w * Math.tan(a1/2))

    pz[:B][:f_n].normalize
    pz[:B][:n_p_n_pl].normalize
    pzBp = pzBp + scalar(pz[:B][:n_p_n_pl], w)
    pzBp = pzBp + scalar(pz[:B][:f_n], w * Math.tan(a2/2))

    pz[:C][:f_n].normalize
    pz[:C][:n_p_n_pl].normalize
    pzCp = pzCp + scalar(pz[:C][:n_p_n_pl], w)
    pzCp = pzCp + scalar(pz[:C][:f_n], w * Math.tan(a3/2))

    pz[:D][:f_n].normalize                                               if iv
    pz[:D][:n_p_n_pl].normalize                                          if iv
    pzDp = pzDp + scalar(pz[:D][:n_p_n_pl], w)                           if iv
    pzDp = pzDp + scalar(pz[:D][:f_n], w * Math.tan(a4/2))               if iv

    # Re-convert to OpenStudio 3D points.
    vec  = OpenStudio::Point3dVector.new
    vec << OpenStudio::Point3d.new(pzAp.x, pzAp.y, pzAp.z)
    vec << OpenStudio::Point3d.new(pzBp.x, pzBp.y, pzBp.z)
    vec << OpenStudio::Point3d.new(pzCp.x, pzCp.y, pzCp.z)
    vec << OpenStudio::Point3d.new(pzDp.x, pzDp.y, pzDp.z)               if iv

    return vec
  end
end

#outline(a = [], bfr = 0, flat = true) ⇒ OpenStudio::Point3dVector

Generates a ULC OpenStudio 3D point vector (a bounding box) that surrounds multiple (smaller) OpenStudio 3D point vectors. The generated, 4-point outline is optionally buffered (or offset). Frame and Divider frame widths are taken into account.

Parameters:

  • a (Array) (defaults to: [])

    sets of OpenStudio 3D points

  • bfr (Numeric) (defaults to: 0)

    an optional buffer size (min: 0.0254m)

  • flat (Bool) (defaults to: true)

    if points are to be pre-flattened (Z=0)

Returns:

  • (OpenStudio::Point3dVector)

    ULC outline (see logs if empty)



3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
# File 'lib/osut/utils.rb', line 3941

def outline(a = [], bfr = 0, flat = true)
  mth  = "OSut::#{__callee__}"
  flat = true unless [true, false].include?(flat)
  xMIN = nil
  xMAX = nil
  yMIN = nil
  yMAX = nil
  a2   = []
  out  = OpenStudio::Point3dVector.new
  cl   = Array
  return mismatch("array", a, cl, mth, DBG, out) unless a.is_a?(cl)
  return empty("array",           mth, DBG, out)     if a.empty?

  mismatch("buffer", bfr, Numeric, mth) unless bfr.respond_to?(:to_f)

  bfr = bfr.to_f if bfr.respond_to?(:to_f)
  bfr = 0    unless bfr.respond_to?(:to_f)
  bfr = 0        if bfr < 0.0254
  vtx = poly(a.first)
  return out if vtx.empty?

  t = OpenStudio::Transformation.alignFace(vtx)

  a.each do |pts|
    points = poly(pts, false, true, false, t)
    points = flatten(points) if flat
    next if points.empty?

    a2 << points
  end

  a2.each do |pts|
    minX = pts.min_by(&:x).x
    maxX = pts.max_by(&:x).x
    minY = pts.min_by(&:y).y
    maxY = pts.max_by(&:y).y

    # Consider frame width, if frame-and-divider-enabled sub surface.
    if pts.respond_to?(:allowWindowPropertyFrameAndDivider)
      fd = pts.windowPropertyFrameAndDivider
      w  = 0
      w  = fd.get.frameWidth unless fd.empty?

      if w > TOL
        minX -= w
        maxX += w
        minY -= w
        maxY += w
      end
    end

    xMIN = minX if xMIN.nil?
    xMAX = maxX if xMAX.nil?
    yMIN = minY if yMIN.nil?
    yMAX = maxY if yMAX.nil?

    xMIN = [xMIN, minX].min
    xMAX = [xMAX, maxX].max
    yMIN = [yMIN, minY].min
    yMAX = [yMAX, maxY].max
  end

  return negative("outline width",  mth, DBG, out) if xMAX < xMIN
  return negative("outline height", mth, DBG, out) if yMAX < yMIN
  return zero("outline width",      mth, DBG, out) if (xMIN - xMAX).abs < TOL
  return zero("outline height",     mth, DBG, out) if (yMIN - yMAX).abs < TOL

  # Generate ULC point 3D vector.
  out << OpenStudio::Point3d.new(xMIN, yMAX, 0)
  out << OpenStudio::Point3d.new(xMIN, yMIN, 0)
  out << OpenStudio::Point3d.new(xMAX, yMIN, 0)
  out << OpenStudio::Point3d.new(xMAX, yMAX, 0)

  # Apply buffer, apply ULC (options).
  out = offset(out, bfr, 300) if bfr > 0.0254

  to_p3Dv(t * out)
end

#overlap(p1 = nil, p2 = nil, flat = false) ⇒ OpenStudio::Point3dVector

Returns intersection of overlapping polygons, empty if non intersecting. If the optional 3rd argument is left as false, the 2nd polygon may only overlap if it shares the 3D plane equation of the 1st one. If the 3rd argument is instead set to true, then the 2nd polygon is first cast onto the 3D plane of the 1st one; the method therefore returns (as overlap) the intersection of a projection of the 2nd polygon onto the 1st one. The method returns the smallest of the 2 polygons if either fits within the larger one.

Parameters:

  • p1 (Set<OpenStudio::Point3d>) (defaults to: nil)

    1st set of 3D points

  • p2 (Set<OpenStudio::Point3d>) (defaults to: nil)

    2nd set of 3D points

  • flat (Bool) (defaults to: false)

    whether to first align the 2nd set onto the 1st set plane

Returns:

  • (OpenStudio::Point3dVector)

    largest intersection (see logs if empty)



3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
# File 'lib/osut/utils.rb', line 3582

def overlap(p1 = nil, p2 = nil, flat = false)
  mth  = "OSut::#{__callee__}"
  flat = false unless [true, false].include?(flat)
  face = OpenStudio::Point3dVector.new
  p01  = poly(p1)
  p02  = poly(p2)
  return empty("points 1", mth, DBG, face) if p01.empty?
  return empty("points 2", mth, DBG, face) if p02.empty?
  return p01 if fits?(p01, p02)
  return p02 if fits?(p02, p01)

  if xyz?(p01, :z)
    t   = nil
    cw1 = clockwise?(p01)
    a1  = cw1 ? p01.to_a.reverse : p01.to_a
    a2  = p02.to_a
    a2  = flatten(a2).to_a if flat
    return invalid("points 2", mth, 2, DBG, face) unless xyz?(a2, :z)

    cw2 = clockwise?(a2)
    a2  = a2.reverse if cw2
  else
    t   = OpenStudio::Transformation.alignFace(p01)
    a1  = t.inverse * p01
    a2  = t.inverse * p02
    a2  = flatten(a2).to_a if flat
    return invalid("points 2", mth, 2, DBG, face) unless xyz?(a2, :z)

    cw2 = clockwise?(a2)
    a2  = a2.reverse if cw2
  end

  # Return either (transformed) polygon if one fits into the other.
  p1t = p01

  if t
    p2t = to_p3Dv(cw2 ? t * a2 : t * a2.reverse)
  else
    if cw1
      p2t = to_p3Dv(cw2 ? a2.reverse : a2)
    else
      p2t = to_p3Dv(cw2 ? a2 : a2.reverse)
    end
  end

  return p1t if fits?(a1, a2)
  return p2t if fits?(a2, a1)

  area1 = OpenStudio.getArea(a1)
  area2 = OpenStudio.getArea(a2)
  return empty("points 1 area", mth, ERR, face) if area1.empty?
  return empty("points 2 area", mth, ERR, face) if area2.empty?

  area1 = area1.get
  area2 = area2.get
  union = OpenStudio.join(a1.reverse, a2.reverse, TOL2)
  return face if union.empty?

  union = union.get
  area  = OpenStudio.getArea(union)
  return face if area.empty?

  area  = area.get
  delta = area1 + area2 - area

  if area > TOL
    return face if  area.round(2) == area1.round(2)
    return face if  area.round(2) == area2.round(2)
    return face if delta.round(2) == 0
  end

  res = OpenStudio.intersect(a1.reverse, a2.reverse, TOL)
  return face if res.empty?

  res  = res.get
  res1 = res.polygon1
  return face if res1.empty?

  to_p3Dv(t ? t * res1.reverse : res1.reverse)
end

#overlaps?(p1 = nil, p2 = nil, flat = false) ⇒ Bool, false

Determines whether OpenStudio polygons overlap.

Parameters:

  • p1 (Set<OpenStudio::Point3d>) (defaults to: nil)

    1st set of 3D points

  • p2 (Set<OpenStudio::Point3d>) (defaults to: nil)

    2nd set of 3D points

  • flat (Bool) (defaults to: false)

    whether points are to be pre-flattened (Z=0)

Returns:

  • (Bool)

    whether polygons overlap (or fit)

  • (false)

    if invalid input (see logs)



3672
3673
3674
# File 'lib/osut/utils.rb', line 3672

def overlaps?(p1 = nil, p2 = nil, flat = false)
  overlap(p1, p2, flat).empty? ? false : true
end

#parallel?(p1 = nil, p2 = nil) ⇒ Bool, false

Validates whether 2 polygons are parallel, regardless of their direction.

Parameters:

  • p1 (Set<OpenStudio::Point3d>) (defaults to: nil)

    1st set of 3D points

  • p2 (Set<OpenStudio::Point3d>) (defaults to: nil)

    2nd set of 3D points

Returns:

  • (Bool)

    whether 2 polygons are parallel

  • (false)

    if invalid input (see logs)



3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
# File 'lib/osut/utils.rb', line 3398

def parallel?(p1 = nil, p2 = nil)
  p1 = poly(p1, false, true)
  p2 = poly(p2, false, true)
  return false if p1.empty?
  return false if p2.empty?

  n1 = OpenStudio.getOutwardNormal(p1)
  n2 = OpenStudio.getOutwardNormal(p2)
  return false if n1.empty?
  return false if n2.empty?

  n1.get.dot(n2.get).abs > 0.99
end

#plenum?(space = nil) ⇒ Bool, false

Validates whether a space is an indirectly-conditioned plenum.

Parameters:

  • space (OpenStudio::Model::Space) (defaults to: nil)

    a space

Returns:

  • (Bool)

    whether space is considered a plenum

  • (false)

    if invalid input (see logs)



1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
# File 'lib/osut/utils.rb', line 1884

def plenum?(space = nil)
  # Largely inspired from NREL's "space_plenum?":
  #
  #   github.com/NREL/openstudio-standards/blob/
  #   58964222d25783e9da4ae292e375fb0d5c902aa5/lib/openstudio-standards/
  #   standards/Standards.Space.rb#L1384
  #
  # Ideally, "plenum?" should be in sync with OpenStudio SDK's "isPlenum"
  # method, which solely looks for either HVAC air mixer objects:
  #  - AirLoopHVACReturnPlenum
  #  - AirLoopHVACSupplyPlenum
  #
  # Of the OpenStudio-Standards Prototype models, only the LargeOffice
  # holds AirLoopHVACReturnPlenum objects. OpenStudio-Standards' method
  # "space_plenum?" indeed catches them by checking if the space is
  # "partofTotalFloorArea" (which internally has an "isPlenum" check). So
  # "isPlenum" closely follows ASHRAE 90.1 2016's definition of "plenum":
  #
  #   "plenum": a compartment or chamber ...
  #             - to which one or more ducts are connected
  #             - that forms a part of the air distribution system, and
  #             - that is NOT USED for occupancy or storage.
  #
  # Canadian NECB 2020 has the following (not as well) defined term:
  #   "plenum": a chamber forming part of an air duct system.
  #             ... we'll assume that a space shall also be considered
  #             UNOCCUPIED if it's "part of an air duct system".
  #
  # As intended, "isPlenum" would NOT identify as a "plenum" any vented
  # UNCONDITIONED or UNENCLOSED attic or crawlspace - good. Yet "isPlenum"
  # would also ignore dead air spaces integrating ducted return air. The
  # SDK's "partofTotalFloorArea" would be more suitable in such cases, as
  # long as modellers have, a priori, set this parameter to FALSE.
  #
  # By initially relying on the SDK's "partofTotalFloorArea", "space_plenum?"
  # ends up catching a MUCH WIDER range of spaces, which aren't caught by
  # "isPlenum". This includes attics, crawlspaces, non-plenum air spaces above
  # ceiling tiles, and any other UNOCCUPIED space in a model. The term
  # "plenum" in this context is more of a catch-all shorthand - to be used
  # with caution. For instance, "space_plenum?" shouldn't be used (in
  # isolation) to determine whether an UNOCCUPIED space should have its
  # envelope insulated ("plenum") or not ("attic").
  #
  # In contrast to OpenStudio-Standards' "space_plenum?", the method below
  # strictly returns FALSE if a space is indeed "partofTotalFloorArea". It
  # also returns FALSE if the space is a vestibule. Otherwise, it needs more
  # information to determine if such an UNOCCUPIED space is indeed a
  # plenum. Beyond these 2x criteria, a space is considered a plenum if:
  #
  # CASE A: it includes the substring "plenum" (case insensitive) in its
  #         spaceType's name, or in the latter's standardsSpaceType string;
  #
  # CASE B: "isPlenum" == TRUE in an OpenStudio model WITH HVAC airloops; OR
  #
  # CASE C: its zone holds an 'inactive' thermostat (i.e. can't extract valid
  #         setpoints) in an OpenStudio model with setpoint temperatures.
  #
  # If a modeller is instead simply interested in identifying UNOCCUPIED
  # spaces that are INDIRECTLYCONDITIONED (not necessarily plenums), then the
  # following combination is likely more reliable and less confusing:
  #   - SDK's partofTotalFloorArea == FALSE
  #   - OSut's unconditioned? == FALSE
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Space
  return mismatch("space", space, cl, mth, DBG, false) unless space.is_a?(cl)
  return false if space.partofTotalFloorArea
  return false if vestibule?(space)

  # CASE A: "plenum" spaceType.
  unless space.spaceType.empty?
    type = space.spaceType.get
    return true if type.nameString.downcase.include?("plenum")

    unless type.standardsSpaceType.empty?
      type = type.standardsSpaceType.get.downcase
      return true if type.include?("plenum")
    end
  end

  # CASE B: "isPlenum" == TRUE if airloops.
  return space.isPlenum if airLoopsHVAC?(space.model)

  # CASE C: zone holds an 'inactive' thermostat.
  zone   = space.thermalZone
  heated = heatingTemperatureSetpoints?(space.model)
  cooled = coolingTemperatureSetpoints?(space.model)

  if heated || cooled
    return false if zone.empty?

    zone = zone.get
    heat = maxHeatScheduledSetpoint(zone)
    cool = minCoolScheduledSetpoint(zone)
    return false if heat[:spt] || cool[:spt] # directly CONDITIONED
    return heat[:dual] || cool[:dual]        # FALSE if both are nilled
  end

  false
end

#pointAlongSegment?(p0 = nil, sg = []) ⇒ Bool, false

Validates whether a 3D point lies ~along a 3D point segment, i.e. less than 10mm from any segment.

Parameters:

  • p0 (OpenStudio::Point3d) (defaults to: nil)

    a 3D point

  • sg (Set<OpenStudio::Point3d] a 3D point segment) (defaults to: [])

    g [Set<OpenStudio::Point3d] a 3D point segment

Returns:

  • (Bool)

    whether a 3D point lies ~along a 3D point segment

  • (false)

    if invalid input (see logs)



2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
# File 'lib/osut/utils.rb', line 2904

def pointAlongSegment?(p0 = nil, sg = [])
  mth = "OSut::#{__callee__}"
  cl1 = OpenStudio::Point3d
  cl2 = OpenStudio::Point3dVector
  return mismatch(  "point", p0, cl1, mth, DBG, false) unless p0.is_a?(cl1)
  return mismatch("segment", sg, cl2, mth, DBG, false) unless segment?(sg)

  return true if holds?(sg, p0)

  a   = sg.first
  b   = sg.last
  ab  = b - a
  abn = b - a
  abn.normalize
  ap  = p0 - a
  sp = ap.dot(abn)
  return false if sp < 0

  apd = scalar(abn, sp)
  return false if apd.length > ab.length + TOL

  ap0 = a + apd
  return true if (p0 - ap0).length.round(2) <= TOL

  false
end

#pointAlongSegments?(p0 = nil, sgs = []) ⇒ Bool, false

Validates whether a 3D point lies anywhere ~along a set of 3D point segments, i.e. less than 10mm from any segment.

Parameters:

  • p0 (OpenStudio::Point3d) (defaults to: nil)

    a 3D point

  • sgs (Set<OpenStudio::Point3d] 3D point segments) (defaults to: [])

    gs [Set<OpenStudio::Point3d] 3D point segments

Returns:

  • (Bool)

    whether a 3D point lies ~along a set of 3D point segments

  • (false)

    if invalid input (see logs)



2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
# File 'lib/osut/utils.rb', line 2940

def pointAlongSegments?(p0 = nil, sgs = [])
  mth = "OSut::#{__callee__}"
  cl1 = OpenStudio::Point3d
  cl2 = OpenStudio::Point3dVectorVector
  sgs = sgs.is_a?(cl2) ? sgs : getSegments(sgs)
  return empty("segments",         mth, DBG, false)     if sgs.empty?
  return mismatch("point", p0, cl, mth, DBG, false) unless p0.is_a?(cl1)

  sgs.each { |sg| return true if pointAlongSegment?(p0, sg) }

  false
end

#pointWithinPolygon?(p0 = nil, s = [], entirely = false) ⇒ Bool, false

Validates whether 3D point is within a 3D polygon. If option ‘entirely’ is set to true, then the method returns false if point lies along any of the polygon edges, or is very near any of its vertices.

Parameters:

  • p0 (OpenStudio::Point3d) (defaults to: nil)

    a 3D point

  • s (Set<OpenStudio::Point3d] a 3D polygon) (defaults to: [])
    Set<OpenStudio::Point3d

    a 3D polygon

  • entirely (Bool) (defaults to: false)

    whether point should be neatly within polygon limits

Returns:

  • (Bool)

    whether a 3D point lies within a 3D polygon

  • (false)

    if invalid input (see logs)



3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
# File 'lib/osut/utils.rb', line 3332

def pointWithinPolygon?(p0 = nil, s = [], entirely = false)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Point3d
  s   = poly(s, false, true, true)
  return empty("polygon",          mth, DBG, false)     if s.empty?
  return mismatch("point", p0, cl, mth, DBG, false) unless p0.is_a?(cl)

  n = OpenStudio.getOutwardNormal(s)
  return invalid("plane/normal", mth, 2, DBG, false) if n.empty?

  n  = n.get
  pl = OpenStudio::Plane.new(s.first, n)
  return false unless pl.pointOnPlane(p0)

  entirely = false unless [true, false].include?(entirely)
  segments = getSegments(s)

  # Along polygon edges, or near vertices?
  if pointAlongSegments?(p0, segments)
    return false    if entirely
    return true unless entirely
  end

  segments.each do |segment|
    #   - draw vector from segment midpoint to point
    #   - scale 1000x (assuming no building surface would be 1km wide)
    #   - convert vector to an independent line segment
    #   - loop through polygon segments, tally the number of intersections
    #   - avoid double-counting polygon vertices as intersections
    #   - return false if number of intersections is even
    mid = midpoint(segment.first, segment.last)
    mpV = scalar(mid - p0, 1000)
    p1  = p0 + mpV
    ctr = 0

    # Skip if ~collinear.
    next if mpV.cross(segment.last - segment.first).length.round(4) < TOL2

    segments.each do |sg|
      intersect = getLineIntersection([p0, p1], sg)
      next unless intersect

      # Skip test altogether if one of the polygon vertices.
      if holds?(s, intersect)
        ctr = 0
        break
      else
        ctr += 1
      end
    end

    next         if ctr.zero?
    return false if ctr.even?
  end

  true
end

#poly(pts = nil, vx = false, uq = false, co = false, tt = false, sq = :no) ⇒ OpenStudio::Point3dVector

Returns an OpenStudio 3D point vector as basis for a valid OpenStudio 3D polygon. In addition to basic OpenStudio polygon tests (e.g. all points sharing the same 3D plane, non-self-intersecting), the method can optionally check for convexity, or ensure uniqueness and/or non-collinearity. Returned vector can also be ‘aligned’, as well as in UpperLeftCorner (ULC), BottomLeftCorner (BLC), in clockwise (or counterclockwise) sequence.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

  • vx (Bool) (defaults to: false)

    whether to check for convexity

  • uq (Bool) (defaults to: false)

    whether to ensure uniqueness

  • co (Bool) (defaults to: false)

    whether to ensure non-collinearity

  • tt (Bool, OpenStudio::Transformation) (defaults to: false)

    whether to ‘align’

  • sq (:no, :ulc, :blc, :cw) (defaults to: :no)

    unaltered, ULC, BLC or clockwise sequence

Returns:

  • (OpenStudio::Point3dVector)

    3D points (see logs if empty)



3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
# File 'lib/osut/utils.rb', line 3222

def poly(pts = nil, vx = false, uq = false, co = false, tt = false, sq = :no)
  mth = "OSut::#{__callee__}"
  pts = to_p3Dv(pts)
  cl  = OpenStudio::Transformation
  v   = OpenStudio::Point3dVector.new
  vx  = false unless [true, false].include?(vx)
  uq  = false unless [true, false].include?(uq)
  co  = false unless [true, false].include?(co)

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Exit if mismatched/invalid arguments.
  ok1 = tt == true || tt == false || tt.is_a?(cl)
  ok2 = sq == :no  || sq == :ulc  || sq == :blc || sq == :cw
  return invalid("transformation", mth, 5, DBG, v) unless ok1
  return invalid("sequence",       mth, 6, DBG, v) unless ok2

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Minimum 3 points?
  p3 = getNonCollinears(pts, 3)
  return empty("polygon (non-collinears < 3)", mth, ERR, v) if p3.size < 3

  # Coplanar?
  pln = OpenStudio::Plane.new(p3)

  pts.each do |pt|
    return empty("plane", mth, ERR, v) unless pln.pointOnPlane(pt)
  end

  t  = OpenStudio::Transformation.alignFace(pts)
  at = (t.inverse * pts).reverse

  if tt.is_a?(cl)
    att = (tt.inverse * pts).reverse

    if same?(at, att)
      a = att
      a = ulc(a).to_a if clockwise?(a)
      t = nil
    else
      t = xyz?(att, :z) ? nil : OpenStudio::Transformation.alignFace(att)
      a = t ? (t.inverse * att).reverse : att
    end
  else
    a = at
  end

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Ensure uniqueness and/or non-collinearity. Preserve original sequence.
  p0 = a.first
  a  = getUniques(a).to_a       if uq
  a  = getNonCollinears(a).to_a if co
  i0 = a.index { |pt| same?(pt, p0) }
  a  = a.rotate(i0)             unless i0.nil?

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Check for convexity (optional).
  if vx && a.size > 3
    zen = OpenStudio::Point3d.new(0, 0, 1000)

    getTriads(a).each do |trio|
      p1  = trio[0]
      p2  = trio[1]
      p3  = trio[2]
      v12 = p2 - p1
      v13 = p3 - p1
      x   = (zen - p1).cross(v12)
      return v if x.dot(v13).round(4) > 0
    end
  end

  # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  # Alter sequence (optional).
  if tt.is_a?(cl)
    case sq
    when :ulc
      a = t ? to_p3Dv(t * ulc(a.reverse)) : to_p3Dv(ulc(a.reverse))
    when :blc
      a = t ? to_p3Dv(t * blc(a.reverse)) : to_p3Dv(blc(a.reverse))
    when :cw
      a = t ? to_p3Dv(t * a) : to_p3Dv(a)
    else
      a = t ? to_p3Dv(t * a.reverse) : to_p3Dv(a.reverse)
    end
  else
    case sq
    when :ulc
      a = tt ? to_p3Dv(ulc(a.reverse)) : to_p3Dv(t * ulc(a.reverse))
    when :blc
      a = tt ? to_p3Dv(blc(a.reverse)) : to_p3Dv(t * blc(a.reverse))
    when :cw
      a = tt ? to_p3Dv(a) : to_p3Dv(t * a)
    else
      a = tt ? to_p3Dv(a.reverse) : to_p3Dv(t * a.reverse)
    end
  end

  a
end

#rectangular?(pts = nil) ⇒ Bool, false

Validates whether an OpenStudio polygon is a rectangle (4x sides + 2x diagonals of equal length, meeting at midpoints).

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

Returns:

  • (Bool)

    whether polygon is rectangular

  • (false)

    if invalid input (see logs)



3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
# File 'lib/osut/utils.rb', line 3491

def rectangular?(pts = nil)
  pts = poly(pts, false, false, false)
  return false     if pts.empty?
  return false unless pts.size == 4

  m1 = midpoint(pts[0], pts[2])
  m2 = midpoint(pts[1], pts[3])
  return false unless same?(m1, m2)

  diag1 = pts[2] - pts[0]
  diag2 = pts[3] - pts[1]
  return true if (diag1.length - diag2.length).abs < TOL

  false
end

#refrigerated?(space = nil) ⇒ Bool, false

Validates whether a space can be considered as REFRIGERATED.

Parameters:

  • space (OpenStudio::Model::Space) (defaults to: nil)

    a space

Returns:

  • (Bool)

    whether space is considered REFRIGERATED

  • (false)

    if invalid input (see logs)



2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
# File 'lib/osut/utils.rb', line 2100

def refrigerated?(space = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Space
  tg0 = "refrigerated"
  return mismatch("space", space, cl, mth, DBG, false) unless space.is_a?(cl)

  # 1. First check OSut's REFRIGERATED status.
  status = space.additionalProperties.getFeatureAsString(tg0)

  unless status.empty?
    status = status.get
    return status if [true, false].include?(status)

    log(ERR, "Unknown #{space.nameString} REFRIGERATED #{status} (#{mth})")
  end

  # 2. Else, compare design heating/cooling setpoints.
  stps = setpoints(space)
  return false unless stps[:heating].nil?
  return false     if stps[:cooling].nil?
  return true      if stps[:cooling] < 15

  false
end

#roof?(pts = nil) ⇒ Bool, false

Validates whether a polygon can be considered a valid ‘roof’ surface, as per ASHRAE 90.1 & Canadian NECBs, i.e. outward normal within 60° from vertical

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    OpenStudio 3D points

Returns:

  • (Bool)

    if considered a roof surface

  • (false)

    if invalid input (see logs)



3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
# File 'lib/osut/utils.rb', line 3420

def roof?(pts = nil)
  ray = OpenStudio::Point3d.new(0,0,1) - OpenStudio::Point3d.new(0,0,0)
  dut = Math.cos(60 * Math::PI / 180)
  pts = poly(pts, false, true, true)
  return false if pts.empty?

  dot = ray.dot(OpenStudio.getOutwardNormal(pts).get)
  return false if dot.round(2) <= 0
  return true  if dot.round(2) == 1

  dot.round(4) >= dut.round(4)
end

#rsi(lc = nil, film = 0.0, t = 0.0) ⇒ Float, 0.0

Returns a construction’s ‘standard calc’ thermal resistance (m2•K/W), which includes air film resistances. It excludes insulating effects of shades, screens, etc. in the case of fenestrated constructions.

Parameters:

  • lc (OpenStudio::Model::LayeredConstruction) (defaults to: nil)

    a layered construction

  • film (Numeric) (defaults to: 0.0)

    thermal resistance of surface air films (m2•K/W)

  • t (Numeric) (defaults to: 0.0)

    gas temperature (°C) (optional)

Returns:

  • (Float)

    layered construction’s thermal resistance

  • (0.0)

    if invalid input (see logs)



983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
# File 'lib/osut/utils.rb', line 983

def rsi(lc = nil, film = 0.0, t = 0.0)
  # This is adapted from BTAP's Material Module "get_conductance" (P. Lopez)
  #
  #   https://github.com/NREL/OpenStudio-Prototype-Buildings/blob/
  #   c3d5021d8b7aef43e560544699fb5c559e6b721d/lib/btap/measures/
  #   btap_equest_converter/envelope.rb#L122
  mth = "OSut::#{__callee__}"
  cl1 = OpenStudio::Model::LayeredConstruction
  cl2 = Numeric
  return invalid("lc", mth, 1, DBG, 0.0) unless lc.respond_to?(NS)

  id = lc.nameString
  return mismatch(id,       lc, cl1, mth, DBG, 0.0) unless lc.is_a?(cl1)
  return mismatch("film", film, cl2, mth, DBG, 0.0) unless film.is_a?(cl2)
  return mismatch("temp K",  t, cl2, mth, DBG, 0.0) unless t.is_a?(cl2)

  t += 273.0 # °C to K
  return negative("temp K", mth, ERR, 0.0) if t < 0
  return negative("film",   mth, ERR, 0.0) if film < 0

  rsi = film

  lc.layers.each do |m|
    # Fenestration materials first.
    empty = m.to_SimpleGlazing.empty?
    return 1 / m.to_SimpleGlazing.get.uFactor                     unless empty

    empty = m.to_StandardGlazing.empty?
    rsi += m.to_StandardGlazing.get.thermalResistance             unless empty
    empty = m.to_RefractionExtinctionGlazing.empty?
    rsi += m.to_RefractionExtinctionGlazing.get.thermalResistance unless empty
    empty = m.to_Gas.empty?
    rsi += m.to_Gas.get.getThermalResistance(t)                   unless empty
    empty = m.to_GasMixture.empty?
    rsi += m.to_GasMixture.get.getThermalResistance(t)            unless empty

    # Opaque materials next.
    empty = m.to_StandardOpaqueMaterial.empty?
    rsi += m.to_StandardOpaqueMaterial.get.thermalResistance      unless empty
    empty = m.to_MasslessOpaqueMaterial.empty?
    rsi += m.to_MasslessOpaqueMaterial.get.thermalResistance      unless empty
    empty = m.to_RoofVegetation.empty?
    rsi += m.to_RoofVegetation.get.thermalResistance              unless empty
    empty = m.to_AirGap.empty?
    rsi += m.to_AirGap.get.thermalResistance                      unless empty
  end

  rsi
end

#same?(s1 = nil, s2 = nil, indexed = true) ⇒ Bool, false

Returns true if 2 sets of OpenStudio 3D points are nearly equal.

Parameters:

  • s1 (Set<OpenStudio::Point3d>) (defaults to: nil)

    1st set of 3D point(s)

  • s2 (Set<OpenStudio::Point3d>) (defaults to: nil)

    2nd set of 3D point(s)

  • indexed (Bool) (defaults to: true)

    whether to attempt to harmonize vertex sequence

Returns:

  • (Bool)

    whether sets are nearly equal (within TOL)

  • (false)

    if invalid input (see logs)



2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
# File 'lib/osut/utils.rb', line 2428

def same?(s1 = nil, s2 = nil, indexed = true)
  mth = "OSut::#{__callee__}"
  s1  = to_p3Dv(s1).to_a
  s2  = to_p3Dv(s2).to_a
  return false if s1.empty?
  return false if s2.empty?
  return false unless s1.size == s2.size

  indexed = true unless [true, false].include?(indexed)

  if indexed
    xOK = (s1[0].x - s2[0].x).abs < TOL
    yOK = (s1[0].y - s2[0].y).abs < TOL
    zOK = (s1[0].z - s2[0].z).abs < TOL

    if xOK && yOK && zOK && s1.size == 1
      return true
    else
      indx = nil

      s2.each_with_index do |pt, i|
        break if indx

        xOK = (s1[0].x - s2[i].x).abs < TOL
        yOK = (s1[0].y - s2[i].y).abs < TOL
        zOK = (s1[0].z - s2[i].z).abs < TOL

        indx = i if xOK && yOK && zOK
      end

      return false unless indx

      s2 = to_p3Dv(s2).to_a
      s2.rotate!(indx)
    end
  end

  # OpenStudio.isAlmostEqual3dPt(p1, p2, TOL) # ... from v350 onwards.
  s1.size.times.each do |i|
    xOK = (s1[i].x - s2[i].x).abs < TOL
    yOK = (s1[i].y - s2[i].y).abs < TOL
    zOK = (s1[i].z - s2[i].z).abs < TOL
    return false unless xOK && yOK && zOK
  end

  true
end

#scalar(v = OpenStudio::Vector3d.new, m = 0) ⇒ OpenStudio::Vector3d

Returns a scalar product of an OpenStudio Vector3d.

Parameters:

  • v (OpenStudio::Vector3d) (defaults to: OpenStudio::Vector3d.new)

    a vector

  • m (#to_f) (defaults to: 0)

    a scalar

Returns:

  • (OpenStudio::Vector3d)

    scaled points (see logs if empty)



2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
# File 'lib/osut/utils.rb', line 2374

def scalar(v = OpenStudio::Vector3d.new, m = 0)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Vector3d
  ok  = m.respond_to?(:to_f)
  return mismatch("vector", v, cl,      mth, DBG, v) unless v.is_a?(cl)
  return mismatch("m",      m, Numeric, mth, DBG, v) unless ok

  m = m.to_f
  OpenStudio::Vector3d.new(m * v.x, m * v.y, m * v.z)
end

#scheduleCompactMinMax(sched = nil) ⇒ Hash

Returns MIN/MAX values of a schedule (compact).

Parameters:

  • sched (OpenStudio::Model::ScheduleCompact) (defaults to: nil)

    schedule

Returns:

  • (Hash)

    min: (Float), max: (Float)

  • (Hash)

    min: nil, max: nil if invalid input (see logs)



1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
# File 'lib/osut/utils.rb', line 1374

def scheduleCompactMinMax(sched = nil)
  # Largely inspired from Andrew Parker's
  # "schedule_compact_annual_min_max_value":
  #
  # github.com/NREL/openstudio-standards/blob/
  # 99cf713750661fe7d2082739f251269c2dfd9140/lib/openstudio-standards/
  # standards/Standards.ScheduleCompact.rb#L8
  mth  = "OSut::#{__callee__}"
  cl   = OpenStudio::Model::ScheduleCompact
  vals = []
  prev = ""
  res  = { min: nil, max: nil }
  return invalid("sched", mth, 1, DBG, res) unless sched.respond_to?(NS)

  id = sched.nameString
  return mismatch(id, sched, cl, mth, DBG, res) unless sched.is_a?(cl)

  sched.extensibleGroups.each do |eg|
    if prev.include?("until")
      vals << eg.getDouble(0).get unless eg.getDouble(0).empty?
    end

    str  = eg.getString(0)
    prev = str.get.downcase unless str.empty?
  end

  return empty("#{id} values", mth, ERR, res) if vals.empty?

  res[:min] = vals.min.is_a?(Numeric) ? vals.min : nil
  res[:max] = vals.min.is_a?(Numeric) ? vals.max : nil

  res
end

#scheduleConstantMinMax(sched = nil) ⇒ Hash

Returns MIN/MAX values of a schedule (constant).

Parameters:

  • sched (OpenStudio::Model::ScheduleConstant) (defaults to: nil)

    a schedule

Returns:

  • (Hash)

    min: (Float), max: (Float)

  • (Hash)

    min: nil, max: nil if invalid inputs (see logs)



1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
# File 'lib/osut/utils.rb', line 1344

def scheduleConstantMinMax(sched = nil)
  # Largely inspired from David Goldwasser's
  # "schedule_constant_annual_min_max_value":
  #
  # github.com/NREL/openstudio-standards/blob/
  # 99cf713750661fe7d2082739f251269c2dfd9140/lib/openstudio-standards/
  # standards/Standards.ScheduleConstant.rb#L21
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::ScheduleConstant
  res = { min: nil, max: nil }
  return invalid("sched", mth, 1, DBG, res) unless sched.respond_to?(NS)

  id = sched.nameString
  return mismatch(id, sched, cl, mth, DBG, res) unless sched.is_a?(cl)

  ok = sched.value.is_a?(Numeric)
  mismatch("#{id} value", sched.value, Numeric, mth, ERR, res) unless ok
  res[:min] = sched.value
  res[:max] = sched.value

  res
end

#scheduleIntervalMinMax(sched = nil) ⇒ Hash

Returns MIN/MAX values for schedule (interval).

Parameters:

  • sched (OpenStudio::Model::ScheduleInterval) (defaults to: nil)

    schedule

Returns:

  • (Hash)

    min: (Float), max: (Float)

  • (Hash)

    min: nil, max: nil if invalid input (see logs)



1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
# File 'lib/osut/utils.rb', line 1415

def scheduleIntervalMinMax(sched = nil)
  mth  = "OSut::#{__callee__}"
  cl   = OpenStudio::Model::ScheduleInterval
  vals = []
  res  = { min: nil, max: nil }
  return invalid("sched", mth, 1, DBG, res) unless sched.respond_to?(NS)

  id = sched.nameString
  return mismatch(id, sched, cl, mth, DBG, res) unless sched.is_a?(cl)

  vals = sched.timeSeries.values

  res[:min] = vals.min.is_a?(Numeric) ? vals.min : nil
  res[:max] = vals.max.is_a?(Numeric) ? vals.min : nil

  res
end

#scheduleRulesetMinMax(sched = nil) ⇒ Hash

Returns MIN/MAX values of a schedule (ruleset).

Parameters:

  • sched (OpenStudio::Model::ScheduleRuleset) (defaults to: nil)

    a schedule

Returns:

  • (Hash)

    min: (Float), max: (Float)

  • (Hash)

    min: nil, max: nil if invalid inputs (see logs)



1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
# File 'lib/osut/utils.rb', line 1312

def scheduleRulesetMinMax(sched = nil)
  # Largely inspired from David Goldwasser's
  # "schedule_ruleset_annual_min_max_value":
  #
  # github.com/NREL/openstudio-standards/blob/
  # 99cf713750661fe7d2082739f251269c2dfd9140/lib/openstudio-standards/
  # standards/Standards.ScheduleRuleset.rb#L124
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::ScheduleRuleset
  res = { min: nil, max: nil }
  return invalid("sched", mth, 1, DBG, res) unless sched.respond_to?(NS)

  id = sched.nameString
  return mismatch(id, sched, cl, mth, DBG, res) unless sched.is_a?(cl)

  values = sched.defaultDaySchedule.values.to_a

  sched.scheduleRules.each { |rule| values += rule.daySchedule.values }

  res[:min] = values.min.is_a?(Numeric) ? values.min : nil
  res[:max] = values.max.is_a?(Numeric) ? values.max : nil

  res
end

#segment?(pts = nil) ⇒ Bool, false

Determines if a set of 3D points if a valid segment.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

Returns:

  • (Bool)

    whether set is a valid segment

  • (false)

    if invalid input (see logs)



2834
2835
2836
2837
2838
2839
2840
2841
# File 'lib/osut/utils.rb', line 2834

def segment?(pts = nil)
  pts = to_p3Dv(pts)
  return false     if pts.empty?
  return false unless pts.size == 2
  return false     if same?(pts[0], pts[1])

  true
end

#semiheated?(space = nil) ⇒ Bool, false

Validates whether a space can be considered as SEMIHEATED as per NECB 2020 1.2.1.2. 2): design heating setpoint < 15°C (and non-REFRIGERATED).

Parameters:

  • space (OpenStudio::Model::Space) (defaults to: nil)

    a space

Returns:

  • (Bool)

    whether space is considered SEMIHEATED

  • (false)

    if invalid input (see logs)



2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
# File 'lib/osut/utils.rb', line 2133

def semiheated?(space = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Space
  return mismatch("space", space, cl, mth, DBG, false) unless space.is_a?(cl)
  return false if refrigerated?(space)

  stps = setpoints(space)
  return false unless stps[:cooling].nil?
  return false     if stps[:heating].nil?
  return true      if stps[:heating] < 15

  false
end

#setpoints(space = nil) ⇒ Hash

Retrieves a space’s (implicit or explicit) heating/cooling setpoints.

Parameters:

  • space (OpenStudio::Model::Space) (defaults to: nil)

    a space

Returns:

  • (Hash)

    heating: (Float), cooling: (Float)

  • (Hash)

    heating: nil, cooling: nil if invalid input (see logs)



1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
# File 'lib/osut/utils.rb', line 1991

def setpoints(space = nil)
  mth = "OSut::#{__callee__}"
  cl1 = OpenStudio::Model::Space
  cl2 = String
  res = {heating: nil, cooling: nil}
  tg1 = "space_conditioning_category"
  tg2 = "indirectlyconditioned"
  cts = ["nonresconditioned", "resconditioned", "semiheated", "unconditioned"]
  cnd = nil
  return mismatch("space", space, cl1, mth, DBG, res) unless space.is_a?(cl1)

  # 1. Check for OpenStudio-Standards' space conditioning categories.
  if space.additionalProperties.hasFeature(tg1)
    cnd = space.additionalProperties.getFeatureAsString(tg1)

    if cnd.empty?
      cnd = nil
    else
      cnd = cnd.get

      if cts.include?(cnd.downcase)
        return res if cnd.downcase == "unconditioned"
      else
        invalid("#{tg1}:#{cnd}", mth, 0, ERR)
        cnd = nil
      end
    end
  end

  # 2. Check instead OSut's INDIRECTLYCONDITIONED (parent space) link.
  if cnd.nil?
    id = space.additionalProperties.getFeatureAsString(tg2)

    unless id.empty?
      id  = id.get
      dad = space.model.getSpaceByName(id)

      if dad.empty?
        log(ERR, "Unknown space #{id} (#{mth})")
      else
        # Now focus on 'parent' space linked to INDIRECTLYCONDITIONED space.
        space = dad.get
        cnd   = tg2
      end
    end
  end

  # 3. Fetch space setpoints (if model indeed holds valid setpoints).
  heated = heatingTemperatureSetpoints?(space.model)
  cooled = coolingTemperatureSetpoints?(space.model)
  zone   = space.thermalZone

  if heated || cooled
    return res if zone.empty? # UNCONDITIONED

    zone = zone.get
    res[:heating] = maxHeatScheduledSetpoint(zone)[:spt]
    res[:cooling] = minCoolScheduledSetpoint(zone)[:spt]
  end

  # 4. Reset if AdditionalProperties were found & valid.
  unless cnd.nil?
    if cnd.downcase == "unconditioned"
      res[:heating] = nil
      res[:cooling] = nil
    elsif cnd.downcase == "semiheated"
      res[:heating] = 14.0 if res[:heating].nil?
      res[:cooling] = nil
    elsif cnd.downcase.include?("conditioned")
      # "nonresconditioned", "resconditioned" or "indirectlyconditioned"
      res[:heating] = 21.0 if res[:heating].nil? # default
      res[:cooling] = 24.0 if res[:cooling].nil? # default
    end
  end

  # 5. Reset if plenum?
  if plenum?(space)
    res[:heating] = 21.0 if res[:heating].nil? # default
    res[:cooling] = 24.0 if res[:cooling].nil? # default
  end

  res
end

#sloped?(pts = nil) ⇒ Bool, false

Validates whether surface can be considered ‘sloped’ (i.e. not ~flat, as per OpenStudio Utilities’ “alignZPrime”). A vertical polygon returns true.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    OpenStudio 3D points

Returns:

  • (Bool)

    whether surface is sloped

  • (false)

    if invalid input (see logs)



3473
3474
3475
3476
3477
3478
3479
3480
3481
# File 'lib/osut/utils.rb', line 3473

def sloped?(pts = nil)
  mth = "OSut::#{__callee__}"
  pts = poly(pts, false, true, true)
  return false if pts.empty?
  return false if facingUp?(pts)
  return false if facingDown?(pts)

  true
end

#spandrel?(s = nil) ⇒ Bool, false

Validates whether opaque surface can be considered as a curtain wall (or similar technology) spandrel, regardless of construction layers, by looking up AdditionalProperties or its identifier.

Parameters:

  • s (OpenStudio::Model::Surface) (defaults to: nil)

    an opaque surface

Returns:

  • (Bool)

    whether surface can be considered ‘spandrel’

  • (false)

    if invalid input (see logs)



1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
# File 'lib/osut/utils.rb', line 1097

def spandrel?(s = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Surface
  return invalid("surface", mth, 1, DBG, false) unless s.respond_to?(NS)

  id = s.nameString
  m1  = "#{id}:spandrel"
  m2  = "#{id}:spandrel:boolean"
  return mismatch(id, s, cl, mth) unless s.is_a?(cl)

  if s.additionalProperties.hasFeature("spandrel")
    val = s.additionalProperties.getFeatureAsBoolean("spandrel")
    return invalid(m1, mth, 1, ERR, false) if val.empty?

    val = val.get
    return invalid(m2, mth, 1, ERR, false) unless [true, false].include?(val)
    return val
  end

  id.downcase.include?("spandrel")
end

#square?(pts = nil) ⇒ Bool, false

Validates whether an OpenStudio polygon is a square (rectangular, 4x ~equal sides).

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

Returns:

  • (Bool)

    whether polygon is a square

  • (false)

    if invalid input (see logs)



3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
# File 'lib/osut/utils.rb', line 3515

def square?(pts = nil)
  d   = nil
  pts = poly(pts, false, false, false)
  return false if pts.empty?
  return false unless rectangular?(pts)

  getSegments(pts).each do |pt|
    l = (pt[1] - pt[0]).length
    d = l unless d
    return false unless l.round(2) == d.round(2)
  end

  true
end

#standardOpaqueLayers?(lc = nil) ⇒ Bool, false

Validates if every material in a layered construction is standard & opaque.

Parameters:

  • lc (OpenStudio::LayeredConstruction) (defaults to: nil)

    a layered construction

Returns:

  • (Bool)

    whether all layers are valid

  • (false)

    if invalid input (see logs)



898
899
900
901
902
903
904
905
906
907
# File 'lib/osut/utils.rb', line 898

def standardOpaqueLayers?(lc = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::LayeredConstruction
  return invalid("lc", mth, 1, DBG, false) unless lc.respond_to?(NS)
  return mismatch(lc.nameString, lc, cl, mth, DBG, false) unless lc.is_a?(cl)

  lc.layers.each { |m| return false if m.to_StandardOpaqueMaterial.empty? }

  true
end

#thickness(lc = nil) ⇒ Float, 0.0

Returns total (standard opaque) layered construction thickness (m).

Parameters:

  • lc (OpenStudio::LayeredConstruction) (defaults to: nil)

    a layered construction

Returns:

  • (Float)

    construction thickness

  • (0.0)

    if invalid input (see logs)



916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
# File 'lib/osut/utils.rb', line 916

def thickness(lc = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::LayeredConstruction
  return invalid("lc", mth, 1, DBG, 0.0) unless lc.respond_to?(NS)

  id = lc.nameString
  return mismatch(id, lc, cl, mth, DBG, 0.0) unless lc.is_a?(cl)

  ok = standardOpaqueLayers?(lc)
  log(ERR, "'#{id}' holds non-StandardOpaqueMaterial(s) (#{mth})")  unless ok
  return 0.0                                                        unless ok

  thickness = 0.0
  lc.layers.each { |m| thickness += m.thickness }

  thickness
end

#to_p3Dv(pts = nil) ⇒ OpenStudio::Point3dVector

Returns OpenStudio 3D points as an OpenStudio point vector, validating points in the process (if Array).

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    OpenStudio 3D points

Returns:

  • (OpenStudio::Point3dVector)

    3D vector (see logs if empty)



2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
# File 'lib/osut/utils.rb', line 2392

def to_p3Dv(pts = nil)
  mth = "OSut::#{__callee__}"
  cl1 = OpenStudio::Point3d
  cl2 = OpenStudio::Point3dVector
  cl3 = OpenStudio::Model::PlanarSurface
  cl4 = Array
  v   = OpenStudio::Point3dVector.new

  if pts.is_a?(cl1)
    v << pts
    return v
  end

  return pts if pts.is_a?(cl2)
  return pts.vertices if pts.is_a?(cl3)

  return mismatch("points", pts, cl1, mth, DBG, v) unless pts.is_a?(cl4)

  pts.each do |pt|
    return mismatch("point", pt, cl4, mth, DBG, v) unless pt.is_a?(cl1)
  end

  pts.each { |pt| v << OpenStudio::Point3d.new(pt.x, pt.y, pt.z) }

  v
end

#toToplit(spaces = [], opts = {}) ⇒ Array<OpenStudio::Model::Space>

Preselects ideal spaces to toplight, based on ‘addSkylights’ options and key building model geometry attributes. Can be called from within ‘addSkylights’ by setting :ration (opts key:value argument) to ‘true’ (‘false’ by default). Alternatively, the method can be called prior to ‘addSkylights’. The set of filters stems from previous rounds of ‘addSkylights’ stress testing. It is intended as an option to prune away less ideal candidate spaces (irregular, smaller) in favour of (larger) candidates (notably with more suitable roof geometries). This is key when dealing with attic and plenums, where ‘addSkylights’ seeks to add skylight wells (relying on roof cut-outs and leader lines). Another check/outcome is whether to prioritize skylight allocation in already sidelit spaces - opts may be reset to ‘true’.

Parameters:

  • spaces (Array<OpenStudio::Model::Space>) (defaults to: [])

    candidate(s) to toplight

  • opts (Hash) (defaults to: {})

    requested skylight attributes (same as ‘addSkylights’)

Options Hash (opts):

  • :size (#to_f) — default: 1.22m

    template skylight width/depth (min 0.4m)

Returns:

  • (Array<OpenStudio::Model::Space>)

    candidates (see logs if empty)



6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
# File 'lib/osut/utils.rb', line 6092

def toToplit(spaces = [], opts = {})
  mth  = "OSut::#{__callee__}"
  gap4 = 0.4  # minimum skylight 16" width/depth (excluding frame width)
  w    = 1.22 # default 48" x 48" skylight base
  w2   = w * w

  # Validate skylight size, if provided.
  if opts.key?(:size)
    if opts[:size].respond_to?(:to_f)
      w  = opts[:size].to_f
      w2 = w * w
      return invalid(size, mth, 0, ERR, []) if w.round(2) < gap4
    else
      return mismatch("size", opts[:size], Numeric, mth, DBG, [])
    end
  end

  # Accept single 'OpenStudio::Model::Space' (vs an array of spaces). Filter.
  #
  # Whether individual spaces are UNCONDITIONED (e.g. attics, unheated areas)
  # or flagged as NOT being part of the total floor area (e.g. unoccupied
  # plenums), should of course reflect actual design intentions. It's up to
  # modellers to correctly flag such cases - can't safely guess in lieu of
  # design/modelling team.
  #
  # A friendly reminder: 'addSkylights' should be called separately for
  # strictly SEMIHEATED spaces vs REGRIGERATED spaces vs all other CONDITIONED
  # spaces, as per 90.1 and NECB requirements.
  if spaces.respond_to?(:spaceType) || spaces.respond_to?(:to_a)
    spaces = spaces.respond_to?(:to_a) ? spaces.to_a : [spaces]
    spaces = spaces.select { |sp| sp.respond_to?(:spaceType) }
    spaces = spaces.select { |sp| sp.partofTotalFloorArea }
    spaces = spaces.reject { |sp| unconditioned?(sp) }
    spaces = spaces.reject { |sp| vestibule?(sp) }
    spaces = spaces.reject { |sp| getRoofs(sp).empty? }
    spaces = spaces.reject { |sp| sp.floorArea < 4 * w2 }
    spaces = spaces.sort_by(&:floorArea).reverse
    return empty("spaces", mth, WRN, 0) if spaces.empty?
  else
    return mismatch("spaces", spaces, Array, mth, DBG, 0)
  end

  # Unfenestrated spaces have no windows, glazed doors or skylights. By
  # default, 'addSkylights' will prioritize unfenestrated spaces (over all
  # existing sidelit ones) and maximize skylight sizes towards achieving the
  # required skylight area target. This concentrates skylights for instance in
  # typical (large) core spaces, vs (narrower) perimeter spaces. However, for
  # less conventional spatial layouts, this default approach can produce less
  # optimal skylight distributions. A balance is needed to prioritize large
  # unfenestrated spaces when appropriate on one hand, while excluding smaller
  # unfenestrated ones on the other. Here, exclusion is based on the average
  # floor area of spaces to toplight.
  fm2  = spaces.sum(&:floorArea)
  afm2 = fm2 / spaces.size

  unfen = spaces.reject { |sp| daylit?(sp) }.sort_by(&:floorArea).reverse

  # Target larger unfenestrated spaces, if sufficient in area.
  if unfen.empty?
    opts[:sidelit] = true
  else
    if spaces.size > unfen.size
      ufm2  = unfen.sum(&:floorArea)
      u0fm2 = unfen.first.floorArea

      if ufm2 > 0.33 * fm2 && u0fm2 > 3 * afm2
        unfen  = unfen.reject { |sp| sp.floorArea > 0.25 * afm2 }
        spaces = spaces.reject { |sp| unfen.include?(sp) }
      else
        opts[:sidelit] = true
      end
    end
  end

  espaces = {}
  rooms   = []
  toits   = []

  # Gather roof surfaces - possibly those of attics or plenums above.
  spaces.each do |sp|
    getRoofs(sp).each do |rf|
      espaces[sp] = {roofs: []} unless espaces.key?(sp)
      espaces[sp][:roofs] << rf unless espaces[sp][:roofs].include?(rf)
    end
  end

  # Priortize larger spaces.
  espaces = espaces.sort_by { |espace, _| espace.floorArea }.reverse

  # Prioritize larger roof surfaces.
  espaces.each do |_, datum|
    datum[:roofs] = datum[:roofs].sort_by(&:grossArea).reverse
  end

  # Single out largest roof in largest space, key when dealing with shared
  # attics or plenum roofs.
  espaces.each do |espace, datum|
    rfs = datum[:roofs].reject { |ruf| toits.include?(ruf) }
    next if rfs.empty?

    toits << rfs.sort { |ruf| ruf.grossArea }.reverse.first
    rooms << espace
  end

  log(INF, "No ideal toplit candidates (#{mth})") if rooms.empty?

  rooms
end

#transforms(group = nil) ⇒ Hash

Returns OpenStudio site/space transformation & rotation angle [0,2PI) rads.

Parameters:

  • group (OpenStudio::Model::PlanarSurfaceGroup) (defaults to: nil)

    a site or space object

Returns:

  • (Hash)

    t: (OpenStudio::Transformation), r: (Float)

  • (Hash)

    t: nil, r: nil if invalid input (see logs)



2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
# File 'lib/osut/utils.rb', line 2329

def transforms(group = nil)
  mth = "OSut::#{__callee__}"
  cl2 = OpenStudio::Model::PlanarSurfaceGroup
  res = { t: nil, r: nil }
  return invalid("group", mth, 2, DBG, res) unless group.respond_to?(NS)

  id  = group.nameString
  mdl = group.model
  return mismatch(id, group, cl2, mth, DBG, res) unless group.is_a?(cl2)

  res[:t] = group.siteTransformation
  res[:r] = group.directionofRelativeNorth + mdl.getBuilding.northAxis

  res
end

#triad?(pts = nil) ⇒ Bool, false

Determines if a set of 3D points if a valid triad.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

Returns:

  • (Bool)

    whether set is a valid triad (i.e. a trio of 3D points)

  • (false)

    if invalid input (see logs)



2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
# File 'lib/osut/utils.rb', line 2884

def triad?(pts = nil)
  pts = to_p3Dv(pts)
  return false     if pts.empty?
  return false unless pts.size == 3
  return false     if same?(pts[0], pts[1])
  return false     if same?(pts[0], pts[2])
  return false     if same?(pts[1], pts[2])

  true
end

#triadBox(pts = nil) ⇒ Set<OpenStudio::Point3D>

Generates a BLC box from a triad (3D points). Points must be unique and non-collinear.

Parameters:

  • a (Set<OpenStudio::Point3d>)

    triad (3D points)

Returns:

  • (Set<OpenStudio::Point3D>)

    a rectangular ULC box (see logs if empty)



4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
# File 'lib/osut/utils.rb', line 4027

def triadBox(pts = nil)
  mth = "OSut::#{__callee__}"
  bkp = OpenStudio::Point3dVector.new
  box = []
  pts = getNonCollinears(pts)
  return bkp if pts.empty?

  t   = xyz?(pts, :z) ? nil : OpenStudio::Transformation.alignFace(pts)
  pts = poly(pts, false, true, true, t) if t
  return bkp if pts.empty?
  return invalid("triad", mth, 1, ERR, bkp) unless pts.size == 3

  pts = to_p3Dv(pts.to_a.reverse) if clockwise?(pts)
  p0  = pts[0]
  p1  = pts[1]
  p2  = pts[2]

  # Cast p0 unto vertical plane defined by p1/p2.
  pp0 = verticalPlane(p1, p2).project(p0)
  v00 = p0  - pp0
  v11 = pp0 - p1
  v10 = p0  - p1
  v12 = p2  - p1

  # Reset p0 and/or p1 if obtuse or acute.
  if v12.dot(v10) < 0
    p0 = p1 + v00
  elsif v12.dot(v10) > 0
    if v11.length < v12.length
      p1 = pp0
    else
      p0 = p1 + v00
    end
  end

  p3 = p2 + v00

  box << OpenStudio::Point3d.new(p0.x, p0.y, p0.z)
  box << OpenStudio::Point3d.new(p1.x, p1.y, p1.z)
  box << OpenStudio::Point3d.new(p2.x, p2.y, p2.z)
  box << OpenStudio::Point3d.new(p3.x, p3.y, p3.z)
  box = getNonCollinears(box, 4)
  return bkp unless box.size == 4

  box = blc(box)
  return bkp unless rectangular?(box)

  box = to_p3Dv(t * box) if t

  box
end

#trueNormal(s = nil, r = 0) ⇒ OpenStudio::Vector3d?

Returns the site/true outward normal vector of a surface.

Parameters:

  • s (OpenStudio::Model::PlanarSurface) (defaults to: nil)

    a surface

  • r (#to_f) (defaults to: 0)

    a group/site rotation angle [0,2PI) radians

Returns:

  • (OpenStudio::Vector3d)

    true normal vector

  • (nil)

    if invalid input (see logs)



2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
# File 'lib/osut/utils.rb', line 2353

def trueNormal(s = nil, r = 0)
  mth = "TBD::#{__callee__}"
  cl  = OpenStudio::Model::PlanarSurface
  return mismatch("surface", s, cl, mth)   unless s.is_a?(cl)
  return invalid("rotation angle", mth, 2) unless r.respond_to?(:to_f)

  r = -r.to_f * Math::PI / 180.0
  vx = s.outwardNormal.x * Math.cos(r) - s.outwardNormal.y * Math.sin(r)
  vy = s.outwardNormal.x * Math.sin(r) + s.outwardNormal.y * Math.cos(r)
  vz = s.outwardNormal.z

  OpenStudio::Point3d.new(vx, vy, vz) - OpenStudio::Point3d.new(0, 0, 0)
end

#ulc(pts = nil) ⇒ OpenStudio::Point3dVector

Returns OpenStudio 3D points (min 3x) conforming to an UpperLeftCorner (ULC) convention. Points Z-axis values must be ~= 0. Points are returned counterclockwise.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

Returns:

  • (OpenStudio::Point3dVector)

    ULC points (see logs if empty)



3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
# File 'lib/osut/utils.rb', line 3092

def ulc(pts = nil)
  mth = "OSut::#{__callee__}"
  v   = OpenStudio::Point3dVector.new
  pts = to_p3Dv(pts).to_a
  return invalid("points (3+)",      mth, 1, DBG, v)     if pts.size < 3
  return invalid("points (aligned)", mth, 1, DBG, v) unless xyz?(pts, :z)

  # Ensure counterclockwise sequence.
  pts  = pts.reverse if clockwise?(pts)
  minX = pts.min_by(&:x).x
  i0   = nearest(pts)
  p0   = pts[i0]

  pts_x = pts.select { |pt| pt.x.round(2) == minX.round(2) }.reverse

  p1 = pts_x.max_by { |pt| (pt - p0).length }
  i1 = pts.index(p1)

  to_p3Dv(pts.rotate(i1))
end

#unconditioned?(space = nil) ⇒ Bool, false

Validates if a space is UNCONDITIONED.

Parameters:

  • space (OpenStudio::Model::Space) (defaults to: nil)

    a space

Returns:

  • (Bool)

    whether space is considered UNCONDITIONED

  • (false)

    if invalid input (see logs)



2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
# File 'lib/osut/utils.rb', line 2082

def unconditioned?(space = nil)
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Space
  return mismatch("space", space, cl, mth, DBG, false) unless space.is_a?(cl)

  ok = false
  ok = setpoints(space)[:heating].nil? && setpoints(space)[:cooling].nil?

  ok
end

#verticalPlane(p1 = nil, p2 = nil) ⇒ OpenStudio::Plane?

Returns a vertical 3D plane from 2x 3D points, right-hand rule. Input points are considered last 2 (of 3) points forming the plane; the first point is assumed zenithal. Input points cannot align vertically.

Parameters:

  • p1 (OpenStudio::Point3d) (defaults to: nil)

    1st 3D point of a line segment

  • p2 (OpenStudio::Point3d) (defaults to: nil)

    2nd 3D point of a line segment

Returns:

  • (OpenStudio::Plane)

    3D plane

  • (nil)

    if invalid input (see logs)



2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
# File 'lib/osut/utils.rb', line 2754

def verticalPlane(p1 = nil, p2 = nil)
  mth = "OSut::#{__callee__}"
  return mismatch("point 1", p1, cl, mth) unless p1.is_a?(OpenStudio::Point3d)
  return mismatch("point 2", p2, cl, mth) unless p2.is_a?(OpenStudio::Point3d)

  if (p1.x - p2.x).abs < TOL && (p1.y - p2.y).abs < TOL
    return invalid("vertically aligned points", mth)
  end

  zenith = OpenStudio::Point3d.new(p1.x, p1.y, (p2 - p1).length)
  points = OpenStudio::Point3dVector.new
  points << zenith
  points << p1
  points << p2

  OpenStudio::Plane.new(points)
end

#vestibule?(space = nil) ⇒ Bool, false

Validates whether space is a vestibule.

Parameters:

  • space (OpenStudio::Model::Space) (defaults to: nil)

    a space

Returns:

  • (Bool)

    whether space is considered a vestibule

  • (false)

    if invalid input (see logs)



1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
# File 'lib/osut/utils.rb', line 1812

def vestibule?(space = nil)
  # INFO: OpenStudio-Standards' "thermal_zone_vestibule" criteria:
  #   - zones less than 200ft2; AND
  #   - having infiltration using Design Flow Rate
  #
  #   github.com/NREL/openstudio-standards/blob/
  #   86bcd026a20001d903cc613bed6d63e94b14b142/lib/openstudio-standards/
  #   standards/Standards.ThermalZone.rb#L1264
  #
  # This (unused) OpenStudio-Standards method likely needs revision; it would
  # return "false" if the thermal zone area were less than 200ft2. Not sure
  # which edition of 90.1 relies on a 200ft2 threshold (2010?); 90.1 2016
  # doesn't. Yet even fixed, the method would nonetheless misidentify as
  # "vestibule" a small space along an exterior wall, such as a semiheated
  # storage space.
  #
  # The code below is intended as a simple short-term solution, basically
  # relying on AdditionalProperties, or (if missing) a "vestibule" substring
  # within a space's spaceType name (or the latter's standardsSpaceType).
  #
  # Alternatively, some future method could infer its status as a vestibule
  # based on a few basic features (common to all vintages):
  #   - 1x+ outdoor-facing wall(s) holding 1x+ door(s)
  #   - adjacent to 1x+ 'occupied' conditioned space(s)
  #   - ideally, 1x+ door(s) between vestibule and 1x+ such adjacent space(s)
  #
  # An additional method parameter (i.e. std = :necb) could be added to
  # ensure supplementary Standard-specific checks, e.g. maximum floor area,
  # minimum distance between doors.
  #
  # Finally, an entirely separate method could be developed to first identify
  # whether "building entrances" (a defined term in 90.1) actually require
  # vestibules as per specific code requirements. Food for thought.
  mth = "OSut::#{__callee__}"
  cl  = OpenStudio::Model::Space
  return mismatch("space", space, cl, mth, DBG, false) unless space.is_a?(cl)

  id  = space.nameString
  m1  = "#{id}:vestibule"
  m2  = "#{id}:vestibule:boolean"

  if space.additionalProperties.hasFeature("vestibule")
    val = space.additionalProperties.getFeatureAsBoolean("vestibule")
    return invalid(m1, mth, 1, ERR, false) if val.empty?

    val = val.get
    return invalid(m2, mth, 1, ERR, false) unless [true, false].include?(val)
    return val
  end

  unless space.spaceType.empty?
    type = space.spaceType.get
    return false if type.nameString.downcase.include?("plenum")
    return true  if type.nameString.downcase.include?("vestibule")

    unless type.standardsSpaceType.empty?
      type = type.standardsSpaceType.get.downcase
      return false if type.include?("plenum")
      return true  if type.include?("vestibule")
    end
  end

  false
end

#width(pts = nil) ⇒ Float, 0.0

Returns ‘width’ of a set of OpenStudio 3D points.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    3D points

Returns:

  • (Float)

    width along X-axis, once re/aligned

  • (0.0)

    if invalid inputs



2697
2698
2699
2700
2701
2702
# File 'lib/osut/utils.rb', line 2697

def width(pts = nil)
  pts = to_p3Dv(pts)
  return 0 if pts.size < 2

  pts.max_by(&:x).x - pts.min_by(&:x).x
end

#xyz?(pts = nil, axs = :z, val = 0) ⇒ Bool, false

Validates whether 3D points share X, Y or Z coordinates.

Parameters:

  • pts (Set<OpenStudio::Point3d>) (defaults to: nil)

    OpenStudio 3D points

  • axs (Symbol) (defaults to: :z)

    if potentially along :x, :y or :z axis

  • val (Numeric) (defaults to: 0)

    axis value

Returns:

  • (Bool)

    if points share X, Y or Z coordinates

  • (false)

    if invalid input (see logs)



2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
# File 'lib/osut/utils.rb', line 2647

def xyz?(pts = nil, axs = :z, val = 0)
  mth = "OSut::#{__callee__}"
  pts = to_p3Dv(pts)
  ok1 = val.respond_to?(:to_f)
  ok2 = [:x, :y, :z].include?(axs)
  return false if pts.empty?
  return mismatch("val", val, Numeric, mth,    DBG, false) unless ok1
  return invalid("axis",               mth, 2, DBG, false) unless ok2

  val = val.to_f

  case axs
  when :x
    pts.each { |pt| return false if (pt.x - val).abs > TOL }
  when :y
    pts.each { |pt| return false if (pt.y - val).abs > TOL }
  else
    pts.each { |pt| return false if (pt.z - val).abs > TOL }
  end

  true
end