repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
bolasblack/programr
example.rb
# coding: utf-8 require 'bundler' Bundler.setup :default require 'programr' robot = ProgramR::Facade.new robot.environment.readonly_tags_file = 'spec/data/readOnlyTags.yaml' robot.learn ['spec/data'] robot.learn <<-AIML <category> <pattern>Hello</pattern> <template>World</template> </category> AIML while true print '>> ' s = STDIN.gets.chomp reaction = robot.get_reaction(s) STDOUT.puts "<< #{reaction}" end
bolasblack/programr
lib/programr.rb
require 'yaml' require 'rexml/parsers/sax2parser' require 'active_support/core_ext/string' require "programr/version" require 'programr/graphmaster' require 'programr/graph_node' require 'programr/environment' require 'programr/aiml_elements' require 'programr/aiml_parser' require 'programr/history' require 'programr/facade' module ProgramR module GraphMark THAT = '<that>' TOPIC = '<topic>' ALL = [THAT, TOPIC] end end
bolasblack/programr
spec/aiml_elements_spec.rb
# coding: utf-8 describe ProgramR::ReplaceTag do let(:robot) { ProgramR::Facade.new } before do end it "can custom gender map" do robot.learn <<-AIML <category> <pattern>gender test</pattern> <template> <gender>他和她</gender> </template> </category> AIML ProgramR::Gender::Map['他和她'] = proc { '她和他' } expect(robot.get_reaction 'gender test').to eq '她和他' end end
bolasblack/programr
spec/graph_node_spec.rb
require File.join(File.dirname(__FILE__), './utils/fake_graphmaster') def parse_category category_aiml history = ProgramR::History.new environment = ProgramR::Environment.new history fake_graphmaster = FakeGraphmaster.new parser = ProgramR::AimlParser.new fake_graphmaster, environment, history parser.parse category_aiml fake_graphmaster.learned.first end def generate_aiml template <<-AIML <category> <pattern>test</pattern> <template>#{template}</template> </category> AIML end describe ProgramR::GraphNode do let(:node) { ProgramR::GraphNode.new } describe '#learn' do it 'create children for each word in path' do node.learn parse_category(generate_aiml 'success'), ['a', 'b'] expect(node.children['a'].children['b'].template.value).to eq ['success'] end end describe '#get_template' do shared_examples '#get_template specs' do |opts| it 'support full word matcher' do node.learn parse_category(generate_aiml 'success'), 'abcdefg'.split('').concat(opts[:path_suffix]) matched = [] expect(node.get_template(opts[:input_path], matched).value).to eq ['success'] expect(matched).to eq [] + opts[:matched_suffix] end it 'support star matcher' do node.learn parse_category(generate_aiml 'success'), 'a*g'.split('').concat(opts[:path_suffix]) matched = [] expect(node.get_template(opts[:input_path], matched).value).to eq ['success'] expect(matched).to eq ['<star>', 'b', 'c', 'd', 'e', 'f'] + opts[:matched_suffix] end it 'support multiple star matcher' do node.learn parse_category(generate_aiml 'success'), 'a*cd*g'.split('').concat(opts[:path_suffix]) matched = [] expect(node.get_template(opts[:input_path], matched).value).to eq ['success'] expect(matched).to eq ['<star>', 'b', '<star>', 'e', 'f'] + opts[:matched_suffix] end it 'try exact word matcher first, then try star matcher if failed' do node.learn parse_category(generate_aiml 'success'), 'a*g'.split('').concat(opts[:path_suffix]) node.learn parse_category(generate_aiml 'failed'), 'abk*g'.split('').concat(opts[:path_suffix]) matched = [] expect(node.get_template(opts[:input_path], matched).value).to eq ['success'] expect(matched).to eq ['<star>', 'b', 'c', 'd', 'e', 'f'] + opts[:matched_suffix] end it 'make star matcher match at least one word' do node.learn parse_category(generate_aiml 'success'), 'a******g'.split('').concat(opts[:path_suffix]) matched = [] expect(node.get_template opts[:input_path], matched).to be_nil expect(matched).to eq [] end it 'make star matcher non-greedy' do node.learn parse_category(generate_aiml 'success'), 'a**g'.split('').concat(opts[:path_suffix]) matched = [] expect(node.get_template(opts[:input_path], matched).value).to eq ['success'] expect(matched).to eq ['<star>', 'b', '<star>', 'c', 'd', 'e', 'f'] + opts[:matched_suffix] end end context 'without that and topic' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'undef', ProgramR::GraphMark::TOPIC, 'undef'], path_suffix: [], matched_suffix: [] ) end context 'with that' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'c', 'd', 'g', ProgramR::GraphMark::TOPIC, 'undef'], path_suffix: [ProgramR::GraphMark::THAT, 'c', 'd', 'g'], matched_suffix: [] ) end context 'with star existed that' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'c', 'd', 'g', ProgramR::GraphMark::TOPIC, 'undef'], path_suffix: [ProgramR::GraphMark::THAT, 'c', '*', 'g'], matched_suffix: [ProgramR::GraphMark::THAT, '<star>', 'd'] ) end context 'with multiple star existed that' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'c', 'd', 'f', 'e', 'g', ProgramR::GraphMark::TOPIC, 'undef'], path_suffix: [ProgramR::GraphMark::THAT, 'c', '*', '*', 'g'], matched_suffix: [ProgramR::GraphMark::THAT, '<star>', 'd', '<star>', 'f', 'e'] ) end context 'with topic' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'undef', ProgramR::GraphMark::TOPIC, 'c', 'd', 'g'], path_suffix: [ProgramR::GraphMark::TOPIC, 'c', 'd', 'g'], matched_suffix: [] ) end context 'with star existed topic' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'undef', ProgramR::GraphMark::TOPIC, 'c', 'd', 'g'], path_suffix: [ProgramR::GraphMark::TOPIC, 'c', '*', 'g'], matched_suffix: [ProgramR::GraphMark::TOPIC, '<star>', 'd'] ) end context 'with multiple star existed topic' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'undef', ProgramR::GraphMark::TOPIC, 'c', 'd', 'f', 'e', 'g'], path_suffix: [ProgramR::GraphMark::TOPIC, 'c', '*', '*', 'g'], matched_suffix: [ProgramR::GraphMark::TOPIC, '<star>', 'd', '<star>', 'f', 'e'] ) end context 'with that and topic' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'c', 'd', 'g', ProgramR::GraphMark::TOPIC, 'c', 'd', 'g'], path_suffix: [ProgramR::GraphMark::THAT, 'c', 'd', 'g', ProgramR::GraphMark::TOPIC, 'c', 'd', 'g'], matched_suffix: [] ) end context 'with star existed that and topic' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'c', 'd', 'g', ProgramR::GraphMark::TOPIC, 'c', 'd', 'g'], path_suffix: [ProgramR::GraphMark::THAT, 'c', '*', 'g', ProgramR::GraphMark::TOPIC, 'c', '*', 'g'], matched_suffix: [ProgramR::GraphMark::THAT, '<star>', 'd', ProgramR::GraphMark::TOPIC, '<star>', 'd'] ) end context 'with multiple star existed that and topic' do include_examples( '#get_template specs', input_path: ['a', 'b', 'c', 'd', 'e', 'f', 'g', ProgramR::GraphMark::THAT, 'c', 'd', 'f', 'e', 'g', ProgramR::GraphMark::TOPIC, 'c', 'd', 'f', 'e', 'g'], path_suffix: [ProgramR::GraphMark::THAT, 'c', '*', '*', 'g', ProgramR::GraphMark::TOPIC, 'c', '*', '*', 'g'], matched_suffix: [ProgramR::GraphMark::THAT, '<star>', 'd', '<star>', 'f', 'e', ProgramR::GraphMark::TOPIC, '<star>', 'd', '<star>', 'f', 'e'] ) end end end
bolasblack/programr
spec/graphmaster_spec.rb
<filename>spec/graphmaster_spec.rb # coding: utf-8 require File.join(File.dirname(__FILE__), './utils/fake_graphmaster') describe ProgramR::Graphmaster do aiml = <<-AIML <category> <pattern>test</pattern> <template>success</template> </category> AIML let(:history) { ProgramR::History.new } let(:graphmaster) { ProgramR::Graphmaster.new } let(:environment) { ProgramR::Environment.new history } def response graphmaster.get_reaction 'TEST', 'default', 'undef', [] end describe '#learn' do let(:parsed_category) do fake_graphmaster = FakeGraphmaster.new parser = ProgramR::AimlParser.new fake_graphmaster, environment, history parser.parse aiml fake_graphmaster.learned.first end it "learn category" do graphmaster.learn parsed_category expect(response).to eq ['success'] end end describe '#reset' do before do parser = ProgramR::AimlParser.new graphmaster, environment, history parser.parse aiml end it "reset the brain of graphmaster" do expect(response).to eq ['success'] graphmaster.reset expect(response).to eq [] end end describe '#register_segmenter' do it 'split input stimula' do class FakeNode attr_reader :last_path def get_template path, starGreedy @last_path = path ProgramR::Template.new end end fakeNode = FakeNode.new graphmaster.register_segmenter(:zh) do |segments| segments.map{ |segment| segment.split '' }.flatten end graphmaster.instance_eval { @graph = fakeNode } input = '你好,这是一个测试' graphmaster.get_reaction input, [], [], [] expect(fakeNode.last_path[0, input.length]).to eq input.split '' end it 'split pattern text in aiml when language matched' do class FakeNode attr_reader :last_path def learn category, path @last_path = path end end fakeNode = FakeNode.new graphmaster.register_segmenter(:zh) do |segments| segments.map{ |segment| segment.split '' }.flatten end graphmaster.instance_eval { @graph = fakeNode } pattern = '你好,这是一个测试' cn_category = ProgramR::Category.new cn_category.language = :zh cn_category.add_pattern pattern cn_category.template = ProgramR::Template.new cn_category.template.append 'hello world' en_category = ProgramR::Category.new en_category.language = :en en_category.add_pattern pattern en_category.template = ProgramR::Template.new en_category.template.append 'hello world' graphmaster.learn cn_category expect(fakeNode.last_path[0, pattern.length]).to eq pattern.split '' graphmaster.learn en_category expect(fakeNode.last_path[0, 1]).to eq [pattern] end end end
chausovSurfStudio/TextFieldsCatalog
TextFieldsCatalog.podspec
Pod::Spec.new do |s| s.name = "TextFieldsCatalog" s.version = "0.17.0" s.summary = "This is catalog of various input field with great opportunities for validation and formatting." s.homepage = "https://github.com/chausovSurfStudio/TextFieldsCatalog" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "<NAME>" => "<EMAIL>" } s.ios.deployment_target = "10.0" s.swift_version = '5.0' s.source = { :git => "https://github.com/chausovSurfStudio/TextFieldsCatalog.git", :tag => "#{s.version}" } s.source_files = 'TextFieldsCatalog/**/*.{swift,xib,strings}' s.resource_bundles = { 'TextFieldsCatalog' => ['TextFieldsCatalog/Resources/Images/*.{png}'] } s.framework = "UIKit" s.dependency "InputMask", '6.0.0' end
amckinnell/callgraphy
lib/callgraphy/definition.rb
module Callgraphy # Exposes a DSL to describe call graphs for a target class. # class Definition attr_reader :registry def self.register(&block) definition = Definition.new(Registry.new) definition.instance_eval(&block) definition.registry end def initialize(registry) @registry = registry end def methods_to_graph(method_scope, calls = {}) validate_scope(method_scope, :public, :private) register_methods_to_graph(method_scope, calls) end def constants_to_graph(constant_scope, calls = {}) validate_scope(constant_scope, :callers, :dependencies) register_constants_to_graph(constant_scope, calls) end private def register_methods_to_graph(method_scope, calls) register_calls(calls) do |caller, _callees| register_method(method_scope, caller) end end def register_constants_to_graph(constant_scope, calls) register_calls(calls) do |caller, callees| register_constants(constant_scope, caller, callees) end end def register_constants(constant_scope, caller, callees) constants = constant_scope == :callers ? caller : callees register_constant(constant_scope, constants) end def register_calls(calls) calls.each do |caller, callees| yield(caller, callees) register_each_call(caller, callees) end end def register_each_call(caller, callees) callees.each { |callee| registry.register_call(caller, callee) } end def register_method(method_scope, caller) registry.register_method(method_scope, caller) end def register_constant(constant_scope, constants) Array(constants).each { |constant| registry.register_constant(constant_scope, constant) } end def validate_scope(scope, *valid_scopes) raise "Invalid scope: #{scope}" unless valid_scopes.include?(scope) end end end
amckinnell/callgraphy
sample/rule_service_graph.rb
<reponame>amckinnell/callgraphy require "callgraphy" Callgraphy.draw target: "rule_service" do methods_to_graph :public, :generate_lot_code => [:generate_lot_code_fragments, :reference_value_for], :interpret_mfg_date_from_lot => [:earliest_date, :interpret_from] methods_to_graph :private, :earliest_date => [:validate_length], :generate_lot_code_fragments => [], :interpret_from => [:validate_length], :reference_value_for => [], :validate_length => [] constants_to_graph :callers, :code_generation_service => [:generate_lot_code, :interpret_mfg_date_from_lot] constants_to_graph :dependencies, :earliest_date => [:earliest_date_interpreter] end
amckinnell/callgraphy
lib/callgraphy/utils.rb
module Callgraphy # Utility methods. # module Utils def self.pascal_case(snake_case) snake_case.split("_").map(&:capitalize).join end end end
amckinnell/callgraphy
spec/callgraphy_spec.rb
require "spec_helper" module Callgraphy RSpec.describe Callgraphy do let(:registry) { instance_double(Registry) } describe ".draw" do it "invokes collaborators" do expect(Definition).to receive(:register).and_return(registry) expect(CallGraph).to receive(:draw).with("target", "output", registry) Callgraphy.draw(target: "target", output_directory: "output") end it "default the output directory to the current directory" do expect(Definition).to receive(:register).and_return(registry) expect(CallGraph).to receive(:draw).with("target", ".", registry) Callgraphy.draw(target: "target") end end it "has a version number" do expect(Callgraphy::VERSION).not_to be_nil end end end
amckinnell/callgraphy
spec/callgraphy/definition_spec.rb
<reponame>amckinnell/callgraphy require "ruby-graphviz" require "callgraphy/definition" module Callgraphy RSpec.describe Definition do describe "#define" do it "saves definition in registry" do registry = Definition.register do methods_to_graph :public, m_1: [:m_2] methods_to_graph :private, m_2: [] constants_to_graph :callers, c_1: [:m_1] constants_to_graph :dependencies, m_2: [:c_2] end expect(registry).to have_attributes( all_public_methods: ["m_1"], all_private_methods: ["m_2"], all_callers: ["c_1"], all_dependencies: ["c_2"], all_calls: [["c_1", "m_1"], ["m_1", "m_2"], ["m_2", "c_2"]] ) end it "fails for an unknown method scope" do expect do Definition.register do methods_to_graph :bad_scope, m_1: [] end end.to raise_error(RuntimeError, /Invalid scope: bad_scope/) end it "fails for an unknown constant scope" do expect do Definition.register do constants_to_graph :bad_scope, c_1: [:m_1] end end.to raise_error(RuntimeError, /Invalid scope: bad_scope/) end end end end
amckinnell/callgraphy
spec/callgraphy/registry_spec.rb
<filename>spec/callgraphy/registry_spec.rb require "callgraphy/registry" module Callgraphy RSpec.describe Registry do subject(:registry) { Registry.new } it "registers public methods" do registry.register_method(:public, :m_1) registry.register_method(:public, :m_2) expect(registry).to have_attributes( all_public_methods: ["m_1", "m_2"], all_private_methods: [] ) end it "registers private methods" do registry.register_method(:private, :m_1) expect(registry).to have_attributes( all_public_methods: [], all_private_methods: ["m_1"] ) end it "handles registration of duplicate methods" do registry.register_method(:private, :m_1) registry.register_method(:private, :m_1) expect(registry).to have_attributes( all_public_methods: [], all_private_methods: ["m_1"] ) end it "sorts registered methods" do registry.register_method(:public, :m_2) registry.register_method(:public, :m_4) registry.register_method(:public, :m_1) registry.register_method(:public, :m_3) expect(subject).to have_attributes( all_public_methods: ["m_1", "m_2", "m_3", "m_4"], all_private_methods: [] ) end it "registers calls" do registry.register_call(:m_1, :m_2) expect(subject).to have_attributes( all_calls: [["m_1", "m_2"]] ) end it "registers callers constants" do registry.register_constant(:callers, :c_1) expect(subject).to have_attributes( all_callers: ["c_1"] ) end it "registers dependencies constants" do registry.register_constant(:dependencies, :c_2) expect(subject).to have_attributes( all_dependencies: ["c_2"] ) end end end
amckinnell/callgraphy
spec/callgraphy/utils_spec.rb
require "callgraphy/utils" module Callgraphy RSpec.describe Utils do describe "#pascal_case" do it "converts case" do expect(Utils.pascal_case("some_name")).to eq("SomeName") end end end end
amckinnell/callgraphy
lib/callgraphy/call_graph.rb
<filename>lib/callgraphy/call_graph.rb require "ruby-graphviz" module Callgraphy # Knows how to graph the target class call graph given the specified registry. # class CallGraph NODE_OPTIONS = { public: { style: "filled", fillcolor: "palegreen" }, private: {}, callers: { style: "filled", fillcolor: "lightblue" }, dependencies: { style: "filled", fillcolor: "lightcoral" } } attr_reader :registry def self.draw(target, output_directory, registry) new(target, output_directory, registry).draw end def initialize(target, output_directory, registry) @target = target @output_directory = output_directory @registry = registry @nodes = {} end def draw add_methods add_constants add_calls generate_graph end private def add_methods registry.all_public_methods.each { |name| add_method(name, :public) } registry.all_private_methods.each { |name| add_method(name, :private) } end def add_constants registry.all_callers.each { |name| add_constant(name, :callers) } registry.all_dependencies.each { |name| add_constant(name, :dependencies) } end def add_method(method_name, node_type) add_node(method_name, NODE_OPTIONS[node_type]) end def add_constant(constant_name, node_type) add_node(constant_name, NODE_OPTIONS[node_type].merge(label: Utils.pascal_case(constant_name))) end def add_node(node_name, options) @nodes[node_name] = graphviz.add_nodes(node_name, options.dup) end def add_calls registry.all_calls.each { |caller, callee| add_call(caller, callee) } end def add_call(caller, callee) graphviz.add_edges(@nodes.fetch(caller), @nodes.fetch(callee)) end def generate_graph graphviz.output(png: graph_filename) end def graph_filename File.join(@output_directory, "#{@target}.png") end def graphviz @graphviz ||= GraphViz.new(:G, type: :digraph, labelloc: "b", label: "Target class is #{Utils.pascal_case(@target)}") end end end
amckinnell/callgraphy
spec/callgraphy/call_graph_spec.rb
require "callgraphy/call_graph" module Callgraphy RSpec.describe CallGraph do let(:registry) { instance_double(Registry) } it "draws a graph" do configure_registry( public_methods: ["m_1"], private_methods: ["m_2", "m_3"], callers: ["c_1"], dependencies: ["c_2"], calls: [["m_1", "m_2"], ["m_2", "m_3"], ["c_1", "m_1"], ["m_3", "c_2"]] ) expect(GraphViz).to receive(:new) .with(:G, type: :digraph, labelloc: "b", label: "Target class is Target") .and_call_original expect_graphviz_to_add_nodes_for( ["m_1", CallGraph::NODE_OPTIONS[:public]], ["m_2", CallGraph::NODE_OPTIONS[:private]], ["m_3", CallGraph::NODE_OPTIONS[:private]], ["c_1", CallGraph::NODE_OPTIONS[:callers].merge(label: "C1")], ["c_2", CallGraph::NODE_OPTIONS[:dependencies].merge(label: "C2")] ) expect_any_instance_of(GraphViz).to receive(:add_edges).exactly(4).and_call_original expect_any_instance_of(GraphViz).to receive(:output).with(png: "output_directory/target.png") CallGraph.draw("target", "output_directory", registry) end private def configure_registry(public_methods:, private_methods:, callers:, dependencies:, calls:) allow(registry).to receive(:all_public_methods).and_return(public_methods) allow(registry).to receive(:all_private_methods).and_return(private_methods) allow(registry).to receive(:all_calls).and_return(calls) allow(registry).to receive(:all_callers).and_return(callers) allow(registry).to receive(:all_dependencies).and_return(dependencies) end def expect_graphviz_to_add_nodes_for(*add_nodes_arguments) add_nodes_arguments.each do |node_name, node_opts| expect_any_instance_of(GraphViz).to receive(:add_nodes).with(node_name, node_opts).and_call_original end end end end
amckinnell/callgraphy
callgraphy.gemspec
<reponame>amckinnell/callgraphy lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "callgraphy/version" Gem::Specification.new do |spec| spec.name = "callgraphy" spec.version = Callgraphy::VERSION spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = "A command line tool for creating a call graph for a target class." spec.homepage = "https://github.com/amckinnell/callgraphy" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.required_ruby_version = ">= 2.3" spec.add_runtime_dependency "ruby-graphviz", ">= 1.2.0" spec.add_development_dependency "bundler", ">= 1.16.0" spec.add_development_dependency "rake", ">= 12.0.0" spec.add_development_dependency "rspec", ">= 3.7.0" spec.add_development_dependency "rubocop", ">= 0.52.1" spec.add_development_dependency "simplecov", ">= 0.15.1" end
amckinnell/callgraphy
lib/callgraphy/registry.rb
<gh_stars>0 module Callgraphy # Records the information that describes a call graph. # class Registry def initialize @registry = { public: [], private: [], callers: [], dependencies: [], calls: [] } end def register_method(scope, caller) @registry.fetch(scope).push(caller.to_s) end alias register_constant register_method def register_call(caller, callee) @registry.fetch(:calls).push([caller.to_s, callee.to_s]) end def all_public_methods normalized :public end def all_private_methods normalized :private end def all_calls normalized :calls end def all_callers normalized :callers end def all_dependencies normalized :dependencies end private def normalized(category) @registry.fetch(category).sort.uniq end end end
amckinnell/callgraphy
lib/callgraphy.rb
require "callgraphy/call_graph" require "callgraphy/definition" require "callgraphy/registry" require "callgraphy/utils" require "callgraphy/version" # Provides a DSL for creating call graphs for a target class. # module Callgraphy def self.draw(target:, output_directory: ".", &block) CallGraph.draw(target, output_directory, Definition.register(&block)) end end
amckinnell/callgraphy
spec/spec_helper.rb
# Right at the top so we don't miss any opportunities to track coverage. require "simplecov" SimpleCov.start do add_filter "/spec/" end $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) require "callgraphy"
andrewkww/shopify_app
lib/shopify_app/version.rb
<reponame>andrewkww/shopify_app<filename>lib/shopify_app/version.rb # frozen_string_literal: true module ShopifyApp VERSION = '13.0.1' end
andrewkww/shopify_app
lib/shopify_app/engine.rb
# frozen_string_literal: true module ShopifyApp class Engine < Rails::Engine engine_name 'shopify_app' isolate_namespace ShopifyApp initializer "shopify_app.assets.precompile" do |app| app.config.assets.precompile += %w[ shopify_app/redirect.js shopify_app/top_level.js shopify_app/enable_cookies.js shopify_app/request_storage_access.js storage_access.svg ] end initializer "shopify_app.middleware" do |app| app.config.middleware.insert_after(::Rack::Runtime, ShopifyApp::SameSiteCookieMiddleware) end end end
andrewkww/shopify_app
lib/shopify_app/session/jwt.rb
# frozen_string_literal: true module ShopifyApp class JWT def initialize(token) @token = token set_payload end def shopify_domain payload && dest_host end def shopify_user_id payload && payload['sub'] end private def payload return unless @payload return unless dest_host return unless dest_host == iss_host return unless @payload['aud'] == ShopifyApp.configuration.api_key @payload end def set_payload @payload, _ = parse_token_data(ShopifyApp.configuration.secret) configuration_old_secret = @payload && ShopifyApp.configuration @payload, _ = parse_token_data(ShopifyApp.configuration.old_secret) unless configuration_old_secret end def parse_token_data(secret) ::JWT.decode(@token, secret, true, { algorithm: 'HS256' }) rescue ::JWT::DecodeError, ::JWT::VerificationError, ::JWT::ExpiredSignature, ::JWT::ImmatureSignature nil end def dest_host @payload && ShopifyApp::Utils.sanitize_shop_domain(@payload['dest']) end def iss_host @payload && ShopifyApp::Utils.sanitize_shop_domain(@payload['iss']) end end end
andrewkww/shopify_app
lib/shopify_app/test_helpers/all.rb
<reponame>andrewkww/shopify_app require 'shopify_app/test_helpers/webhook_verification_helper'
andrewkww/shopify_app
test/shopify_app/session/jwt_test.rb
<gh_stars>0 # frozen_string_literal: true require 'test_helper' module ShopifyApp class JWTTest < ActiveSupport::TestCase TEST_SHOPIFY_DOMAIN = 'https://test.myshopify.io' TEST_SANITIZED_SHOPIFY_DOMAIN = 'test.myshopify.io' TEST_USER_ID = 'test-user' setup do ShopifyApp.configuration.api_key = 'api_key' ShopifyApp.configuration.secret = 'secret' ShopifyApp.configuration.old_secret = 'old_secret' ShopifyApp.configuration.myshopify_domain = 'myshopify.io' end test "#shopify_domain and #shopify_user_id are returned from jwt payload" do p = payload jwt = JWT.new(token(p)) assert_equal TEST_SANITIZED_SHOPIFY_DOMAIN, jwt.shopify_domain assert_equal TEST_USER_ID, jwt.shopify_user_id end test "#shopify_domain and #shopify_user_id are returned using the old secret" do p = payload t = ::JWT.encode(p, ShopifyApp.configuration.old_secret, 'HS256') jwt = JWT.new(t) assert_equal TEST_SANITIZED_SHOPIFY_DOMAIN, jwt.shopify_domain assert_equal TEST_USER_ID, jwt.shopify_user_id end test "shopify_domain and shopify_user_id are nil if the jwt is invalid" do jwt = JWT.new('token') assert_nil jwt.shopify_domain assert_nil jwt.shopify_user_id end test "#shopify_domain and #shopify_user_id are nil if the jwt is unsigned" do p = payload t = ::JWT.encode(p, nil, 'none') jwt = JWT.new(t) assert_nil jwt.shopify_domain assert_nil jwt.shopify_user_id end test "#shopify_domain and #shopify_user_id are nil if the signature is bad" do p = payload t = ::JWT.encode(p, 'bad', 'HS256') jwt = JWT.new(t) assert_nil jwt.shopify_domain assert_nil jwt.shopify_user_id end test "#shopify_domain and #shopify_user_id are nil if 'aud' claim doesn't match api_key" do ShopifyApp.configuration.api_key = 'other_key' p = payload jwt = JWT.new(token(p)) assert_nil jwt.shopify_domain assert_nil jwt.shopify_user_id end test "#shopify_domain and #shopify_user_id are nil if 'exp' claim is in the past" do p = payload(exp: 1.day.ago) jwt = JWT.new(token(p)) assert_nil jwt.shopify_domain assert_nil jwt.shopify_user_id end test "#shopify_domain and #shopify_user_id are nil if 'nbf' claim is in the future" do p = payload(nbf: 1.day.from_now) jwt = JWT.new(token(p)) assert_nil jwt.shopify_domain assert_nil jwt.shopify_user_id end test "#shopify_domain and #shopify_user_id are nil if `dest` is not a valid shopify domain" do p = payload(dest: 'https://example.com') jwt = JWT.new(token(p)) assert_nil jwt.shopify_domain assert_nil jwt.shopify_user_id end test "#shopify_domain and #shopify_user_id are nil if `iss` host doesn't match `dest` host" do p = payload(dest: 'https://other.myshopify.io') jwt = JWT.new(token(p)) assert_nil jwt.shopify_domain assert_nil jwt.shopify_user_id end test "#shopify_user_id returns nil if `sub` does not exist" do p = payload(sub: nil) jwt = JWT.new(token(p)) assert_nil jwt.shopify_user_id assert_equal TEST_SANITIZED_SHOPIFY_DOMAIN, jwt.shopify_domain end private def token(payload) ::JWT.encode(payload, ShopifyApp.configuration.secret, 'HS256') end def header { 'alg' => 'none', } end def payload( api_key: 'api_key', iss_host: TEST_SHOPIFY_DOMAIN, dest: iss_host, exp: 1.day.from_now, nbf: 1.day.ago, sub: TEST_USER_ID ) { 'iss' => "#{iss_host}/admin", 'dest' => dest, 'aud' => api_key, 'sub' => sub, 'exp' => exp.to_i, 'nbf' => nbf.to_i, 'iat' => 1.day.ago.to_i, 'jti' => 'abc', } end end end
JJ/markup
lib/github/markup.rb
<filename>lib/github/markup.rb begin require "linguist" rescue LoadError # Rely on extensions instead. end require "github/markup/command_implementation" require "github/markup/gem_implementation" module GitHub module Markups # all of supported markups: MARKUP_ASCIIDOC = :asciidoc MARKUP_CREOLE = :creole MARKUP_MARKDOWN = :markdown MARKUP_MEDIAWIKI = :mediawiki MARKUP_ORG = :org MARKUP_POD = :pod MARKUP_RDOC = :rdoc MARKUP_RST = :rst MARKUP_TEXTILE = :textile MARKUP_POD6 = :pod6 end module Markup extend self @@markups = {} def markups @@markups end def markup_impls markups.values end def preload! markup_impls.each(&:load) end def render(filename, content, symlink: false, options: {}) if (impl = renderer(filename, content, symlink: symlink)) impl.render(filename, content, options: options) else content end end def render_s(symbol, content) raise ArgumentError, 'Can not render a nil.' if content.nil? if markups.key?(symbol) markups[symbol].render(nil, content) else content end end def markup(symbol, gem_name, regexp, languages, opts = {}, &block) impl = GemImplementation.new(regexp, languages, gem_name, &block) markup_impl(symbol, impl) end def markup_impl(symbol, impl) if markups.key?(symbol) raise ArgumentError, "The '#{symbol}' symbol is already defined." end markups[symbol] = impl end def command(symbol, command, regexp, languages, name, &block) if File.exist?(file = File.dirname(__FILE__) + "/commands/#{command}") command = file end impl = CommandImplementation.new(regexp, languages, command, name, &block) markup_impl(symbol, impl) end def can_render?(filename, content, symlink: false) renderer(filename, content, symlink: symlink) != nil end def renderer(filename, content, symlink: false) language = language(filename, content, symlink: symlink) markup_impls.find do |impl| impl.match?(filename, language) end end def language(filename, content, symlink: false) return unless defined?(::Linguist) blob = Linguist::Blob.new(filename, content, symlink: symlink) Linguist.detect(blob, allow_empty: true) end # Define markups markups_rb = File.dirname(__FILE__) + '/markups.rb' instance_eval File.read(markups_rb), markups_rb end end
leodsgn/gymintel
app/models/user.rb
# frozen_string_literal: true class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :omniauthable, omniauth_providers: %i[facebook] end
leodsgn/gymintel
app/models/body_group.rb
<gh_stars>1-10 # frozen_string_literal: true class BodyGroup < ApplicationRecord end
leodsgn/gymintel
db/migrate/20180627201336_add_information_to_user.rb
<gh_stars>1-10 class AddInformationToUser < ActiveRecord::Migration[5.2] def change add_column :users, :first_name, :string, null: false add_column :users, :last_name, :string, null: false add_column :users, :birth_date, :date add_column :users, :phone_number, :string, limit: 20 add_column :users, :gender, :string, limit: 6 add_column :users, :document_id, :string, limit: 6 # cpf add_index :users, :first_name add_index :users, :last_name add_index :users, :gender add_index :users, :birth_date end end
doamatto/nano
nano.gemspec
<gh_stars>1-10 # frozen_string_literal: true Gem::Specification.new do |spec| spec.name = "nano-theme" spec.version = "0.5.2" spec.authors = ["doamatto"] spec.email = ["<EMAIL>"] spec.summary = "Nano is a super lightweight Jekyll theme built to work great on all platforms, respect user privacy, and load at lightning-fast speeds." spec.license = "BSD-3-Clause" spec.metadata = { "plugin_type" => "theme", "changelog_uri" => "https://github.com/doamatto/nano/releases", "documentation_uri" => "https://github.com/doamatto/nano/wiki", "source_code_uri" => "https://github.com/doamatto/nano", "wiki_uri" => "https://github.com/doamatto/nano/wiki" } spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r{^(assets|_layouts|_includes|_posts|_sass|LICENSE|README)}i) } spec.add_dependency "jekyll", "~> 4.1" spec.add_dependency "jekyll-sitemap", "~> 1.4" spec.add_dependency "jekyll-feed", "~> 0.13" end
benlellouch/AlphaBuilding-SyntheticDataset
code/OpenStudio-measures/Occupancy_Simulator_Office/measure.rb
<gh_stars>10-100 # *** Copyright Notice *** # OS Measures Copyright (c) 2018, The Regents of the University of California, # through Lawrence Berkeley National Laboratory (subject to receipt of any required # approvals from the U.S. Dept. of Energy). All rights reserved. # If you have questions about your rights to use or distribute this software, # please contact Berkeley Lab's Innovation & Partnerships Office at <EMAIL>. # NOTICE. This Software was developed under funding from the U.S. Department of # Energy and the U.S. Government consequently retains certain rights. As such, # the U.S. Government has been granted for itself and others acting on its behalf # a paid-up, nonexclusive, irrevocable, worldwide license in the Software to # reproduce, distribute copies to the public, prepare derivative works, and # perform publicly and display publicly, and to permit other to do so. # **************************** require 'openstudio' require 'time' require 'date' require 'rbconfig' # start the measure class OccupancySimulator < OpenStudio::Measure::ModelMeasure @@v_space_args = Hash.new # Standard space types for office rooms @@v_office_space_types = [ 'WholeBuilding - Sm Office', 'WholeBuilding - Md Office', 'WholeBuilding - Lg Office', 'Office', 'ClosedOffice', 'OpenOffice', 'SmallOffice - ClosedOffice', 'SmallOffice - OpenOffice', 'MediumOffice - ClosedOffice', 'MediumOffice - OpenOffice', 'LargeOffice - ClosedOffice', 'LargeOffice - OpenOffice' ] # Standard space types for meeting rooms @@v_conference_space_types = [ 'Conference', 'Classroom', 'SmallOffice - Conference', 'MediumOffice - Conference', 'MediumOffice - Classroom', 'LargeOffice - Conference' ] # Standard space types for auxiliary rooms @@v_auxiliary_space_types = [ 'OfficeLarge Data Center', 'OfficeLarge Main Data Center', 'SmallOffice - Elec/MechRoom', 'MediumOffice - Elec/MechRoom', 'LargeOffice - Elec/MechRoom' ] @@v_other_space_types = [ 'Office Attic', 'BreakRoom', 'Attic', 'Plenum', 'Corridor', 'Lobby', 'Elec/MechRoom', 'Stair', 'Restroom', 'Dining', 'Storage', 'Locker', 'Plenum Space Type', 'SmallOffice - Corridor', 'SmallOffice - Lobby', 'SmallOffice - Attic', 'SmallOffice - Restroom', 'SmallOffice - Stair', 'SmallOffice - Storage', 'MediumOffice - Corridor', 'MediumOffice - Dining', 'MediumOffice - Restroom', 'MediumOffice - Lobby', 'MediumOffice - Storage', 'MediumOffice - Stair', 'LargeOffice - Corridor', 'LargeOffice - Dining', 'LargeOffice - Restroom', 'LargeOffice - Lobby', 'LargeOffice - Storage', 'LargeOffice - Stair', '' ] # human readable name def name return "Occupancy Simulator" end # human readable description def description return "Generate stochastic occupancy schedules for office rooms and conference rooms. The stochastic schedules are generated by Occupancy Simulator (https://occupancysimulator.lbl.gov/)." end # human readable description of modeling approach def modeler_description return "The default space types in the measure inputs are automatically filled by the spaces' standard space types. User can overwrite the default assumptions in the library.csv file in the measure's resources folder." end # define the arguments that the user will input def arguments(model) args = OpenStudio::Measure::OSArgumentVector.new ############################################################################ # Prepare options for the apply measure now GUI ############################################################################ # Read user pre-defined library root_path = File.dirname(__FILE__) + '/resources/' # Load required class and gem files load root_path + 'UserLibrary.rb' userLib = UserLibrary.new(root_path + "library.csv") # Space type choices space_type_chs = OpenStudio::StringVector.new office_space_type_chs = OpenStudio::StringVector.new meeting_space_type_chs = OpenStudio::StringVector.new other_space_type_chs = OpenStudio::StringVector.new office_space_type_chs << userLib.Office_t1_name office_space_type_chs << userLib.Office_t2_name office_space_type_chs << userLib.Office_t3_name office_space_type_chs << userLib.Office_t4_name office_space_type_chs << userLib.Office_t5_name meeting_space_type_chs << userLib.meetingRoom_t1_name meeting_space_type_chs << userLib.meetingRoom_t2_name meeting_space_type_chs << userLib.meetingRoom_t3_name meeting_space_type_chs << userLib.meetingRoom_t4_name meeting_space_type_chs << userLib.meetingRoom_t5_name other_space_type_chs << "Auxiliary" other_space_type_chs << "Lobby" other_space_type_chs << "Corridor" other_space_type_chs << "Other" other_space_type_chs << "Plenum" v_space_types = model.getSpaceTypes i = 1 # Loop through all space types, group spaces by their types v_space_types.each do |space_type| # Populate the valid options for each space depending on its space type if @@v_office_space_types.include? space_type.standardsSpaceType.to_s space_type_chs = office_space_type_chs elsif @@v_conference_space_types.include? space_type.standardsSpaceType.to_s space_type_chs = meeting_space_type_chs elsif @@v_other_space_types.include? space_type.standardsSpaceType.to_s space_type_chs = other_space_type_chs else space_type_chs = other_space_type_chs end v_current_spaces = space_type.spaces next if not v_current_spaces.size > 0 v_current_spaces.each do |current_space| arg_name = current_space.nameString.gsub(' ', '-') @@v_space_args[current_space.nameString] = arg_name arg_temp = OpenStudio::Measure::OSArgument::makeChoiceArgument(arg_name, space_type_chs, true) arg_temp.setDisplayName("Space #{i}: " + current_space.nameString) # Conditionally set the default choice for the space if (@@v_office_space_types.include? space_type.standardsSpaceType.to_s) arg_temp.setDefaultValue(userLib.Office_t1_name) elsif (@@v_conference_space_types.include? space_type.standardsSpaceType.to_s) arg_temp.setDefaultValue(userLib.meetingRoom_t1_name) elsif (@@v_auxiliary_space_types.include? space_type.standardsSpaceType.to_s) arg_temp.setDefaultValue('Auxiliary') elsif (@@v_other_space_types.include? space_type.standardsSpaceType.to_s) # If the space type is not in standard space types arg_temp.setDefaultValue('Other') end args << arg_temp i += 1 end end return args end # Utility functions for the OccSim integration ################################## Functions ################################# # Utility function, read a model from a osm file and translate it to the # current OS version def loadOSM(pathStr) translator = OpenStudio::OSVersion::VersionTranslator.new path = OpenStudio::Path.new(pathStr) model = translator.loadModel(path) if model.empty? raise "Input #{pathStr} is not valid, please check." else model = model.get end return model end # [assignOccType description] # @param probabilityDct [Hash] A hash table of occupancy type and its probability # # @return [String] Occupancy type in String def assignOccType(probabilityDct) # Build an array based on probability v_sample = Array.new() probabilityDct.each do |key, p| (v_sample << Array.new(probabilityDct[key] * 100, key)).flatten! end # Sample from the array occType = v_sample.sample return occType end # # Utility function, check if a string can be parsed to a date # @param dateStr [String] original date string # # @return [Boolean] if the string can be parsed to date def isValidDate(dateStr) begin return (Date.strptime(dateStr, "%m/%d/%Y").class.to_s == "Date"), Date.strptime(dateStr, "%m/%d/%Y").to_s rescue begin return (Date.parse(dateStr).class.to_s == "Date"), Date.parse(dateStr).to_s rescue return false, nil end end end def space_rule_hash_wrapper(userLib) # Create hashes to store space rules available in the library # Office spaces office_t1 = { 'name' => userLib.Office_t1_name, 'OccupancyDensity' => userLib.Office_t1_OccupancyDensity, 'OccupantPercentageManager' => userLib.office_t1_OccupantPercentageManager, 'OccupantPercentageAdminitrator' => userLib.office_t1_OccupantPercentageAdminitrator, 'OccupantPercentageRegularStaff' => userLib.office_t1_OccupantPercentageRegularStaff } office_t2 = { 'name' => userLib.Office_t2_name, 'OccupancyDensity' => userLib.Office_t2_OccupancyDensity, 'OccupantPercentageManager' => userLib.office_t2_OccupantPercentageManager, 'OccupantPercentageAdminitrator' => userLib.office_t2_OccupantPercentageAdminitrator, 'OccupantPercentageRegularStaff' => userLib.office_t2_OccupantPercentageRegularStaff } office_t3 = { 'name' => userLib.Office_t3_name, 'OccupancyDensity' => userLib.Office_t3_OccupancyDensity, 'OccupantPercentageManager' => userLib.office_t3_OccupantPercentageManager, 'OccupantPercentageAdminitrator' => userLib.office_t3_OccupantPercentageAdminitrator, 'OccupantPercentageRegularStaff' => userLib.office_t3_OccupantPercentageRegularStaff } office_t4 = { 'name' => userLib.Office_t4_name, 'OccupancyDensity' => userLib.Office_t4_OccupancyDensity, 'OccupantPercentageManager' => userLib.office_t4_OccupantPercentageManager, 'OccupantPercentageAdminitrator' => userLib.office_t4_OccupantPercentageAdminitrator, 'OccupantPercentageRegularStaff' => userLib.office_t4_OccupantPercentageRegularStaff } office_t5 = { 'name' => userLib.Office_t5_name, 'OccupancyDensity' => userLib.Office_t5_OccupancyDensity, 'OccupantPercentageManager' => userLib.office_t5_OccupantPercentageManager, 'OccupantPercentageAdminitrator' => userLib.office_t5_OccupantPercentageAdminitrator, 'OccupantPercentageRegularStaff' => userLib.office_t5_OccupantPercentageRegularStaff } # Meeting spaces meeting_t1 = { 'name' => userLib.meetingRoom_t1_name, 'MinimumNumberOfMeetingPerDay' => userLib.meetingRoom_t1_MinimumNumberOfMeetingPerDay, 'MaximumNumberOfMeetingPerDay' => userLib.meetingRoom_t1_MaximumNumberOfMeetingPerDay, 'MinimumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t1_MinimumNumberOfPeoplePerMeeting, 'MaximumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t1_MaximumNumberOfPeoplePerMeeting, 'ProbabilityOf_30_minMeetings' => userLib.meetingRoom_t1_ProbabilityOf_30_minMeetings, 'ProbabilityOf_60_minMeetings' => userLib.meetingRoom_t1_ProbabilityOf_60_minMeetings, 'ProbabilityOf_90_minMeetings' => userLib.meetingRoom_t1_ProbabilityOf_90_minMeetings, 'ProbabilityOf_120_minMeetings' => userLib.meetingRoom_t1_ProbabilityOf_120_minMeetings } meeting_t2 = { 'name' => userLib.meetingRoom_t2_name, 'MinimumNumberOfMeetingPerDay' => userLib.meetingRoom_t2_MinimumNumberOfMeetingPerDay, 'MaximumNumberOfMeetingPerDay' => userLib.meetingRoom_t2_MaximumNumberOfMeetingPerDay, 'MinimumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t2_MinimumNumberOfPeoplePerMeeting, 'MaximumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t2_MaximumNumberOfPeoplePerMeeting, 'ProbabilityOf_30_minMeetings' => userLib.meetingRoom_t2_ProbabilityOf_30_minMeetings, 'ProbabilityOf_60_minMeetings' => userLib.meetingRoom_t2_ProbabilityOf_60_minMeetings, 'ProbabilityOf_90_minMeetings' => userLib.meetingRoom_t2_ProbabilityOf_90_minMeetings, 'ProbabilityOf_120_minMeetings' => userLib.meetingRoom_t2_ProbabilityOf_120_minMeetings } meeting_t3 = { 'name' => userLib.meetingRoom_t3_name, 'MinimumNumberOfMeetingPerDay' => userLib.meetingRoom_t3_MinimumNumberOfMeetingPerDay, 'MaximumNumberOfMeetingPerDay' => userLib.meetingRoom_t3_MaximumNumberOfMeetingPerDay, 'MinimumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t3_MinimumNumberOfPeoplePerMeeting, 'MaximumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t3_MaximumNumberOfPeoplePerMeeting, 'ProbabilityOf_30_minMeetings' => userLib.meetingRoom_t3_ProbabilityOf_30_minMeetings, 'ProbabilityOf_60_minMeetings' => userLib.meetingRoom_t3_ProbabilityOf_60_minMeetings, 'ProbabilityOf_90_minMeetings' => userLib.meetingRoom_t3_ProbabilityOf_90_minMeetings, 'ProbabilityOf_120_minMeetings' => userLib.meetingRoom_t3_ProbabilityOf_120_minMeetings } meeting_t4 = { 'name' => userLib.meetingRoom_t4_name, 'MinimumNumberOfMeetingPerDay' => userLib.meetingRoom_t4_MinimumNumberOfMeetingPerDay, 'MaximumNumberOfMeetingPerDay' => userLib.meetingRoom_t4_MaximumNumberOfMeetingPerDay, 'MinimumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t4_MinimumNumberOfPeoplePerMeeting, 'MaximumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t4_MaximumNumberOfPeoplePerMeeting, 'ProbabilityOf_30_minMeetings' => userLib.meetingRoom_t4_ProbabilityOf_30_minMeetings, 'ProbabilityOf_60_minMeetings' => userLib.meetingRoom_t4_ProbabilityOf_60_minMeetings, 'ProbabilityOf_90_minMeetings' => userLib.meetingRoom_t4_ProbabilityOf_90_minMeetings, 'ProbabilityOf_120_minMeetings' => userLib.meetingRoom_t4_ProbabilityOf_120_minMeetings } meeting_t5 = { 'name' => userLib.meetingRoom_t5_name, 'MinimumNumberOfMeetingPerDay' => userLib.meetingRoom_t5_MinimumNumberOfMeetingPerDay, 'MaximumNumberOfMeetingPerDay' => userLib.meetingRoom_t5_MaximumNumberOfMeetingPerDay, 'MinimumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t5_MinimumNumberOfPeoplePerMeeting, 'MaximumNumberOfPeoplePerMeeting' => userLib.meetingRoom_t5_MaximumNumberOfPeoplePerMeeting, 'ProbabilityOf_30_minMeetings' => userLib.meetingRoom_t5_ProbabilityOf_30_minMeetings, 'ProbabilityOf_60_minMeetings' => userLib.meetingRoom_t5_ProbabilityOf_60_minMeetings, 'ProbabilityOf_90_minMeetings' => userLib.meetingRoom_t5_ProbabilityOf_90_minMeetings, 'ProbabilityOf_120_minMeetings' => userLib.meetingRoom_t5_ProbabilityOf_120_minMeetings } space_rules = { userLib.Office_t1_name => office_t1, userLib.Office_t2_name => office_t2, userLib.Office_t3_name => office_t3, userLib.Office_t4_name => office_t4, userLib.Office_t5_name => office_t5, userLib.meetingRoom_t1_name => meeting_t1, userLib.meetingRoom_t2_name => meeting_t2, userLib.meetingRoom_t3_name => meeting_t3, userLib.meetingRoom_t4_name => meeting_t4, userLib.meetingRoom_t5_name => meeting_t5 } return space_rules end # Primary function, build a obXML from OpenStudio model and pre-defined library # @param osModel [OpenStudio::Model::Model] # @param userLib [UserLibrary] # # @return [type] [description] def obXML_builder(osModel, userLib, outPath, all_args) # Get general information ---------------------------------------------------- # Get specific occupancy assumptions for each space flag_space_occ_choice = all_args[0] space_rules = space_rule_hash_wrapper(userLib) v_space_types = osModel.getSpaceTypes v_meeting_spaces = Array.new v_office_spaces = Array.new v_all_occ_id = Array.new v_occ_bhvr_ID = ["Regular_staff_0", "Manager_0", "Administrator_0"] v_holidays = [ userLib.usHolidayNewYearsDay, userLib.usHolidayMartinLutherKingJrDay, userLib.usHolidayGeorgeWashingtonsBirthday, userLib.usHolidayMemorialDay, userLib.usHolidayIndependenceDay, userLib.usHolidayLaborDay, userLib.usHolidayColumbusDay, userLib.usHolidayVeteransDay, userLib.usHolidayThanksgivingDay, userLib.usHolidayChristmasDay, userLib.customHolidayCustomHoliday_1, userLib.customHolidayCustomHoliday_2, userLib.customHolidayCustomHoliday_3, userLib.customHolidayCustomHoliday_4, userLib.customHolidayCustomHoliday_5 ] # Loop through all space types v_space_types.each do |space_type| if @@v_office_space_types.include? space_type.standardsSpaceType.to_s # Add the corresponding office spaces to the array v_office_spaces += space_type.spaces elsif @@v_conference_space_types.include? space_type.standardsSpaceType.to_s # Add the corresponding conference spaces to the array v_meeting_spaces += space_type.spaces end end # Number of space and number of people n_space = v_office_spaces.length n_occ = 0 n_occ_hash = Hash.new v_office_spaces.each do |officeSpace| space_type_selected = flag_space_occ_choice[officeSpace.name.to_s] n_occ_current = (officeSpace.floorArea / space_rules[space_type_selected]['OccupancyDensity']).floor n_occ += n_occ_current # Save the maximum number of people to a hash n_occ_hash[officeSpace.name.to_s] = n_occ_current end # Generate the obXML file f = File.new(outPath + "/obXML.xml", "w") f.puts('<?xml version="1.0"?>') f.puts('<OccupantBehavior xsi:noNamespaceSchemaLocation="obXML_v1.3.2.xsd" ID="OS001" Version="1.3.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">') # Buildings f.puts('<Buildings>') ## Building f.puts('<Building ID="Building_1">') ### Description f.puts("<Description>A office building which contains #{n_space} spaces and #{n_occ} occupants</Description>") ### --Description ### Type f.puts("<Type>Office</Type>") ### --Type ### Spaces f.puts("<Spaces ID='All_Spaces'>") #### Space f.puts("<Space ID='Outdoor'>") ##### Space Type f.puts("<Type>Outdoor</Type>") f.puts("</Space>") # Add spaces to the building all_index = 0 # Create a hash to store the space and index space_ID_map = Hash.new # ~ Meeting room spaces v_meeting_spaces.each_with_index do |meetingSpace, index| meeting_space_name = meetingSpace.nameString space_type_selected = flag_space_occ_choice[meeting_space_name] min_meeting_per_day = space_rules[space_type_selected]['MinimumNumberOfMeetingPerDay'] max_meeting_per_day = space_rules[space_type_selected]['MaximumNumberOfMeetingPerDay'] min_occupant_per_meeting = space_rules[space_type_selected]['MinimumNumberOfPeoplePerMeeting'] max_occupant_per_meeting = space_rules[space_type_selected]['MaximumNumberOfPeoplePerMeeting'] probabilityOf_30_minMeetings = space_rules[space_type_selected]['ProbabilityOf_30_minMeetings'] probabilityOf_60_minMeetings = space_rules[space_type_selected]['ProbabilityOf_60_minMeetings'] probabilityOf_90_minMeetings = space_rules[space_type_selected]['ProbabilityOf_90_minMeetings'] probabilityOf_120_minMeetings = space_rules[space_type_selected]['ProbabilityOf_120_minMeetings'] # Assign the space id and name, and save it to the hash space_ID_map[meeting_space_name] = index + 1 + all_index n_occ_hash[meetingSpace.nameString] = max_occupant_per_meeting f.puts("<Space ID='" + meeting_space_name + "'>") f.puts("<Type>MeetingRoom</Type>") f.puts("<MeetingEvent>") f.puts("<SeasonType>All</SeasonType>") f.puts('<DayofWeek>Weekdays</DayofWeek>') f.puts("<MinNumOccupantsPerMeeting>#{min_occupant_per_meeting}</MinNumOccupantsPerMeeting>") f.puts("<MaxNumOccupantsPerMeeting>#{max_occupant_per_meeting}</MaxNumOccupantsPerMeeting>") f.puts("<MinNumberOfMeetingsPerDay>#{min_meeting_per_day}</MinNumberOfMeetingsPerDay>") f.puts("<MaxNumberOfMeetingsPerDay>#{max_meeting_per_day}</MaxNumberOfMeetingsPerDay>") f.puts("<MeetingDurationProbability>") f.puts("<MeetingDuration>PT30M</MeetingDuration>") f.puts("<Probability>#{probabilityOf_30_minMeetings}</Probability>") f.puts("</MeetingDurationProbability>") f.puts("<MeetingDurationProbability>") f.puts("<MeetingDuration>PT60M</MeetingDuration>") f.puts("<Probability>#{probabilityOf_60_minMeetings}</Probability>") f.puts("</MeetingDurationProbability>") f.puts("<MeetingDurationProbability>") f.puts("<MeetingDuration>PT90M</MeetingDuration>") f.puts("<Probability>#{probabilityOf_90_minMeetings}</Probability>") f.puts("</MeetingDurationProbability>") f.puts("<MeetingDurationProbability>") f.puts("<MeetingDuration>PT120M</MeetingDuration>") f.puts("<Probability>#{probabilityOf_120_minMeetings}</Probability>") f.puts("</MeetingDurationProbability>") f.puts("</MeetingEvent>") f.puts("</Space>") end all_index = all_index + v_meeting_spaces.length # ~ Office spaces occ_id_spaceName_hash = Hash.new v_office_spaces.each_with_index do |officeSpace, index| # Get space basic information office_space_name = officeSpace.nameString space_type_selected = flag_space_occ_choice[office_space_name] nOcc = (officeSpace.floorArea / space_rules[space_type_selected]['OccupancyDensity']).floor # Assign the space id and name, and save it to the hash space_ID_map[office_space_name] = index + 1 + all_index f.puts("<Space ID='" + office_space_name + "'>") f.puts("<Type>OfficeShared</Type>") # Add occupants to each space for i in 0..(nOcc - 1) occ_id_string = "#{office_space_name}_Occ_#{i + 1}" f.puts("<OccupantID>" + occ_id_string + "</OccupantID>") v_all_occ_id << occ_id_string occ_id_spaceName_hash[occ_id_string] = office_space_name end f.puts("</Space>") end all_index = all_index + v_office_spaces.length #### --Space f.puts("</Spaces>") ### --Spaces f.puts('</Building>') ## --Building f.puts('</Buildings>') # --Buildings # Occupants f.puts('<Occupants>') ## Occupant v_all_occ_id.each_with_index do |occID, index| f.puts("<Occupant ID='" + occID + "'>") # puts '---->' space_type_selected = flag_space_occ_choice[occ_id_spaceName_hash[occID]] f.puts("<LifeStyle>Norm</LifeStyle>") # Randomly assign occ type by probability p_hash = { "Manager" => space_rules[space_type_selected]['OccupantPercentageManager'], "Administrator" => space_rules[space_type_selected]['OccupantPercentageAdminitrator'], "Regular staff" => space_rules[space_type_selected]['OccupantPercentageRegularStaff'] } occType = assignOccType(p_hash) f.puts("<JobType>" + occType + " </JobType>") # Assign movement behavior based on occ type drawed previously case occType when "Regular staff" occ_mvmnt_bhvr_id = "Regular_staff_0" when "Manager" occ_mvmnt_bhvr_id = "Manager_0" when "Administrator" occ_mvmnt_bhvr_id = "Administrator_0" end f.puts("<MovementBehaviorID>" + occ_mvmnt_bhvr_id + " </MovementBehaviorID>") f.puts("</Occupant>") end ## --Occupant f.puts('</Occupants>') # --Occupants # Behaviors f.puts('<Behaviors>') v_occ_bhvr_ID.each do |occBhvrID| ## Movement Behavior f.puts("<MovementBehavior ID='" + occBhvrID + "'>") case occBhvrID when "Regular_staff_0" # Regular Staff behaviors f.puts('<SeasonType>All</SeasonType>') f.puts('<DayofWeek>Weekdays</DayofWeek>') ### Random movement behavior f.puts('<RandomMovementEvent>') #### Space occupancy -- 1.OwnOffice f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>OwnOffice</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.regularStaffPercentOfTimeInSpaceOwnOffice}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.regularStaffAverageStayTimeOwnOffice}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 1.OwnOffice #### Space occupancy -- 2.OtherOffice f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>OtherOffice</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.regularStaffPercentOfTimeInSpaceOtherOffices}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.regularStaffAverageStayTimeOtherOffices}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 2.OtherOffice #### Space occupancy -- 3.MeetingRoom f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>MeetingRoom</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.regularStaffPercentOfTimeInSpaceMeetingRooms}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.regularStaffAverageStayTimeMeetingRooms}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 3.MeetingRoom #### Space occupancy -- 4.AuxRoom f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>AuxRoom</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.regularStaffPercentOfTimeInSpaceAuxiliaryRooms}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.regularStaffAverageStayTimeAuxiliaryRooms}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 4.AuxRoom #### Space occupancy -- 5.Outdoor f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>Outdoor</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.regularStaffPercentOfTimeInSpaceOutdoor}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.regularStaffAverageStayTimeOutdoor}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 5.Ourdoor f.puts('</RandomMovementEvent>') ### --Random movement behavior ### Status transition event --1.Arrival f.puts('<StatusTransitionEvent>') f.puts('<EventType>Arrival</EventType>') #### Event occur model f.puts('<EventOccurModel>') f.puts('<NormalProbabilityModel>') timeStr = userLib.regularStaffTypicalArrivalTime timeVar = userLib.regularStaffArrivalTimeVariation f.puts('<EarlyOccurTime>' + (Time.strptime(timeStr, "%H:%M") - timeVar * 60).strftime("%H:%M:%S") + '</EarlyOccurTime>') f.puts("<TypicalOccurTime>#{timeStr}:00</TypicalOccurTime>") f.puts('</NormalProbabilityModel>') f.puts('</EventOccurModel>') #### --Event occur model f.puts('</StatusTransitionEvent>') ### --Status transition event --1.Arrival ### Status transition event --2.Departure f.puts('<StatusTransitionEvent>') f.puts('<EventType>Departure</EventType>') #### Event occur model f.puts('<EventOccurModel>') f.puts('<NormalProbabilityModel>') timeStr = userLib.regularStaffTypicalDepartureTime timeVar = userLib.regularStaffDepartureTimeVariation f.puts('<EarlyOccurTime>' + (Time.strptime(timeStr, "%H:%M") - timeVar * 60).strftime("%H:%M:%S") + '</EarlyOccurTime>') f.puts("<TypicalOccurTime>#{timeStr}:00</TypicalOccurTime>") f.puts('</NormalProbabilityModel>') f.puts('</EventOccurModel>') #### --Event occur model f.puts('</StatusTransitionEvent>') ### --Status transition event --2.Departure ### Status transition event --3.Short term leaving f.puts('<StatusTransitionEvent>') f.puts('<EventType>ShortTermLeaving</EventType>') #### Event occur model f.puts('<EventOccurModel>') f.puts('<NormalProbabilityModel>') timeStr = userLib.regularStaffTypicalShortTermLeaving timeVar = userLib.regularStaffShortTermLeavingVariation f.puts('<EarlyOccurTime>' + (Time.strptime(timeStr, "%H:%M") - timeVar * 60).strftime("%H:%M:%S") + '</EarlyOccurTime>') f.puts("<TypicalOccurTime>#{timeStr}:00</TypicalOccurTime>") f.puts('</NormalProbabilityModel>') f.puts('</EventOccurModel>') #### --Event occur model #### Event Duration f.puts('<EventDuration>') f.puts('<NormalDurationModel>') duration = userLib.regularStaffTypicalShortTermLeavingDuration durationVar = userLib.regularStaffShortTermLeavingDurationVariation f.puts("<TypicalDuration>PT#{duration}M</TypicalDuration>") f.puts("<MinimumDuration>PT#{duration - durationVar}M</MinimumDuration>") f.puts('</NormalDurationModel>') f.puts('</EventDuration>') #### --Event Duration f.puts('</StatusTransitionEvent>') ### --Status transition event --3.Short term leaving when "Manager_0" # Manager behaviors f.puts('<SeasonType>All</SeasonType>') f.puts('<DayofWeek>Weekdays</DayofWeek>') ### Random movement behavior f.puts('<RandomMovementEvent>') #### Space occupancy -- 1.OwnOffice f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>OwnOffice</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.managerPercentOfTimeInSpaceOwnOffice}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.managerAverageStayTimeOwnOffice}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 1.OwnOffice #### Space occupancy -- 2.OtherOffice f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>OtherOffice</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.managerPercentOfTimeInSpaceOtherOffices}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.managerAverageStayTimeOtherOffices}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 2.OtherOffice #### Space occupancy -- 3.MeetingRoom f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>MeetingRoom</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.managerPercentOfTimeInSpaceMeetingRooms}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.managerAverageStayTimeMeetingRooms}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 3.MeetingRoom #### Space occupancy -- 4.AuxRoom f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>AuxRoom</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.managerPercentOfTimeInSpaceAuxiliaryRooms}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.managerAverageStayTimeAuxiliaryRooms}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 4.AuxRoom #### Space occupancy -- 5.Outdoor f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>Outdoor</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.managerPercentOfTimeInSpaceOutdoor}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.managerAverageStayTimeOutdoor}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 5.Ourdoor f.puts('</RandomMovementEvent>') ### --Random movement behavior ### Status transition event --1.Arrival f.puts('<StatusTransitionEvent>') f.puts('<EventType>Arrival</EventType>') #### Event occur model f.puts('<EventOccurModel>') f.puts('<NormalProbabilityModel>') timeStr = userLib.managerTypicalArrivalTime timeVar = userLib.managerArrivalTimeVariation f.puts('<EarlyOccurTime>' + (Time.strptime(timeStr, "%H:%M") - timeVar * 60).strftime("%H:%M:%S") + '</EarlyOccurTime>') f.puts("<TypicalOccurTime>#{timeStr}:00</TypicalOccurTime>") f.puts('</NormalProbabilityModel>') f.puts('</EventOccurModel>') #### --Event occur model f.puts('</StatusTransitionEvent>') ### --Status transition event --1.Arrival ### Status transition event --2.Departure f.puts('<StatusTransitionEvent>') f.puts('<EventType>Departure</EventType>') #### Event occur model f.puts('<EventOccurModel>') f.puts('<NormalProbabilityModel>') timeStr = userLib.managerTypicalDepartureTime timeVar = userLib.managerDepartureTimeVariation f.puts('<EarlyOccurTime>' + (Time.strptime(timeStr, "%H:%M") - timeVar * 60).strftime("%H:%M:%S") + '</EarlyOccurTime>') f.puts("<TypicalOccurTime>#{timeStr}:00</TypicalOccurTime>") f.puts('</NormalProbabilityModel>') f.puts('</EventOccurModel>') #### --Event occur model f.puts('</StatusTransitionEvent>') ### --Status transition event --2.Departure ### Status transition event --3.Short term leaving f.puts('<StatusTransitionEvent>') f.puts('<EventType>ShortTermLeaving</EventType>') #### Event occur model f.puts('<EventOccurModel>') f.puts('<NormalProbabilityModel>') timeStr = userLib.managerTypicalShortTermLeaving timeVar = userLib.managerShortTermLeavingVariation f.puts('<EarlyOccurTime>' + (Time.strptime(timeStr, "%H:%M") - timeVar * 60).strftime("%H:%M:%S") + '</EarlyOccurTime>') f.puts("<TypicalOccurTime>#{timeStr}:00</TypicalOccurTime>") f.puts('</NormalProbabilityModel>') f.puts('</EventOccurModel>') #### --Event occur model #### Event Duration f.puts('<EventDuration>') f.puts('<NormalDurationModel>') duration = userLib.managerTypicalShortTermLeavingDuration durationVar = userLib.managerShortTermLeavingDurationVariation f.puts("<TypicalDuration>PT#{duration}M</TypicalDuration>") f.puts("<MinimumDuration>PT#{duration - durationVar}M</MinimumDuration>") f.puts('</NormalDurationModel>') f.puts('</EventDuration>') #### --Event Duration f.puts('</StatusTransitionEvent>') ### --Status transition event --3.Short term leaving when 'Administrator_0' # Administrator behaviors f.puts('<SeasonType>All</SeasonType>') f.puts('<DayofWeek>Weekdays</DayofWeek>') ### Random movement behavior f.puts('<RandomMovementEvent>') #### Space occupancy -- 1.OwnOffice f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>OwnOffice</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.administratorPercentOfTimeInSpaceOwnOffice}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.administratorAverageStayTimeOwnOffice}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 1.OwnOffice #### Space occupancy -- 2.OtherOffice f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>OtherOffice</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.administratorPercentOfTimeInSpaceOtherOffices}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.administratorAverageStayTimeOtherOffices}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 2.OtherOffice #### Space occupancy -- 3.MeetingRoom f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>MeetingRoom</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.administratorPercentOfTimeInSpaceMeetingRooms}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.administratorAverageStayTimeMeetingRooms}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 3.MeetingRoom #### Space occupancy -- 4.AuxRoom f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>AuxRoom</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.administratorPercentOfTimeInSpaceAuxiliaryRooms}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.administratorAverageStayTimeAuxiliaryRooms}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 4.AuxRoom #### Space occupancy -- 5.Outdoor f.puts('<SpaceOccupancy>') f.puts('<SpaceCategory>Outdoor</SpaceCategory>') f.puts("<PercentTimePresence>#{userLib.administratorPercentOfTimeInSpaceOutdoor}.0</PercentTimePresence>") f.puts("<Duration>PT#{userLib.administratorAverageStayTimeOutdoor}M</Duration>") f.puts('</SpaceOccupancy>') #### --Space occupancy -- 5.Ourdoor f.puts('</RandomMovementEvent>') ### --Random movement behavior ### Status transition event --1.Arrival f.puts('<StatusTransitionEvent>') f.puts('<EventType>Arrival</EventType>') #### Event occur model f.puts('<EventOccurModel>') f.puts('<NormalProbabilityModel>') timeStr = userLib.administratorTypicalArrivalTime timeVar = userLib.administratorArrivalTimeVariation f.puts('<EarlyOccurTime>' + (Time.strptime(timeStr, "%H:%M") - timeVar * 60).strftime("%H:%M:%S") + '</EarlyOccurTime>') f.puts("<TypicalOccurTime>#{timeStr}:00</TypicalOccurTime>") f.puts('</NormalProbabilityModel>') f.puts('</EventOccurModel>') #### --Event occur model f.puts('</StatusTransitionEvent>') ### --Status transition event --1.Arrival ### Status transition event --2.Departure f.puts('<StatusTransitionEvent>') f.puts('<EventType>Departure</EventType>') #### Event occur model f.puts('<EventOccurModel>') f.puts('<NormalProbabilityModel>') timeStr = userLib.administratorTypicalDepartureTime timeVar = userLib.administratorDepartureTimeVariation f.puts('<EarlyOccurTime>' + (Time.strptime(timeStr, "%H:%M") - timeVar * 60).strftime("%H:%M:%S") + '</EarlyOccurTime>') f.puts("<TypicalOccurTime>#{timeStr}:00</TypicalOccurTime>") f.puts('</NormalProbabilityModel>') f.puts('</EventOccurModel>') #### --Event occur model f.puts('</StatusTransitionEvent>') ### --Status transition event --2.Departure ### Status transition event --3.Short term leaving f.puts('<StatusTransitionEvent>') f.puts('<EventType>ShortTermLeaving</EventType>') #### Event occur model f.puts('<EventOccurModel>') f.puts('<NormalProbabilityModel>') timeStr = userLib.administratorTypicalShortTermLeaving timeVar = userLib.administratorShortTermLeavingVariation f.puts('<EarlyOccurTime>' + (Time.strptime(timeStr, "%H:%M") - timeVar * 60).strftime("%H:%M:%S") + '</EarlyOccurTime>') f.puts("<TypicalOccurTime>#{timeStr}:00</TypicalOccurTime>") f.puts('</NormalProbabilityModel>') f.puts('</EventOccurModel>') #### --Event occur model #### Event Duration f.puts('<EventDuration>') f.puts('<NormalDurationModel>') duration = userLib.administratorTypicalShortTermLeavingDuration durationVar = userLib.administratorShortTermLeavingDurationVariation f.puts("<TypicalDuration>PT#{duration}M</TypicalDuration>") f.puts("<MinimumDuration>PT#{duration - durationVar}M</MinimumDuration>") f.puts('</NormalDurationModel>') f.puts('</EventDuration>') #### --Event Duration f.puts('</StatusTransitionEvent>') ### --Status transition event --3.Short term leaving end f.puts("</MovementBehavior>") ## --Movement Behavior end f.puts('</Behaviors>') # --Behaviors # Holidays f.puts('<Holidays>') v_holidays.each do |hDate| valid_date = false valid_date, date_str = isValidDate(hDate) if (valid_date) ## Holiday f.puts('<Holiday>') f.puts('<Date>' + date_str + '</Date>') f.puts('</Holiday>') ## --Holiday end end f.puts('</Holidays>') f.puts('</OccupantBehavior>') f.close puts '------------------------------------------------------------------' puts 'obXMl.xml file created.' puts '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' result_hashes = [space_ID_map, n_occ_hash] return result_hashes end # This function build a CoSimXMl.xml file # All the fields are default def coSimXML_builder(model, outPath) # Get simulation configurations from model if model.isLeapYear isLeapYear = 'Yes' else isLeapYear = 'No' end dayofWeekforStartDay = model.dayofWeekforStartDay beginMonth = model.getRunPeriod.getBeginMonth beginDayOfMonth = model.getRunPeriod.getBeginDayOfMonth endMonth = model.getRunPeriod.getEndMonth endDayOfMonth = model.getRunPeriod.getEndDayOfMonth timestepsPerHour = model.getTimestep.numberOfTimestepsPerHour # Write XML to file f = File.new(outPath + "/obCoSim.xml", "w") # CoSimulationParameters f.puts('<CoSimulationParameters>') ## SpaceNameMapping f.puts('<SpaceNameMapping>') f.puts('<obXML_SpaceID>ID_Holder</obXML_SpaceID>') f.puts('<FMU_InstanceName>place_holder</FMU_InstanceName>') f.puts('</SpaceNameMapping>') ## --SpaceNameMapping ## Simulation setting f.puts('<SimulationSettings>') f.puts('<IsLeapYear>' + isLeapYear + '</IsLeapYear>') f.puts('<DayofWeekForStartDay>' + dayofWeekforStartDay.to_s + '</DayofWeekForStartDay>') f.puts('<IsDebugMode>No</IsDebugMode>') f.puts('<DoMovementCalculation>Yes</DoMovementCalculation>') f.puts('<StartMonth>' + beginMonth.to_s + '</StartMonth>') f.puts('<StartDay>' + beginDayOfMonth.to_s + '</StartDay>') f.puts('<EndMonth>' + endMonth.to_s + '</EndMonth>') f.puts('<EndDay>' + endDayOfMonth.to_s + '</EndDay>') f.puts('<NumberofTimestepsPerHour>' + timestepsPerHour.to_s + '</NumberofTimestepsPerHour>') f.puts('</SimulationSettings>') ## --Simulation setting f.puts('</CoSimulationParameters>') # --CoSimulationParameters f.close puts '------------------------------------------------------------------' puts 'coSimXML.xml file created.' puts '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' end def get_os_schedule_from_csv(file_name, model, schedule_name, col, skip_row) puts '---> Try to create schedule:file object...' file_name = File.realpath(file_name) raise "File '#{file_name}' does not exist" if !File.exists?(file_name) external_file = OpenStudio::Model::ExternalFile::getExternalFile(model, file_name) raise "ExternalFile for '#{file_name}' is not initialized" if external_file.empty? external_file = external_file.get schedule_file = OpenStudio::Model::ScheduleFile.new(external_file, col, skip_row) schedule_file.setName(schedule_name) return schedule_file end def set_schedule_for_people(model, space_name, csv_file, userLib, all_args) space_rules = space_rule_hash_wrapper(userLib) occ_type_arg_vals = all_args[0] space_ID_map = all_args[1] n_occ_hash = all_args[2] space_type_selected = occ_type_arg_vals[space_name] # Only office and meeting spaces have space rules for now if not space_rules[space_type_selected].nil? # Create people activity schedule people_activity_sch = OpenStudio::Model::ScheduleCompact.new(model) people_activity_sch.setName('obFMU Activity Schedule') people_activity_sch.setToConstantValue(110.7) # Set OS:People:Definition attributes new_people_def = OpenStudio::Model::PeopleDefinition.new(model) new_people_def.setName(space_name + ' people definition') # Test create new people and people definition instances new_people = OpenStudio::Model::People.new(new_people_def) new_people.setName(space_name + ' people') new_people.setActivityLevelSchedule(people_activity_sch) # Check if the space is office or meeting room. if space_rules[space_type_selected]['OccupancyDensity'].nil? n_people = n_occ_hash[space_name] new_people_def.setNumberOfPeopleCalculationMethod('People', 1) new_people_def.setNumberofPeople(n_people) else n_people = n_occ_hash[space_name] new_people_def.setNumberOfPeopleCalculationMethod('People', 1) new_people_def.setNumberofPeople(n_people) end # Map the schedule to space # Get the column number in the output schedule file by space name col_number = space_ID_map[space_name] + 2 # Skip col 1: step and col 2: time sch_file_name = space_name + ' occ sch' people_sch = get_os_schedule_from_csv(csv_file, model, sch_file_name, col_number, skip_row = 7) # Set minute per item (timestep = 10min) May need to change !!! minute_per_timestep = (60 / model.getTimestep.numberOfTimestepsPerHour).round people_sch.setMinutesperItem(minute_per_timestep.to_s) new_people.setNumberofPeopleSchedule(people_sch) # Add schedule to the right space model.getSpaces.each do |current_space| if current_space.nameString == space_name new_people.setSpace(current_space) end end end return model end def os @os ||= ( host_os = RbConfig::CONFIG['host_os'] case host_os when /mswin|msys|mingw|cygwin|bccwin|wince|emc/ :windows when /darwin|mac os/ :macosx when /linux/ :linux when /solaris|bsd/ :unix else raise Error::WebDriverError, "unknown os: #{host_os.inspect}" end ) end ############################################################################## # define what happens when the measure is run def run(model, runner, user_arguments) super(model, runner, user_arguments) puts "=" * 80 puts '---> Entering RUN' # use the built-in error checking if !runner.validateUserArguments(arguments(model), user_arguments) return false end # report initial condition of model runner.registerInitialCondition("Start.") # For run in OS GUI measure_root_path = File.dirname(__FILE__) measure_resources_path = measure_root_path + '/resources/' runner.registerInfo("Measure_resources_path is: '#{measure_resources_path}'") # For run in OSW temp_measure_resources_path = File.expand_path("../../..", Dir.pwd + '/') + '/resources/measures/Occupancy_Simulator/resources/' runner.registerInfo("The temp measure directory is: '#{temp_measure_resources_path}'") # Load uer-defined library if File.directory?(temp_measure_resources_path) load temp_measure_resources_path + 'UserLibrary.rb' userLib = UserLibrary.new(temp_measure_resources_path + "library.csv") puts "---> Loading user-defined library from temporary measure resources path: #{temp_measure_resources_path}" runner.registerInfo("Loading user-defined library from temporary measure resources path: #{temp_measure_resources_path}") else load measure_resources_path + 'UserLibrary.rb' userLib = UserLibrary.new(measure_resources_path + "library.csv") puts "---> Loading user-defined library from measure resources path: #{measure_resources_path}" runner.registerInfo("Loading user-defined library from measure resources path: #{measure_resources_path}") end # ### Get user input for whether to use default assumptions by space types v_space_types = model.getSpaceTypes ### Get user selected occupancy assumptions for each space i = 1 occ_type_arg_vals = {} # Loop through all space types, group spaces by their types v_space_types.each do |space_type| # Loop through all spaces of current space type v_current_spaces = space_type.spaces next if not v_current_spaces.size > 0 v_current_spaces.each do |current_space| occ_type_val = runner.getStringArgumentValue(@@v_space_args[current_space.nameString], user_arguments) occ_type_arg_vals[current_space.nameString] = occ_type_val i += 1 end end all_args = [] all_args[0] = occ_type_arg_vals # Read obXML file and call obFMU.exe file_written_path = File.realpath('./') # Write to the current run folder. output_path_prefix = file_written_path + '/OccSimulator_out' puts File.dirname(output_path_prefix) puts File.expand_path("..", File.dirname(output_path_prefix)) obFMU_xml_file_path = file_written_path + "/obXML.xml" coSim_xml_file_path = file_written_path + "/obCoSim.xml" # Generate obXML and coSimXML files result_hashes = obXML_builder(model, userLib, file_written_path, all_args) coSimXML_builder(model, file_written_path) # Command to call obFMU.exe # Remove old output file if it exists. external_csv_path = output_path_prefix + '_IDF.csv' # Delete the external CSV file is any exists. if File.exist?(external_csv_path) File.delete(external_csv_path) runner.registerInfo("Deleted old output occ sch file at '#{external_csv_path}'") end puts external_csv_path # Run occupancy simulator # system(measure_resources_path + 'obFMU.exe', obFMU_xml_file_path, output_path_prefix, coSim_xml_file_path) if os.to_s == 'windows' runner.registerInfo("Running obFMU on Windows.") puts 'Running obFMU on Windows.' system(measure_resources_path + 'obFMU.exe', obFMU_xml_file_path, output_path_prefix, coSim_xml_file_path) elsif os.to_s == 'macosx' runner.registerInfo("Running obFMU on MacOS.") puts 'Running obFMU on MacOS.' system('chmod +x ' + measure_resources_path + 'obFMU_mac') system(measure_resources_path + 'obFMU_mac', obFMU_xml_file_path, output_path_prefix, coSim_xml_file_path) elsif os.to_s == 'linux' runner.registerInfo("Running obFMU on Linux.") puts 'Running obFMU on Linux.' system('chmod +x ' + measure_resources_path + 'obFMU_linux') system(measure_resources_path + 'obFMU_linux', obFMU_xml_file_path, output_path_prefix, coSim_xml_file_path) end runner.registerInfo("Occupancy schedule simulation successfully completed.") if !File.exist?(external_csv_path) runner.registerError("external_csv_path '#{external_csv_path}' does not exist") return false end # Read schedule back to osm runner.registerInfo("Reading stochastic occupancy schedule back to the osm.") space_ID_map = result_hashes[0] n_occ_hash = result_hashes[1] all_args[1] = space_ID_map all_args[2] = n_occ_hash # Remove all people object (if exist) in the old model model.getPeoples.each do |os_people| os_people.remove end model.getPeopleDefinitions.each do |os_people_def| os_people_def.remove end # Add schedule:file to model model.getSpaces.each do |space| model = set_schedule_for_people(model, space.name.to_s, external_csv_path, userLib, all_args) end runner.registerInfo("Occupancy schedule updated.") # report final condition of model runner.registerFinalCondition("End.") return true end end # register the measure to be used by the application OccupancySimulator.new.registerWithApplication
benlellouch/AlphaBuilding-SyntheticDataset
code/OpenStudio-measures/Occupancy_Simulator_Office/resources/UserLibrary.rb
<reponame>benlellouch/AlphaBuilding-SyntheticDataset<gh_stars>10-100 # *** Copyright Notice *** # OS Measures Copyright (c) 2018, The Regents of the University of California, # through Lawrence Berkeley National Laboratory (subject to receipt of any required # approvals from the U.S. Dept. of Energy). All rights reserved. # If you have questions about your rights to use or distribute this software, # please contact Berkeley Lab's Innovation & Partnerships Office at <EMAIL>. # NOTICE. This Software was developed under funding from the U.S. Department of # Energy and the U.S. Government consequently retains certain rights. As such, # the U.S. Government has been granted for itself and others acting on its behalf # a paid-up, nonexclusive, irrevocable, worldwide license in the Software to # reproduce, distribute copies to the public, prepare derivative works, and # perform publicly and display publicly, and to permit other to do so. # **************************** require "csv" class UserLibrary # This class is used to store user pre-defined library def initialize(csvFile) dt = CSV.table(csvFile,:headers=>false) # SpaceType 1 @Office_t1_name = dt[1][0] @Office_t1_OccupancyDensity = dt[2][1] @office_t1_OccupantPercentageManager = dt[3][1] @office_t1_OccupantPercentageAdminitrator = dt[4][1] @office_t1_OccupantPercentageRegularStaff = dt[5][1] @meetingRoom_t1_name = dt[6][0] @meetingRoom_t1_MinimumNumberOfMeetingPerDay = dt[7][1] @meetingRoom_t1_MaximumNumberOfMeetingPerDay = dt[8][1] @meetingRoom_t1_MinimumNumberOfPeoplePerMeeting = dt[9][1] @meetingRoom_t1_MaximumNumberOfPeoplePerMeeting = dt[10][1] @meetingRoom_t1_ProbabilityOf_30_minMeetings = dt[11][1] @meetingRoom_t1_ProbabilityOf_60_minMeetings = dt[12][1] @meetingRoom_t1_ProbabilityOf_90_minMeetings = dt[13][1] @meetingRoom_t1_ProbabilityOf_120_minMeetings = dt[14][1] # SpaceType 2 @Office_t2_name = dt[1][2] @Office_t2_OccupancyDensity = dt[2][3] @office_t2_OccupantPercentageManager = dt[3][3] @office_t2_OccupantPercentageAdminitrator = dt[4][3] @office_t2_OccupantPercentageRegularStaff = dt[5][3] @meetingRoom_t2_name = dt[6][2] @meetingRoom_t2_MinimumNumberOfMeetingPerDay = dt[7][3] @meetingRoom_t2_MaximumNumberOfMeetingPerDay = dt[8][3] @meetingRoom_t2_MinimumNumberOfPeoplePerMeeting = dt[9][3] @meetingRoom_t2_MaximumNumberOfPeoplePerMeeting = dt[10][3] @meetingRoom_t2_ProbabilityOf_30_minMeetings = dt[11][3] @meetingRoom_t2_ProbabilityOf_60_minMeetings = dt[12][3] @meetingRoom_t2_ProbabilityOf_90_minMeetings = dt[13][3] @meetingRoom_t2_ProbabilityOf_120_minMeetings = dt[14][3] # SpaceType 3 @Office_t3_name = dt[1][4] @Office_t3_OccupancyDensity = dt[2][5] @office_t3_OccupantPercentageManager = dt[3][5] @office_t3_OccupantPercentageAdminitrator = dt[4][5] @office_t3_OccupantPercentageRegularStaff = dt[5][5] @meetingRoom_t3_name = dt[6][4] @meetingRoom_t3_MinimumNumberOfMeetingPerDay = dt[7][5] @meetingRoom_t3_MaximumNumberOfMeetingPerDay = dt[8][5] @meetingRoom_t3_MinimumNumberOfPeoplePerMeeting = dt[9][5] @meetingRoom_t3_MaximumNumberOfPeoplePerMeeting = dt[10][5] @meetingRoom_t3_ProbabilityOf_30_minMeetings = dt[11][5] @meetingRoom_t3_ProbabilityOf_60_minMeetings = dt[12][5] @meetingRoom_t3_ProbabilityOf_90_minMeetings = dt[13][5] @meetingRoom_t3_ProbabilityOf_120_minMeetings = dt[14][5] # SpaceType 4 @Office_t4_name = dt[1][6] @Office_t4_OccupancyDensity = dt[2][7] @office_t4_OccupantPercentageManager = dt[3][7] @office_t4_OccupantPercentageAdminitrator = dt[4][7] @office_t4_OccupantPercentageRegularStaff = dt[5][7] @meetingRoom_t4_name = dt[6][6] @meetingRoom_t4_MinimumNumberOfMeetingPerDay = dt[7][7] @meetingRoom_t4_MaximumNumberOfMeetingPerDay = dt[8][7] @meetingRoom_t4_MinimumNumberOfPeoplePerMeeting = dt[9][7] @meetingRoom_t4_MaximumNumberOfPeoplePerMeeting = dt[10][7] @meetingRoom_t4_ProbabilityOf_30_minMeetings = dt[11][7] @meetingRoom_t4_ProbabilityOf_60_minMeetings = dt[12][7] @meetingRoom_t4_ProbabilityOf_90_minMeetings = dt[13][7] @meetingRoom_t4_ProbabilityOf_120_minMeetings = dt[14][7] # SpaceType 5 @Office_t5_name = dt[1][8] @Office_t5_OccupancyDensity = dt[2][9] @office_t5_OccupantPercentageManager = dt[3][9] @office_t5_OccupantPercentageAdminitrator = dt[4][9] @office_t5_OccupantPercentageRegularStaff = dt[5][9] @meetingRoom_t5_name = dt[6][8] @meetingRoom_t5_MinimumNumberOfMeetingPerDay = dt[7][9] @meetingRoom_t5_MaximumNumberOfMeetingPerDay = dt[8][9] @meetingRoom_t5_MinimumNumberOfPeoplePerMeeting = dt[9][9] @meetingRoom_t5_MaximumNumberOfPeoplePerMeeting = dt[10][9] @meetingRoom_t5_ProbabilityOf_30_minMeetings = dt[11][9] @meetingRoom_t5_ProbabilityOf_60_minMeetings = dt[12][9] @meetingRoom_t5_ProbabilityOf_90_minMeetings = dt[13][9] @meetingRoom_t5_ProbabilityOf_120_minMeetings = dt[14][9] # @OccupantBehaviorRules = dt[15][1] @managerTypicalArrivalTime = dt[16][1] @managerArrivalTimeVariation = dt[17][1] @managerTypicalDepartureTime = dt[18][1] @managerDepartureTimeVariation = dt[19][1] @managerTypicalShortTermLeaving = dt[20][1] @managerShortTermLeavingVariation = dt[21][1] @managerTypicalShortTermLeavingDuration = dt[22][1] @managerShortTermLeavingDurationVariation = dt[23][1] @managerPercentOfTimeInSpaceOwnOffice = dt[24][1] @managerAverageStayTimeOwnOffice = dt[25][1] @managerPercentOfTimeInSpaceOtherOffices = dt[26][1] @managerAverageStayTimeOtherOffices = dt[27][1] @managerPercentOfTimeInSpaceMeetingRooms = dt[28][1] @managerAverageStayTimeMeetingRooms = dt[29][1] @managerPercentOfTimeInSpaceAuxiliaryRooms = dt[30][1] @managerAverageStayTimeAuxiliaryRooms = dt[31][1] @managerPercentOfTimeInSpaceOutdoor = dt[32][1] @managerAverageStayTimeOutdoor = dt[33][1] @administratorTypicalArrivalTime = dt[34][1] @administratorArrivalTimeVariation = dt[35][1] @administratorTypicalDepartureTime = dt[36][1] @administratorDepartureTimeVariation = dt[37][1] @administratorTypicalShortTermLeaving = dt[38][1] @administratorShortTermLeavingVariation = dt[39][1] @administratorTypicalShortTermLeavingDuration = dt[40][1] @administratorShortTermLeavingDurationVariation = dt[41][1] @administratorPercentOfTimeInSpaceOwnOffice = dt[42][1] @administratorAverageStayTimeOwnOffice = dt[43][1] @administratorPercentOfTimeInSpaceOtherOffices = dt[44][1] @administratorAverageStayTimeOtherOffices = dt[45][1] @administratorPercentOfTimeInSpaceMeetingRooms = dt[46][1] @administratorAverageStayTimeMeetingRooms = dt[47][1] @administratorPercentOfTimeInSpaceAuxiliaryRooms = dt[48][1] @administratorAverageStayTimeAuxiliaryRooms = dt[49][1] @administratorPercentOfTimeInSpaceOutdoor = dt[50][1] @administratorAverageStayTimeOutdoor = dt[51][1] @regularStaffTypicalArrivalTime = dt[52][1] @regularStaffArrivalTimeVariation = dt[53][1] @regularStaffTypicalDepartureTime = dt[54][1] @regularStaffDepartureTimeVariation = dt[55][1] @regularStaffTypicalShortTermLeaving = dt[56][1] @regularStaffShortTermLeavingVariation = dt[57][1] @regularStaffTypicalShortTermLeavingDuration = dt[58][1] @regularStaffShortTermLeavingDurationVariation = dt[59][1] @regularStaffPercentOfTimeInSpaceOwnOffice = dt[60][1] @regularStaffAverageStayTimeOwnOffice = dt[61][1] @regularStaffPercentOfTimeInSpaceOtherOffices = dt[62][1] @regularStaffAverageStayTimeOtherOffices = dt[63][1] @regularStaffPercentOfTimeInSpaceMeetingRooms = dt[64][1] @regularStaffAverageStayTimeMeetingRooms = dt[65][1] @regularStaffPercentOfTimeInSpaceAuxiliaryRooms = dt[66][1] @regularStaffAverageStayTimeAuxiliaryRooms = dt[67][1] @regularStaffPercentOfTimeInSpaceOutdoor = dt[68][1] @regularStaffAverageStayTimeOutdoor = dt[69][1] @HolidayRules = dt[70][1] @usHolidayNewYearsDay = dt[71][1] @usHolidayMartinLutherKingJrDay = dt[72][1] @usHolidayGeorgeWashingtonsBirthday = dt[73][1] @usHolidayMemorialDay = dt[74][1] @usHolidayIndependenceDay = dt[75][1] @usHolidayLaborDay = dt[76][1] @usHolidayColumbusDay = dt[77][1] @usHolidayVeteransDay = dt[78][1] @usHolidayThanksgivingDay = dt[79][1] @usHolidayChristmasDay = dt[80][1] @customHolidayCustomHoliday_1 = dt[81][1] @customHolidayCustomHoliday_2 = dt[82][1] @customHolidayCustomHoliday_3 = dt[83][1] @customHolidayCustomHoliday_4 = dt[84][1] @customHolidayCustomHoliday_5 = dt[85][1] # Create getters for all instance variables create_getters end # Create getters for all instance variables def create_getters instance_variables.each do |v| define_singleton_method(v.to_s.tr('@','')) do instance_variable_get(v) end end end end # userLib = UserLibrary.new("library.csv") # puts userLib.Office_t5_OccupancyDensity
benlellouch/AlphaBuilding-SyntheticDataset
code/create_workflow.rb
# MIT License # # Copyright (c) [2021] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require '<place_holder>/openstudio-2.9.1/Ruby/openstudio.rb' # Change to the path where OpenStudio is installed require '<place_holder>/openstudio-standards/lib/openstudio-standards.rb' # Change to the path where openstudio-standards is cloned require 'fileutils' require 'parallel' def loadOSM(pathStr) translator = OpenStudio::OSVersion::VersionTranslator.new path = OpenStudio::Path.new(pathStr) model = translator.loadModel(path) if model.empty? raise "Input #{pathStr} is not valid, please check." else model = model.get end return model end def create_single_model(building_type, vintage, climate_zone, osm_directory) model = OpenStudio::Model::Model.new @debug = false epw_file = 'Not Applicable' prototype_creator = Standard.build("#{vintage}_#{building_type}") prototype_creator.model_create_prototype_model(climate_zone, epw_file, osm_directory, @debug, model) end # Generate OpenStudio seed models for synthetic building operation data creation, # create corresponding OpenStudio workflows which later will be used for simulations # @param [Array] building_types: an array of building types to consider # @param [Array] vintages: an array of building vintages to consider # @param [Array] climate_zones: an array of climate zones to consider # @param [String] root_directory: the path to root working directory # @param [String] epws_path: the path to EPW files folder # @param [Hash] hash_climate_epw: a Hash to map climate zones and EPW files # @param [String] measures_dir: the path to OpenStudio measures # @param [Integer] n_runs: number of stochastic occupancy simulation for each OpenStudio model # @param [Integer] efficiency_level: the energy efficiency level (1: low, 2: Standard, 3: high) # @return [Array] v_osw_paths: an array of OpenStudio workflow paths def create_workflows( building_types, vintages, climate_zones, root_directory, epws_path, hash_climate_epw, measures_dir = nil, n_runs = 5, efficiency_level = 2 ) unless File.directory?(File.expand_path(root_directory)) FileUtils.mkdir_p(File.expand_path(root_directory)) end hash_eff_level = { 1 => 'Low', 2 => 'Standard', 3 => 'High', } out_osw_dir = File.expand_path(File.join(root_directory, "3~OSWs", "efficiency_level_#{hash_eff_level[efficiency_level]}")) v_osw_paths = [] building_types.each do |building_type| climate_zones.each do |climate_zone| sub_epws_path = File.expand_path(File.join(epws_path, hash_climate_epw[climate_zone])) vintages.each do |vintage| ## 1. Generate and prepare OSM model_name = building_type + '_' + vintage + '_' + climate_zone.split('-').last.to_s seed_model_folder = File.join(root_directory, '1~seeds', model_name) new_model_folder = File.join(root_directory, '2~processed_models', "efficiency_level_#{hash_eff_level[efficiency_level]}", model_name) old_osm_path = File.expand_path(File.join(seed_model_folder, 'SR1/in.osm')) old_epw_path = File.expand_path(File.join(seed_model_folder, 'SR1/in.epw')) new_osm_path = File.expand_path(File.join(new_model_folder, "#{model_name}.osm")) new_epw_path = File.expand_path(File.join(new_model_folder, "#{model_name}.epw")) ## Create raw building model create_single_model(building_type, vintage, climate_zone, seed_model_folder) ## Process model process_model(old_osm_path, new_osm_path, efficiency_level) FileUtils.mv(old_epw_path, new_epw_path) ## 2. Prepare OSW v_epw_paths = Dir.glob("#{sub_epws_path}/*.epw") v_osw_paths += prepare_all_osws(new_osm_path, v_epw_paths, out_osw_dir, measures_dir, n_runs) end end end f = File.new(File.join(root_directory, "job_efficiency_level_#{hash_eff_level[efficiency_level]}.txt"), "w") f.write(v_osw_paths) f.close return v_osw_paths end def process_model(old_osm_path, new_osm_path, efficiency_level = 2) osm_dir = File.dirname(new_osm_path) unless File.directory?(osm_dir) FileUtils.mkdir_p(osm_dir) end # Do the following: # 1. Change the simulation run period to match weather data model = loadOSM(old_osm_path) model.getSimulationControl.setRunSimulationforSizingPeriods(false) model.getSimulationControl.setRunSimulationforWeatherFileRunPeriods(true) # 2. Enable CO2 simulations # model.getZoneAirContaminantBalance.setCarbonDioxideConcentration(true) # 3. Change the VAV control logic to dual-maximum vav_reheats = model.getAirTerminalSingleDuctVAVReheats vav_reheats.each do |vav_reheat| vav_reheat.setDamperHeatingAction('ReverseWithLimits') end # 4. Change the efficiency level (TBD) model = adjust_efficiency_level(model, efficiency_level) # Save processed model model.save(new_osm_path, true) end def adjust_efficiency_level(model, level = 2) # Efficiency levels: # 1 - low # 2 - standard # 3 - high if level == 2 puts 'Keep the default efficiency level.' return model else if level == 1 puts 'Adjusting to low efficiency level.' factor = 1.25 elsif level == 3 puts 'Adjusting to high efficiency level.' factor = 0.75 end end # 1. Lighting v_light_defs = model.getLightsDefinitions v_light_defs.each do |light_def| old_lpd = light_def.wattsperSpaceFloorArea.to_f light_def.setWattsperSpaceFloorArea(old_lpd * factor) end # 2. MELs v_equip_defs = model.getElectricEquipmentDefinitions v_equip_defs.each do |equip_def| if equip_def.designLevelCalculationMethod == 'Watts/Area' equip_def.setWattsperSpaceFloorArea(equip_def.wattsperSpaceFloorArea.to_f * factor) elsif equip_def.designLevelCalculationMethod == 'EquipmentLevel' equip_def.setDesignLevel(equip_def.designLevel.to_f * factor) end end # 3. Wall insulation v_opaque_materials = model.getStandardOpaqueMaterials v_opaque_materials.each do |opaque_material| opaque_material.setThermalConductivity(opaque_material.thermalConductivity.to_f * factor) end # 4. Windows v_glazing_materials = model.getGlazings v_glazing_materials.each do |glazing_material| glazing_material.setThickness(glazing_material.thickness.to_f / factor) end # 5. Cooling plant v_cooling_coils = model.getCoilCoolingDXTwoSpeeds v_cooling_coils.each do |cooling_coil| cooling_coil.setRatedLowSpeedCOP(cooling_coil.ratedLowSpeedCOP.to_f / factor) cooling_coil.setRatedHighSpeedCOP(cooling_coil.ratedHighSpeedCOP.to_f / factor) end # 6. Heating plant v_heating_coils = model.getCoilHeatingGass v_heating_coils.each do |heating_coil| # Set highest efficiency to be 0.95 heating_coil.setGasBurnerEfficiency([0.95, heating_coil.gasBurnerEfficiency.to_f / factor].min) end v_reheating_coils = model.getCoilHeatingElectrics v_reheating_coils.each do |reheating_coil| reheating_coil.setEfficiency([1, reheating_coil.efficiency.to_f / factor].min) end v_water_heaters = model.getWaterHeaterMixeds v_water_heaters.each do |water_heater| water_heater.setHeaterThermalEfficiency([0.95, water_heater.heaterThermalEfficiency.to_f / factor].min) end # 7. Fans v_fans = model.getFanVariableVolumes v_fans.each do |fan| fan.setFanTotalEfficiency([0.8, fan.fanTotalEfficiency.to_f / factor].min) fan.setMotorEfficiency([0.95, fan.motorEfficiency.to_f / factor].min) end # 8. Pumps v_pumps = model.getPumpConstantSpeeds v_pumps.each do |pump| pump.setMotorEfficiency([0.6, pump.motorEfficiency.to_f / factor].min) end return model end def prepare_single_osw(seed_osm_path, epw_path, measures_dir, osw_path) # Prepare OSW to add dynamic occupancy, lighting, MELs schedules. osw_dir = File.dirname(osw_path) unless File.directory?(osw_dir) FileUtils.mkdir_p(osw_dir) end osw_str = %({ "weather_file": "#{epw_path}", "seed_file": "#{seed_osm_path}", "measure_paths": [ "#{measures_dir}" ], "steps": [ {"arguments": {},"measure_dir_name": "Occupancy_Simulator_Office"}, {"arguments": {},"measure_dir_name": "create_lighting_schedule_from_occupant_count"}, {"arguments": {},"measure_dir_name": "create_mels_schedule_from_occupant_count"}, {"arguments": {},"measure_dir_name": "update_hvac_setpoint_schedule"}, {"arguments": {},"measure_dir_name": "add_demand_controlled_ventilation"}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Site Outdoor Air Drybulb Temperature","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Site Outdoor Air Dewpoint Temperature","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Site Outdoor Air Wetbulb Temperature","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Site Outdoor Air Relative Humidity","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Site Horizontal Infrared Radiation Rate per Area","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Site Day Type Index","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"System Node Pressure","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"System Node Temperature","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"System Node Mass Flow Rate","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"System Node Relative Humidity","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"System Node Relative Humidity","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Zone Mean Air Temperature","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Zone Air Relative Humidity","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Zone Thermostat Heating Setpoint Temperature","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Zone Thermostat Cooling Setpoint Temperature","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Air System Outdoor Air Economizer Status","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Zone Air Terminal VAV Damper Position","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Zone People Occupant Count","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Zone Electric Equipment Electric Power","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Zone Lights Electric Power","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Fan Electric Power","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Fan Air Mass Flow Rate","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Pump Electric Power","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Pump Mass Flow Rate","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddOutputVariable","arguments":{"variable_name":"Zone Mechanical Ventilation Mass Flow Rate","key_value":"*","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"InteriorLights:Electricity","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"InteriorEquipment:Electricity","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"Fans:Electricity","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"ExteriorLights:Electricity","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"Heating:Electricity","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"Cooling:Electricity","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"Gas:HVAC","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"Electricity:HVAC","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"Pumps:Electricity","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"Electricity:Facility","reporting_frequency":"timestep"}}, {"measure_dir_name":"AddMeter","arguments":{"meter_name":"Gas:Facility","reporting_frequency":"timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Site Outdoor Air Drybulb Temperature","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Site Outdoor Air Dewpoint Temperature","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Site Outdoor Air Wetbulb Temperature","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Site Outdoor Air Relative Humidity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Site Horizontal Infrared Radiation Rate per Area","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Site Day Type Index","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"System Node Pressure","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"System Node Temperature","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"System Node Mass Flow Rate","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"System Node Relative Humidity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"System Node Relative Humidity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Zone Mean Air Temperature","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Zone Air Relative Humidity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Zone Thermostat Heating Setpoint Temperature","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Zone Thermostat Cooling Setpoint Temperature","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Air System Outdoor Air Economizer Status","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Zone Air Terminal VAV Damper Position","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Zone People Occupant Count","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Zone Electric Equipment Electric Power","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Zone Lights Electric Power","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Fan Electric Power","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Fan Air Mass Flow Rate","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Pump Electric Power","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Pump Mass Flow Rate","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportVariabletoCSV","arguments":{"variable_name":"Zone Mechanical Ventilation Mass Flow Rate","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"InteriorLights:Electricity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"InteriorEquipment:Electricity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"Fans:Electricity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"ExteriorLights:Electricity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"Heating:Electricity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"Cooling:Electricity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"Gas:HVAC","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"Electricity:HVAC","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"Pumps:Electricity","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"Electricity:Facility","reporting_frequency":"Zone Timestep"}}, {"measure_dir_name":"ExportMetertoCSV","arguments":{"meter_name":"Gas:Facility","reporting_frequency":"Zone Timestep"}} ] }) f = File.new(osw_path, "w") f.write(osw_str) f.close end def prepare_all_osws(seed_osm_path, v_epw_paths, out_osw_dir, measures_dir, n_runs) # seed_osm_path - seed OS model # v_epw_paths - array of epw paths # out_osw_dir - directory where osw will be grouped and saved by each year's epw # measures_dir - directory where OS measures are saved # n_runs - i.e. n_runs of occupancy simulator runs for each epw v_osw_paths = [] seed_osm_name = File.basename(seed_osm_path, ".osm") v_epw_paths.each do |epw_path| epw_name = File.basename(epw_path, ".epw") year = epw_name[-2..-1] for i in 1..n_runs temp_osw_path = "#{out_osw_dir}/#{seed_osm_name}/#{epw_name}/run_#{i}/#{seed_osm_name}_run_#{i}.osw" prepare_single_osw(seed_osm_path, epw_path, measures_dir, temp_osw_path) v_osw_paths << temp_osw_path end end v_osw_paths end def run_osws(os_exe, v_osw_paths, number_of_threads) n = v_osw_paths.length Parallel.each_with_index(v_osw_paths, :in_threads => number_of_threads) do |osw_path, index| puts "Running #{index + 1}/#{n}" command = "#{os_exe} run -w '#{osw_path}'" puts command system command end end ################################################################################ ## Main: set the run configurations for synthetic operation data generation ################################################################################ # Step 0. Set the working directories (no need to change if you cloned the repository) root_directory = './Models/' measures_dir = './OpenStudio-measures' epws_path = './EPWs' # Step 1. Select the climate zone(s) for simulation. climate_zones = [ 'ASHRAE 169-2006-1A', # 'ASHRAE 169-2006-2A', # 'ASHRAE 169-2006-2B', # 'ASHRAE 169-2006-3A', # 'ASHRAE 169-2006-3B', 'ASHRAE 169-2006-3C', # 'ASHRAE 169-2006-4A', # 'ASHRAE 169-2006-4B', # 'ASHRAE 169-2006-4C', 'ASHRAE 169-2006-5A', # 'ASHRAE 169-2006-5B', # 'ASHRAE 169-2006-6A', # 'ASHRAE 169-2006-6B', # 'ASHRAE 169-2006-7A', # 'ASHRAE 169-2006-8A', ] # Step 2. Make sure you have the weather files (EPWs) and map the their folder # to the climate zones following the example convention hash_climate_epw = { # 'climate zone option' => 'EPWs folder name', (example convention) 'ASHRAE 169-2006-1A' => 'Miami_AMY', 'ASHRAE 169-2006-3C' => 'SF_AMY', 'ASHRAE 169-2006-5A' => 'Chicago_AMY', } # Step 3. Select the vintages you want to consider vintages = [ # '90.1-2004', # '90.1-2007', # '90.1-2010', '90.1-2013' ] # Step 4. Select the building type to consider. # Please note that occupancy_simulator only works for office buildings. building_types = [ ############################################################### ## building types that support stochastic occupancy simulation ############################################################### # 'SmallOffice', # 'MediumOffice', # 'LargeOffice', # 'SmallOfficeDetailed', 'MediumOfficeDetailed', # 'LargeOfficeDetailed', ############################################################### ## building types that do not support stochastic occupancy simulation ############################################################### # 'SecondarySchool', # 'PrimarySchool', # 'SmallHotel', # 'LargeHotel', # 'Warehouse', # 'RetailStandalone', # 'RetailStripmall', # 'QuickServiceRestaurant', # 'FullServiceRestaurant', # 'MidriseApartment', # 'HighriseApartment', # 'Hospital', # 'Outpatient', ] # Step 5. Set the number of stochastic occupancy simulations for each building model. number_of_stochastic_occupancy_simulation = 5 # Step 6. Set the energy efficiency level (1 - low, 2 - standard, 3 - high) to run. efficiency_level = 2 starting = Time.now v_osws = create_workflows(building_types = building_types, vintages = vintages, climate_zones = climate_zones, root_directory = root_directory, epws_path = epws_path, hash_climate_epw = hash_climate_epw, measures_dir = measures_dir, n_runs = number_of_stochastic_occupancy_simulation, efficiency_level = efficiency_level) run_osws( 'os291', # Change this to your command name of OpenStudio 2.9.1. v_osws, # The array of OpenStudio workflows generated in the previous step. 31 # Change this number to set number of threads for parallel simulations. ) ending = Time.now elapsed = ending - starting puts "Job started at #{starting}, finished at #{Time.now}, #{elapsed} seconds elapsed."
benlellouch/AlphaBuilding-SyntheticDataset
code/OpenStudio-measures/ExportMetertoCSV/tests/ExportMetertoCSV_test.rb
<reponame>benlellouch/AlphaBuilding-SyntheticDataset require 'openstudio' require 'openstudio/ruleset/ShowRunnerOutput' require 'minitest/autorun' require 'fileutils' require_relative '../measure.rb' class ExportOutputMetertoCSV_Test < MiniTest::Test def model_path return "#{File.dirname(__FILE__)}/example_model.osm" end def run_dir return "#{File.dirname(__FILE__)}/example_model/" end def sql_path return "#{File.dirname(__FILE__)}/example_model/ModelToIdf/EnergyPlus-0/eplusout.sql" end def report_path return "#{File.dirname(__FILE__)}/report.html" end # create test files if they do not exist when the test first runs def setup_test assert(File.exist?(model_path())) if !File.exist?(run_dir()) FileUtils.mkdir_p(run_dir()) end assert(File.exist?(run_dir())) if File.exist?(report_path()) FileUtils.rm(report_path()) end if !File.exist?(sql_path()) puts "Running EnergyPlus" co = OpenStudio::Runmanager::ConfigOptions.new(true) co.findTools(false, true, false, true) wf = OpenStudio::Runmanager::Workflow.new("modeltoidf->energyplus") wf.add(co.getTools()) job = wf.create(OpenStudio::Path.new(run_dir), OpenStudio::Path.new(model_path())) rm = OpenStudio::Runmanager::RunManager.new rm.enqueue(job, true) rm.waitForFinished end end def test_ExportMetertoCSV assert(File.exist?(model_path())) if !File.exist?(sql_path()) setup_test() end assert(File.exist?(sql_path())) # create an instance of the measure measure = ExportMetertoCSV.new # create an instance of a runner runner = OpenStudio::Ruleset::OSRunner.new # get arguments arguments = measure.arguments() assert_equal(2, arguments.size) argument_map = OpenStudio::Ruleset.convertOSArgumentVectorToMap(arguments) # set argument values to good values and run the measure meter_name = arguments[0].clone assert(meter_name.setValue("Electricity:Facility")) argument_map["meter_name"] = meter_name reporting_frequency = arguments[1].clone assert(reporting_frequency.setValue("Hourly")) argument_map["reporting_frequency"] = reporting_frequency # set up runner, this will happen automatically when measure is run in PAT or OpenStudio runner.setLastOpenStudioModelPath(OpenStudio::Path.new(model_path())) runner.setLastEnergyPlusSqlFilePath(OpenStudio::Path.new(sql_path())) # delete the output if it exists if File.exist?(report_path()) FileUtils.rm(report_path()) end assert(!File.exist?(report_path())) # temporarily change directory to the run directory and run the measure start_dir = Dir.pwd begin Dir.chdir(run_dir()) # run the measure measure.run(runner, argument_map) result = runner.result show_output(result) assert_equal("Success", result.value.valueName) ensure Dir.chdir(start_dir) end # make sure the report file exists #assert(File.exist?(report_path())) end end
benlellouch/AlphaBuilding-SyntheticDataset
code/OpenStudio-measures/AddOutputVariable/measure.rb
<gh_stars>10-100 #see the URL below for information on how to write OpenStuido measures # http://openstudio.nrel.gov/openstudio-measure-writing-guide #see the URL below for access to C++ documentation on mondel objects (click on "model" in the main window to view model objects) # http://openstudio.nrel.gov/sites/openstudio.nrel.gov/files/nv_data/cpp_documentation_it/model/html/namespaces.html #start the measure class AddOutputVariable < OpenStudio::Ruleset::ModelUserScript #define the name that a user will see, this method may be deprecated as #the display name in PAT comes from the name field in measure.xml def name return "AddOutputVariable" end #define the arguments that the user will input def arguments(model) args = OpenStudio::Ruleset::OSArgumentVector.new #make an argument for the variable name variable_name = OpenStudio::Ruleset::OSArgument::makeStringArgument("variable_name",true) variable_name.setDisplayName("Enter Variable Name.") args << variable_name #make an argument for the electric tariff reporting_frequency_chs = OpenStudio::StringVector.new reporting_frequency_chs << "detailed" reporting_frequency_chs << "timestep" reporting_frequency_chs << "hourly" reporting_frequency_chs << "daily" reporting_frequency_chs << "monthly" reporting_frequency_chs << "runperiod" reporting_frequency = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true) reporting_frequency.setDisplayName("Reporting Frequency.") reporting_frequency.setDefaultValue("hourly") args << reporting_frequency #make an argument for the key_value key_value = OpenStudio::Ruleset::OSArgument::makeStringArgument("key_value",true) key_value.setDisplayName("Enter Key Name.") key_value.setDescription("Enter * for all objects or the full name of a specific object to.") key_value.setDefaultValue("*") args << key_value return args end #end the arguments method #define what happens when the measure is run def run(model, runner, user_arguments) super(model, runner, user_arguments) #use the built-in error checking if not runner.validateUserArguments(arguments(model), user_arguments) return false end #assign the user inputs to variables variable_name = runner.getStringArgumentValue("variable_name",user_arguments) reporting_frequency = runner.getStringArgumentValue("reporting_frequency",user_arguments) key_value = runner.getStringArgumentValue("key_value",user_arguments) #check the user_name for reasonableness if variable_name == "" runner.registerError("No variable name was entered.") return false end #check the user_name for reasonableness if key_value == "" runner.registerInfo("Blank key isn't valid. Changing key to *") key_value == "*" end outputVariables = model.getOutputVariables #reporting initial condition of model starting_spaces = model.getSpaces runner.registerInitialCondition("The model started with #{outputVariables.size} output variable objects.") outputVariable = OpenStudio::Model::OutputVariable.new(variable_name,model) outputVariable.setReportingFrequency(reporting_frequency) outputVariable.setKeyValue(key_value) runner.registerInfo("Adding output variable for #{outputVariable.variableName} reporting #{reporting_frequency}.") runner.registerInfo("Key value for variable is #{outputVariable.keyValue}.") outputVariables = model.getOutputVariables #reporting final condition of model finishing_spaces = model.getSpaces runner.registerFinalCondition("The model finished with #{outputVariables.size} output variable objects.") return true end #end the run method end #end the measure #this allows the measure to be use by the application AddOutputVariable.new.registerWithApplication
benlellouch/AlphaBuilding-SyntheticDataset
code/OpenStudio-measures/update_hvac_setpoint_schedule/Gaussian_Random.rb
class RandomGaussian def initialize(mean = 0.0, sd = 1.0, range = lambda { Kernel.rand }) @mean, @sd, @range = mean, sd, range @next_pair = false end def rand if (@next_pair = !@next_pair) # Compute a pair of random values with normal distribution. # See http://en.wikipedia.org/wiki/Box-Muller_transform theta = 2 * Math::PI * @range.call scale = @sd * Math.sqrt(-2 * Math.log(1 - @range.call)) @g1 = @mean + scale * Math.sin(theta) @g0 = @mean + scale * Math.cos(theta) else @g1 end end end file_name = 'adfasdf.csv' gr = RandomGaussian.new(23.72, 1.19) gr = RandomGaussian.new(22.81, 1.87) for i in 1..1000 do puts gr.rand end
benlellouch/AlphaBuilding-SyntheticDataset
code/OpenStudio-measures/ExportVariabletoCSV/measure.rb
require 'erb' require 'csv' #start the measure class ExportVariabletoCSV < OpenStudio::Ruleset::ReportingUserScript # human readable name def name return "ExportVariabletoCSV" end # human readable description def description return "Exports an OutputVariable specified in the AddOutputVariable OpenStudio measure to a csv file." end # human readable description of modeling approach def modeler_description return "This measure searches for the OutputVariable name in the eplusout sql file and saves it to a csv file." end # define the arguments that the user will input def arguments() args = OpenStudio::Ruleset::OSArgumentVector.new #make an argument for the variable name variable_name = OpenStudio::Ruleset::OSArgument::makeStringArgument("variable_name",true) variable_name.setDisplayName("Enter Variable Name.") args << variable_name #make an argument for the reporting frequency reporting_frequency_chs = OpenStudio::StringVector.new reporting_frequency_chs << "Hourly" reporting_frequency_chs << "Zone Timestep" reporting_frequency = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('reporting_frequency', reporting_frequency_chs, true) reporting_frequency.setDisplayName("Reporting Frequency.") reporting_frequency.setDefaultValue("Hourly") args << reporting_frequency return args end # define what happens when the measure is run def run(runner, user_arguments) super(runner, user_arguments) # use the built-in error checking if !runner.validateUserArguments(arguments(), user_arguments) return false end #assign the user inputs to variables variable_name = runner.getStringArgumentValue("variable_name",user_arguments) reporting_frequency = runner.getStringArgumentValue("reporting_frequency",user_arguments) #check the user_name for reasonableness if variable_name == "" runner.registerError("No variable name was entered.") return false end # get the last model and sql file model = runner.lastOpenStudioModel if model.empty? runner.registerError("Cannot find last model.") return false end model = model.get sqlFile = runner.lastEnergyPlusSqlFile if sqlFile.empty? runner.registerError("Cannot find last sql file.") return false end sqlFile = sqlFile.get model.setSqlFile(sqlFile) # get the weather file run period (as opposed to design day run period) ann_env_pd = nil sqlFile.availableEnvPeriods.each do |env_pd| env_type = sqlFile.environmentType(env_pd) if env_type.is_initialized if env_type.get == OpenStudio::EnvironmentType.new("WeatherRunPeriod") ann_env_pd = env_pd break end end end variable_names = sqlFile.availableVariableNames(ann_env_pd, reporting_frequency) if !variable_names.include? "#{variable_name}" runner.registerError("#{variable_name} is not in sqlFile. Please add an AddOutputVariable reporting measure with this variable and run again.") else headers = ["#{reporting_frequency}"] output_timeseries = {} key_values = sqlFile.availableKeyValues(ann_env_pd, reporting_frequency, variable_name.to_s) if key_values.size == 0 runner.registerError("Timeseries for #{variable_name} did not have any key values. No timeseries available.") end key_values.each do |key_value| timeseries = sqlFile.timeSeries(ann_env_pd, reporting_frequency, variable_name.to_s, key_value.to_s) if !timeseries.empty? timeseries = timeseries.get units = timeseries.units headers << "#{key_value.to_s}:#{variable_name.to_s}[#{units}]" output_timeseries[headers[-1]] = timeseries else runner.registerWarning("Timeseries for #{key_value} #{variable_name} is empty.") end end csv_array = [] csv_array << headers date_times = output_timeseries[output_timeseries.keys[0]].dateTimes values = {} for key in output_timeseries.keys values[key] = output_timeseries[key].values end num_times = date_times.size - 1 for i in 0..num_times date_time = date_times[i] row = [] row << date_time for key in headers[1..-1] value = values[key][i] row << value end csv_array << row end File.open("./report_#{variable_name.delete(' ')}_#{reporting_frequency.delete(' ')}.csv", 'wb') do |file| csv_array.each do |elem| file.puts elem.join(',') end end runner.registerInfo("Output file written to #{File.expand_path('.')}") end # close the sql file sqlFile.close() return true end end # register the measure to be used by the application ExportVariabletoCSV.new.registerWithApplication
benlellouch/AlphaBuilding-SyntheticDataset
code/OpenStudio-measures/update_hvac_setpoint_schedule/measure.rb
# insert your copyright here # see the URL below for information on how to write OpenStudio measures # http://nrel.github.io/OpenStudio-user-documentation/reference/measure_writing_guide/ # start the measure class UpdateHVACSetpointSchedule < OpenStudio::Measure::ModelMeasure @@heating_summer_design_t = 15.56 @@heating_winter_design_t = 21.11 @@heating_default_day_t = 15.56 @@cooling_summer_design_t = 23.89 @@cooling_winter_design_t = 29.44 @@cooling_default_day_t = 23.89 @@default_heating_setpoint_mean = 22.81 @@default_cooling_setpoint_mean = 23.72 @@default_heating_setpoint_stdev = 1.87 @@default_cooling_setpoint_stdev = 1.19 @@default_heating_setpoint_setback = 15.56 @@default_cooling_setpoint_setback = 29.44 @@default_time_on = 6 @@default_time_off = 18 @@default_time_end = 24 # Space type names whose thermostat setpoint will not be changed. @@v_other_space_types = [ 'Office Attic', 'Attic', 'Plenum', 'Plenum Space Type', 'SmallOffice - Corridor', 'SmallOffice - Lobby', 'SmallOffice - Attic', 'SmallOffice - Restroom', 'SmallOffice - Stair', 'SmallOffice - Storage', 'MediumOffice - Corridor', 'MediumOffice - Dining', 'MediumOffice - Restroom', 'MediumOffice - Lobby', 'MediumOffice - Storage', 'MediumOffice - Stair', 'LargeOffice - Corridor', 'LargeOffice - Dining', 'LargeOffice - Restroom', 'LargeOffice - Lobby', 'LargeOffice - Storage', 'LargeOffice - Stair', '' ] # human readable name def name # Measure name should be the title case of the class name. return 'Update HVAC Setpoint schedule' end # human readable description def description return 'This measure helps create a new thermostat for each conditioned thermal zone, and generate random heating and cooling setpoints based on a Gaussin distribution.' end # human readable description of modeling approach def modeler_description return ''' This measure helps create a new thermostat for each conditioned thermal zone, and generate random heating and cooling setpoints based on a Gaussin distribution. ''' end class RandomGaussian def initialize(mean = 0.0, sd = 1.0, range = lambda { Kernel.rand }) @mean, @sd, @range = mean, sd, range @next_pair = false end def rand if (@next_pair = !@next_pair) # Compute a pair of random values with normal distribution. # See http://en.wikipedia.org/wiki/Box-Muller_transform theta = 2 * Math::PI * @range.call scale = @sd * Math.sqrt(-2 * Math.log(1 - @range.call)) @g1 = @mean + scale * Math.sin(theta) @g0 = @mean + scale * Math.cos(theta) else @g1 end end end def addThermostat(model, space, heating_setpoint, heating_setback, cooling_setpoint, cooling_setback, sch_type_lmimit) ''' This function add a dual setpoint thermostat object to the specified space in the model with given heating and cooling setpoint and setback temperatures ''' thermal_zone_name = space.thermalZone.get.nameString schTypeLimits = sch_type_lmimit # # 0. Create new ScheduleTypeLimits # schTypeLimits = OpenStudio::Model::ScheduleTypeLimits.new(model) # schTypeLimits.setName('Tempearture') # schTypeLimits.setNumericType('Continuous') # schTypeLimits.setUnitType('Temperature') # 1. Create new OS:Schedule:Ruleset for both heating and cooling setpoints h_schRuleSet = OpenStudio::Model::ScheduleRuleset.new(model) h_schRuleSet.setName('Schedule Rule Set for heating setpoint of thermal zone ' + thermal_zone_name) c_schRuleSet = OpenStudio::Model::ScheduleRuleset.new(model) c_schRuleSet.setName('Schedule Rule Set for cooling setpoint of thermal zone ' + thermal_zone_name) # Create the summer and winter design day schedule time_on = OpenStudio::Time.new(0, @@default_time_on, 0, 0) time_off = OpenStudio::Time.new(0, @@default_time_off, 0, 0) time_end = OpenStudio::Time.new(0, @@default_time_end, 0, 0) h_schSummerDesignDay = OpenStudio::Model::ScheduleDay.new(model) h_schWinterDesignDay = OpenStudio::Model::ScheduleDay.new(model) h_schDefaultDay = OpenStudio::Model::ScheduleDay.new(model) h_schSummerDesignDay.setName('Heating conditioned zone summer design day schedule for thermal zone ' + thermal_zone_name) h_schWinterDesignDay.setName('Heating conditioned zone winter design day schedule for thermal zone ' + thermal_zone_name) h_schDefaultDay.setName('Heating conditioned zone default day schedule for thermal zone ' + thermal_zone_name) h_schSummerDesignDay.addValue(time_end, @@heating_summer_design_t) h_schWinterDesignDay.addValue(time_end, @@heating_winter_design_t) h_schRuleSet.defaultDaySchedule.addValue(time_end, @@heating_default_day_t) # check h_schRuleSet.setScheduleTypeLimits(schTypeLimits) h_schRuleSet.setSummerDesignDaySchedule(h_schSummerDesignDay) h_schRuleSet.setWinterDesignDaySchedule(h_schWinterDesignDay) c_schSummerDesignDay = OpenStudio::Model::ScheduleDay.new(model) c_schWinterDesignDay = OpenStudio::Model::ScheduleDay.new(model) c_schDefaultDay = OpenStudio::Model::ScheduleDay.new(model) c_schSummerDesignDay.setName('Cooling conditioned zone summer design day schedule for thermal zone ' + thermal_zone_name) c_schWinterDesignDay.setName('Cooling conditioned zone winter design day schedule for thermal zone ' + thermal_zone_name) c_schRuleSet.defaultDaySchedule.setName('Cooling conditioned zone default day schedule for thermal zone ' + thermal_zone_name) c_schSummerDesignDay.addValue(time_end, @@cooling_summer_design_t) c_schWinterDesignDay.addValue(time_end, @@cooling_winter_design_t) c_schRuleSet.defaultDaySchedule.addValue(time_end, @@cooling_default_day_t) # check c_schRuleSet.setScheduleTypeLimits(schTypeLimits) c_schRuleSet.setSummerDesignDaySchedule(c_schSummerDesignDay) c_schRuleSet.setWinterDesignDaySchedule(c_schWinterDesignDay) # 2. Create new OS:Schedule:Rule ## heating h_schRule = OpenStudio::Model::ScheduleRule.new(h_schRuleSet) h_schRule.setName('Heating Schedule rule for thermal zone' + thermal_zone_name) h_schRule.daySchedule.setName('Zone' + thermal_zone_name + ' Dual setpoints - heating') h_schRule.daySchedule.addValue(time_on, heating_setback) h_schRule.daySchedule.addValue(time_off, heating_setpoint) h_schRule.daySchedule.addValue(time_end, heating_setback) s_date = OpenStudio::Date.new() h_schRule.setStartDate(s_date) h_schRule.setApplyMonday(true) h_schRule.setApplyTuesday(true) h_schRule.setApplyWednesday(true) h_schRule.setApplyThursday(true) h_schRule.setApplyFriday(true) ## cooling c_schRule = OpenStudio::Model::ScheduleRule.new(c_schRuleSet) c_schRule.setName('Cooling Schedule rule for thermal zone' + thermal_zone_name) c_schRule.daySchedule.setName('Zone ' + thermal_zone_name + ' Dual setpoints - cooling') c_schRule.daySchedule.addValue(time_on, cooling_setback) c_schRule.daySchedule.addValue(time_off, cooling_setpoint) c_schRule.daySchedule.addValue(time_end, cooling_setback) s_date = OpenStudio::Date.new() c_schRule.setStartDate(s_date) c_schRule.setApplyMonday(true) c_schRule.setApplyTuesday(true) c_schRule.setApplyWednesday(true) c_schRule.setApplyThursday(true) c_schRule.setApplyFriday(true) # 3. Create new thermostat and Assign heating and cooling setpoint schedule to the thermostat thermostat = OpenStudio::Model::ThermostatSetpointDualSetpoint.new(model) thermostat.setHeatingSetpointTemperatureSchedule(h_schRuleSet) thermostat.setCoolingSetpointTemperatureSchedule(c_schRuleSet) # 4. Set the new thermostat setpoints for the thermostat space.thermalZone.get.setThermostatSetpointDualSetpoint(thermostat) return model end # define the arguments that the user will input def arguments(model) args = OpenStudio::Measure::OSArgumentVector.new # Enable user inputs of the thermostat setpoint distribution heating_setpoint_mean = OpenStudio::Measure::OSArgument.makeDoubleArgument('heating_setpoint_mean', true) cooling_setpoint_mean = OpenStudio::Measure::OSArgument.makeDoubleArgument('cooling_setpoint_mean', true) heating_setpoint_stdev = OpenStudio::Measure::OSArgument.makeDoubleArgument('heating_setpoint_stdev', true) cooling_setpoint_stdev = OpenStudio::Measure::OSArgument.makeDoubleArgument('cooling_setpoint_stdev', true) heating_setpoint_setback = OpenStudio::Measure::OSArgument.makeDoubleArgument('heating_setpoint_setback', true) cooling_setpoint_setback = OpenStudio::Measure::OSArgument.makeDoubleArgument('cooling_setpoint_setback', true) heating_setpoint_mean.setDisplayName('The mean of the heating setpoint temperature.') cooling_setpoint_mean.setDisplayName('The mean of the cooling setpoint temperature.') heating_setpoint_stdev.setDisplayName('The standard deviation of the heating setpoint temperature.') cooling_setpoint_stdev.setDisplayName('The standard deviation of the cooling setpoint temperature.') heating_setpoint_setback.setDisplayName('The heating setback temperature.') cooling_setpoint_setback.setDisplayName('The cooling setback temperature.') heating_setpoint_mean.setDefaultValue(@@default_heating_setpoint_mean) cooling_setpoint_mean.setDefaultValue(@@default_cooling_setpoint_mean) heating_setpoint_stdev.setDefaultValue(@@default_heating_setpoint_stdev) cooling_setpoint_stdev.setDefaultValue(@@default_cooling_setpoint_stdev) heating_setpoint_setback.setDefaultValue(@@default_heating_setpoint_setback) cooling_setpoint_setback.setDefaultValue(@@default_cooling_setpoint_setback) args << heating_setpoint_mean args << cooling_setpoint_mean args << heating_setpoint_stdev args << cooling_setpoint_stdev args << heating_setpoint_setback args << cooling_setpoint_setback return args end # define what happens when the measure is run def run(model, runner, user_arguments) super(model, runner, user_arguments) # use the built-in error checking if !runner.validateUserArguments(arguments(model), user_arguments) return false end # report initial condition of model runner.registerInitialCondition("Start.") heating_setpoint_mean = runner.getDoubleArgumentValue('heating_setpoint_mean', user_arguments) cooling_setpoint_mean = runner.getDoubleArgumentValue('cooling_setpoint_mean', user_arguments) heating_setpoint_stdev = runner.getDoubleArgumentValue('heating_setpoint_stdev', user_arguments) cooling_setpoint_stdev = runner.getDoubleArgumentValue('cooling_setpoint_stdev', user_arguments) heating_setpoint_setback = runner.getDoubleArgumentValue('heating_setpoint_setback', user_arguments) cooling_setpoint_setback = runner.getDoubleArgumentValue('cooling_setpoint_setback', user_arguments) v_space_types = model.getSpaceTypes # Create a schedule type limits for the thermostat setpoints sch_type_lmimit = OpenStudio::Model::ScheduleTypeLimits.new(model) sch_type_lmimit.setName('Tempearture') sch_type_lmimit.setNumericType('Continuous') sch_type_lmimit.setUnitType('Temperature') v_space_types.each do |space_type| if not @@v_other_space_types.include? space_type.standardsSpaceType.to_s v_current_spaces = space_type.spaces v_current_spaces.each do |current_space| puts 'Adding thermostat for '+ current_space.thermalZone.get.nameString heating_setpoint = RandomGaussian.new(heating_setpoint_mean, heating_setpoint_stdev).rand.round(2) heating_setback = heating_setpoint_setback cooling_setpoint = RandomGaussian.new(cooling_setpoint_mean, cooling_setpoint_stdev).rand.round(2) cooling_setback = cooling_setpoint_setback if heating_setpoint >= cooling_setpoint heating_setpoint = @@default_heating_setpoint_mean cooling_setpoint = @@default_cooling_setpoint_mean end model = addThermostat(model, current_space, heating_setpoint, heating_setback, cooling_setpoint, cooling_setback, sch_type_lmimit) end end end # echo the new space's name back to the user runner.registerInfo("New thermostats were added to the spaces") # report final condition of model runner.registerFinalCondition("The building finished with #{model.getSpaces.size} spaces.") return true end end # register the measure to be used by the application UpdateHVACSetpointSchedule.new.registerWithApplication
benlellouch/AlphaBuilding-SyntheticDataset
code/OpenStudio-measures/add_demand_controlled_ventilation/measure.rb
# insert your copyright here # see the URL below for information on how to write OpenStudio measures # http://nrel.github.io/OpenStudio-user-documentation/reference/measure_writing_guide/ # start the measure class AddDemandControlledVentilation < OpenStudio::Measure::ModelMeasure # Standard space types for office rooms @@v_office_space_types = [ 'WholeBuilding - Sm Office', 'WholeBuilding - Md Office', 'WholeBuilding - Lg Office', 'Office', 'ClosedOffice', 'OpenOffice', 'SmallOffice - ClosedOffice', 'SmallOffice - OpenOffice', 'MediumOffice - ClosedOffice', 'MediumOffice - OpenOffice', 'LargeOffice - ClosedOffice', 'LargeOffice - OpenOffice' ] # Standard space types for meeting rooms @@v_conference_space_types = [ 'Conference', 'SmallOffice - Conference', 'MediumOffice - Conference', 'MediumOffice - Classroom', 'LargeOffice - Conference' ] @@oa_per_person_office_default = 0.0025 @@oa_per_area_office_default = 0.0003 @@oa_per_person_conference_default = 0.0025 @@oa_per_area_conference_default = 0.0003 # human readable name def name # Measure name should be the title case of the class name. return 'Add Demand Controlled Ventilation' end # human readable description def description return 'Replace this text with an explanation of what the measure does in terms that can be understood by a general building professional audience (building owners, architects, engineers, contractors, etc.). This description will be used to create reports aimed at convincing the owner and/or design team to implement the measure in the actual building design. For this reason, the description may include details about how the measure would be implemented, along with explanations of qualitative benefits associated with the measure. It is good practice to include citations in the measure if the description is taken from a known source or if specific benefits are listed.' end # human readable description of modeling approach def modeler_description return 'Replace this text with an explanation for the energy modeler specifically. It should explain how the measure is modeled, including any requirements about how the baseline model must be set up, major assumptions, citations of references to applicable modeling resources, etc. The energy modeler should be able to read this description and understand what changes the measure is making to the model and why these changes are being made. Because the Modeler Description is written for an expert audience, using common abbreviations for brevity is good practice.' end def create_design_spec_oa(model, oa_flow_per_person, oa_flow_per_area) oa_design_spec = OpenStudio::Model::DesignSpecificationOutdoorAir.new(model) oa_design_spec.setOutdoorAirMethod('Sum') oa_design_spec.setOutdoorAirFlowperPerson(oa_flow_per_person) oa_design_spec.setOutdoorAirFlowperFloorArea(oa_flow_per_area) return oa_design_spec end # define the arguments that the user will input def arguments(model) args = OpenStudio::Measure::OSArgumentVector.new v_space_types = model.getSpaceTypes v_space_types.each do |space_type| if @@v_office_space_types.include? space_type.standardsSpaceType.to_s oa_per_person_office = OpenStudio::Measure::OSArgument.makeDoubleArgument('oa_per_person_office', true) oa_per_person_office.setDisplayName('Office outdoor air flow rate per person [m3/(s*person)]') oa_per_person_office.setDescription('This value will be used in the mechanical ventilation calculation with DCV.') oa_per_person_office.setDefaultValue(@@oa_per_person_office_default) oa_per_area_office = OpenStudio::Measure::OSArgument.makeDoubleArgument('oa_per_area_office', true) oa_per_area_office.setDisplayName('Office outdoor air flow rate per floor area [m3/(s*m2)]') oa_per_area_office.setDescription('This value will be used in the mechanical ventilation calculation with DCV.') oa_per_area_office.setDefaultValue(@@oa_per_area_office_default) args << oa_per_person_office args << oa_per_area_office elsif @@v_conference_space_types.include? space_type.standardsSpaceType.to_s oa_per_person_conference = OpenStudio::Measure::OSArgument.makeDoubleArgument('oa_per_person_conference', true) oa_per_person_conference.setDisplayName('Conference outdoor air flow rate per person [m3/(s*person)]') oa_per_person_conference.setDescription('This value will be used in the mechanical ventilation calculation with DCV.') oa_per_person_conference.setDefaultValue(@@oa_per_person_conference_default) oa_per_area_conference = OpenStudio::Measure::OSArgument.makeDoubleArgument('oa_per_area_conference', true) oa_per_area_conference.setDisplayName('Conference outdoor air flow rate per floor area [m3/(s*m2)]') oa_per_area_conference.setDescription('This value will be used in the mechanical ventilation calculation with DCV.') oa_per_area_conference.setDefaultValue(@@oa_per_area_conference_default) args << oa_per_person_conference args << oa_per_area_conference end end return args end # define what happens when the measure is run def run(model, runner, user_arguments) super(model, runner, user_arguments) # use the built-in error checking if !runner.validateUserArguments(arguments(model), user_arguments) return false end # assign the user inputs to variables oa_per_person_office = @@oa_per_person_office_default oa_per_area_office = @@oa_per_area_office_default oa_per_person_conference = @@oa_per_person_conference_default oa_per_area_conference = @@oa_per_area_conference_default v_space_types = model.getSpaceTypes v_space_types.each do |space_type| if @@v_office_space_types.include? space_type.standardsSpaceType.to_s oa_per_person_office = runner.getDoubleArgumentValue('oa_per_person_office', user_arguments) oa_per_area_office = runner.getDoubleArgumentValue('oa_per_area_office', user_arguments) # check the arguments for reasonableness if oa_per_person_office.nan? runner.registerError('Office outdoor air flow rate per person was missing.') return false end if oa_per_area_office.nan? runner.registerError('Office outdoor air flow rate per person was missing.') return false end elsif @@v_conference_space_types.include? space_type.standardsSpaceType.to_s oa_per_person_conference = runner.getDoubleArgumentValue('oa_per_person_conference', user_arguments) oa_per_area_conference = runner.getDoubleArgumentValue('oa_per_area_conference', user_arguments) if oa_per_person_conference.nan? runner.registerError('Conference outdoor air flow rate per person was missing.') return false end if oa_per_area_conference.nan? runner.registerError('Conference outdoor air flow rate per person was missing.') return false end end end # report initial condition of model runner.registerInitialCondition("Measure starts.") # Add DesignSpecificationOutdoorAir to spaces v_spaces = model.getSpaces v_spaces.each do |space| if @@v_office_space_types.include? space.spaceType.get.standardsSpaceType.to_s oa_design_spec = create_design_spec_oa(model, oa_per_person_office, oa_per_area_office) space.setDesignSpecificationOutdoorAir(oa_design_spec) runner.registerInfo("Created new design specification outdoor air for: #{space.name}.") elsif @@v_conference_space_types.include? space.spaceType.get.standardsSpaceType.to_s oa_design_spec = create_design_spec_oa(model, oa_per_person_conference, oa_per_area_conference) space.setDesignSpecificationOutdoorAir(oa_design_spec) runner.registerInfo("Created new design specification outdoor air for: #{space.name}.") end end # Enbable DCV v_OA_controllers = model.getControllerMechanicalVentilations v_OA_controllers.each do |oa_controller| runner.registerInfo("DCV for controller: #{oa_controller.name} was enabled.") oa_controller.setDemandControlledVentilation(true) end # puts v_spaces # # report final condition of model runner.registerFinalCondition("New DesignSpecificationOutdoorAir objects are added, DCV are enabled.") return true end end # register the measure to be used by the application AddDemandControlledVentilation.new.registerWithApplication
benlellouch/AlphaBuilding-SyntheticDataset
code/OpenStudio-measures/Occupancy_Simulator_Office/tests/test.rb
# *** Copyright Notice *** # OS Measures Copyright (c) 2018, The Regents of the University of California, # through Lawrence Berkeley National Laboratory (subject to receipt of any required # approvals from the U.S. Dept. of Energy). All rights reserved. # If you have questions about your rights to use or distribute this software, # please contact Berkeley Lab's Innovation & Partnerships Office at <EMAIL>. # NOTICE. This Software was developed under funding from the U.S. Department of # Energy and the U.S. Government consequently retains certain rights. As such, # the U.S. Government has been granted for itself and others acting on its behalf # a paid-up, nonexclusive, irrevocable, worldwide license in the Software to # reproduce, distribute copies to the public, prepare derivative works, and # perform publicly and display publicly, and to permit other to do so. # **************************** require 'openstudio' # Note: The measure is available with OpenStuio >= 2.7.0 require 'openstudio/ruleset/ShowRunnerOutput' require 'minitest/autorun' require_relative '../measure.rb' require 'fileutils' require 'openstudio-standards.rb' class OccupancySimulatorTest < Minitest::Test def create_model(building_type, vintage, climate_zone, osm_directory) model = OpenStudio::Model::Model.new @debug = false epw_file = 'Not Applicable' prototype_creator = Standard.build("#{vintage}_#{building_type}") prototype_creator.model_create_prototype_model(climate_zone, epw_file, osm_directory, @debug, model) end def setup # Create a small office reference model for the testing path = File.dirname(__FILE__) building_type = 'SmallOffice' vintage = '90.1-2004' climate_zone = 'ASHRAE 169-2006-1A' osm_directory = path create_model(building_type, vintage, climate_zone, osm_directory) # Move the model to the test main folder FileUtils.mv(path + '/SR1/in.osm', path + '/test_model.osm') FileUtils.mv(path + '/SR1/in.idf', path + '/test_model.idf') FileUtils.mv(path + '/SR1/in.epw', path + '/test_model.epw') end def test_argument_size_and_default_values # load the test model generated in the setup translator = OpenStudio::OSVersion::VersionTranslator.new path = File.dirname(__FILE__) path = OpenStudio::Path.new(File.dirname(__FILE__) + "/test_model.osm") model = translator.loadModel(path) assert((not model.empty?)) model = model.get # create an instance of the measure measure = OccupancySimulator.new # get arguments and test that they are what we are expecting arguments = measure.arguments(model) argument_map = OpenStudio::Measure::convertOSArgumentVectorToMap(arguments) # Test the size of the arguments assert_equal(6, arguments.size) # Test the default values of the arguments args_hash = {} args_hash['Space_1_Perimeter_ZN_1'] = 'Office Type 1' args_hash['Space_2_Perimeter_ZN_2'] = 'Office Type 1' args_hash['Space_3_Perimeter_ZN_3'] = 'Office Type 1' args_hash['Space_4_Perimeter_ZN_4'] = 'Office Type 1' args_hash['Space_5_Core_ZN'] = 'Office Type 1' args_hash['Space_6_Attic'] = 'Other' arguments.each do |arg| arg_temp = arg.clone if args_hash[arg.name] assert(arg_temp.setValue(args_hash[arg.name])) end argument_map[arg.name] = arg_temp end end def test_measure_run # load the test model generated in the setup translator = OpenStudio::OSVersion::VersionTranslator.new path = File.dirname(__FILE__) path = OpenStudio::Path.new(File.dirname(__FILE__) + "/test_model.osm") model = translator.loadModel(path) assert((not model.empty?)) model = model.get # create an instance of the measure measure = OccupancySimulator.new # create an instance of a runner runner = OpenStudio::Ruleset::OSRunner.new # get arguments and test that they are what we are expecting arguments = measure.arguments(model) argument_map = OpenStudio::Measure::convertOSArgumentVectorToMap(arguments) assert(measure.run(model, runner, argument_map)) v_schedule_files = model.getScheduleFiles assert_equal(5, v_schedule_files.length) end def teardown FileUtils.rm_f('./OccSimulator_out_IDF.csv') FileUtils.rm_rf('./SR1') FileUtils.rm_f('./SR1') end end
sferik/rainbow
lib/rainbow.rb
require 'rainbow/global' require 'rainbow/legacy' require 'rainbow/ext/string' module Rainbow def self.new Wrapper.new(global.enabled) end self.enabled = false unless STDOUT.tty? && STDERR.tty? self.enabled = false if ENV['TERM'] == 'dumb' self.enabled = true if ENV['CLICOLOR_FORCE'] == '1' # On Windows systems, try to load the local ANSI support library require 'rbconfig' if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ begin require 'Win32/Console/ANSI' rescue LoadError self.enabled = false end end end
sferik/rainbow
lib/rainbow/version.rb
<reponame>sferik/rainbow module Rainbow VERSION = "1.99.1".freeze end
HTW-Webtech/ai-webtech-admin-app
app/controllers/admin/review_dates_controller.rb
<filename>app/controllers/admin/review_dates_controller.rb module Admin class ReviewDatesController < BaseController def new end # TODO: will_paginate? def index @past_dates = ReviewDate.past @upcoming_dates = ReviewDate.upcoming end def show @review_date = ReviewDate.includes(users: [:apps]).find(params[:id]) @user_apps = @review_date.user_apps end def confirm @review_date = ReviewDate.find(params[:id]) points = params[:review_date][:review_points] user_id = params[:review_date][:user_id] @review_date.confirm points, user_id redirect_to :back, notice: "Erfolgreich #{@review_date.review_points} Punkte eingetragen." end def revoke @review_date = ReviewDate.find(params[:id]) @review_date.revoke redirect_to :back, notice: "Review zurückgesetzt." end def create dates = review_dates.each &:save! dates.each { |date| Email::ReviewDatesMailer.new(review_date: date).run } redirect_to :back, notice: "Created #{dates.count} new Review Dates." end private def review_dates begins_at = start_time groups_without_review_date.map do |group| ReviewDate.new(review_group: group, exercise_id: exercise_id, begins_at: begins_at, length_in_minutes: length_in_minutes).tap do begins_at += length_in_minutes.minutes end end end def groups_without_review_date ReviewGroup.without_date_for_exercise(exercise_id).where(order: order).limit(groups_limit) end def start_time Time.new(date_year, date_month, date_day, date_hour, date_minutes) end def date_year params[:review_date]['date(1i)'].to_i end def date_month params[:review_date]['date(2i)'].to_i end def order params[:review_date][:order] end def date_day params[:review_date]['date(3i)'].to_i end def date_hour params[:review_date]['start_time(4i)'].to_i end def date_minutes params[:review_date]['start_time(5i)'].to_i end def groups_limit params[:review_date][:group_count].to_i end def exercise_id params[:review_date][:exercise_id].to_i end def length_in_minutes params[:review_date][:length_in_minutes].to_i end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160510163519_add_unique_condition_to_review_dates_and_groups.rb
<gh_stars>0 class AddUniqueConditionToReviewDatesAndGroups < ActiveRecord::Migration def change add_index :review_dates, [:review_group_id, :exercise_id], unique: true end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160508230109_add_length_to_review_date.rb
<reponame>HTW-Webtech/ai-webtech-admin-app class AddLengthToReviewDate < ActiveRecord::Migration def change add_column :review_dates, :length_in_minutes, :integer, null: false, default: 10 end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20151126170255_add_review_points.rb
class AddReviewPoints < ActiveRecord::Migration def change add_column :apps, :review_points, :integer, default: 0, null: false end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/admin/students_controller.rb
module Admin class StudentsController < BaseController def show @students = current_course.students.includes(:apps) @exercise_ids = ExercisePointMaster.new(current_course).exercise_ids end end end
HTW-Webtech/ai-webtech-admin-app
app/models/user/appraisal.rb
class User < ActiveRecord::Base class Appraisal attr_accessor :user, :course def initialize(user, course: Courses.current) @user = user @course = course end def percentage [ 100 * user.total_points.to_f/course.total_points.to_f, 100].min.round end GRADES = { (0...50) => 5.0, (50...55) => 4.0, (55...60) => 3.7, (60...65) => 3.3, (65...70) => 3.0, (70...75) => 2.7, (75...80) => 2.3, (80...85) => 2.0, (85...90) => 1.7, (90...95) => 1.3, (95..100) => 1.0, } def grade GRADES.detect { |range, _| range.include?(percentage) }.last end end end
HTW-Webtech/ai-webtech-admin-app
app/models/email/review_dates_mailer.rb
module Email class ReviewDatesMailer attr_accessor :review_date def initialize(review_date:) @review_date = review_date end def subject "Neuer CodeReview-Termin am #{formatted_date}" end def message "Es wurde gerade für die #{exercise_id}te Aufgabe ein neuer CodeReview-Temin am #{formatted_date} eingetragen. Mehr Infos im Aris dazu." end def run users.each do |user| ApplicationMailer.sent_email( email: user.email, subject: subject, body: message, ).deliver_now! end Notifier.notify "Review-Date Email '#{subject}' verschickt an: #{users.map(&:email).join(', ')}" end def users review_date.users end def exercise_id review_date.exercise_id end def formatted_date review_date.formatted_begins_at end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20151125045822_remove_app_id_from_name.rb
class RemoveAppIdFromName < ActiveRecord::Migration class App < ActiveRecord::Base end def up remove_index :apps, :name App.find_each do |app| next unless !!app.name.match(/\d+-\w+/) app.update! name: app.name.match(/\d-(.+)/)[1] end end def down add_index :apps, :name, unique: true end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160413150840_add_summer2016_group.rb
class AddSummer2016Group < ActiveRecord::Migration def up ss2016 = Group.create(name: 'SS2016') User.where('created_at > ?', [3.weeks.ago]).each do |user| ss2016.users << user end end def down Group.where(name: 'SS2016').delete_all end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20151011104841_create_exercise_results.rb
class CreateExerciseResults < ActiveRecord::Migration def change create_table :exercise_results do |t| t.integer :app_id, null: false t.integer :exercise_id, null: false t.integer :failures_count, null: false, default: -1 t.timestamps null: false end end end
HTW-Webtech/ai-webtech-admin-app
app/models/app.rb
require 'securerandom' class App < ActiveRecord::Base validates :user, presence: true validates :external_url, url: true, allow_blank: true belongs_to :user has_many :exercise_results has_one :feedback def self.for_permalink_or_id(permalink_or_id) id = permalink_or_id.to_s.split('-').first find(id) end def self.reviewed where.not(reviewed_at: nil) end # TODO: remove user dependency def prefill self.name ||= AppName.generate_unique self.ssh_key ||= user.ssh_key if user self.exercise_id ||= Exercise.generate_next_id(user) self end def permalink "#{id}-#{name}" end def display_name permalink end def reloading? File.exists? semaphore_file_path end def ready? !reloading? end def update_exercise_points(points) if exercise_points < 1 Email::AppPointsMailer.new(app: self, points: points).run end update exercise_points: points end def semaphore_file_path Rails.root + "tmp/#{permalink}-reloading" end def exercise_name ExercisePointMaster.new(course).exercise_name(exercise_id) end def tests_passed? exercise_points > 0 end def has_tests? achievable_exercise_points > 0 end def total_points exercise_points + review_points end def achievable_total_points achievable_exercise_points + achievable_review_points end def achievable_exercise_points ExercisePointMaster.new(course).points_for_exercise(exercise_id) end def achievable_review_points ReviewPoints.new(course).achievable(self) end def course if user "Courses::#{user.course}".constantize end end def reviewed? reviewed_at.present? end # TODO: Extract me def jenkins_url "http://#{cc(:site).jenkins_hostname}/job/#{permalink}/" end def testing_url if external_hosting? external_url else public_url end end def git_webview_url "http://#{cc(:site).git_webview_hostname}/#{permalink}/commits/master" end def publish_to_app_service ArisService.publish(self) end def publish_to_jenkins_service JenkinsService.publish(self) end # TODO: Move in some view helper def view_git_clone_host "ssh://#{permalink}@#{cc(:site).git_hostname}/var/apps/#{permalink}/code" end def public_url "http://#{permalink}.#{cc(:site).app_hostname}" end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/admin/emails_controller.rb
<filename>app/controllers/admin/emails_controller.rb module Admin class EmailsController < BaseController def new end def create scheduler = Email::Scheduler.new( group: group_or_review_group!, subject: email_params[:subject], body: email_params[:body] ) if scheduler.run redirect_to new_admin_email_path, notice: "#{scheduler.mails.count} Mail(s) have been sent." else render :new, alert: 'Mails have not been fully sent' end end private def group_or_review_group! group_or_review_group or raise(ArgumentError, "You have to select either a group or review group") end def group_or_review_group group || review_group end def review_group ReviewGroup.where(id: email_params[:review_group_id]).first end def group Group.where(id: email_params[:group_id]).first end def email_params params.require(:email).permit(:group_id, :review_group_id, :subject, :body) end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160420185752_fix_winter_course_user.rb
<reponame>HTW-Webtech/ai-webtech-admin-app class FixWinterCourseUser < ActiveRecord::Migration def up winter = Group.where(name: 'Winter2015').first winter.users = User.where('created_at < ?', [10.weeks.ago]) end def down # noop end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160504172614_add_course_to_app.rb
<gh_stars>0 class AddCourseToApp < ActiveRecord::Migration def up add_column :apps, :course, :string App.includes(:user).find_each do |app| app.update course: app.user.course end change_column :apps, :course, :string, null: false end def down remove_column :apps, :course, :string end end
HTW-Webtech/ai-webtech-admin-app
app/models/user/app_limit.rb
class User < ActiveRecord::Base module AppLimit module_function def limit_reached?(user, course = Courses.current) return false if user.admin? # TODO: Attach course to the user! user.apps.count >= course.exercises.count end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20150918074851_create_apps.rb
class CreateApps < ActiveRecord::Migration def change create_table :apps do |t| t.string :name, null: false t.string :ssh_key, null: false t.string :pg_host, default: 'localhost', null: false t.string :pg_database, null: false t.string :pg_login, null: false t.string :pg_passwd, null: false t.text :env_vars t.integer :user_id, null: false t.integer :exercise_id, null: false t.datetime :reviewed_at t.datetime :exercise_passed_at t.timestamps null: false end add_index :apps, :name, unique: true end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160512074845_add_slot_to_review_group.rb
class AddSlotToReviewGroup < ActiveRecord::Migration def change add_column :review_groups, :order, :integer, default: 0, null: false end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/apiv1/exercise_results_controller.rb
module Apiv1 class ExerciseResultsController < BaseController def create exercise_result = json_body['exercise_result'] if exercise_result['success'] == true app = App.for_permalink_or_id(exercise_result['app_name']) exercise_id = exercise_result['exercise_id'].to_i result = ExerciseResult.new(app: app, exercise_id: exercise_id) if result.save! ExercisePointMaster.new(app.course).evaluate!(result) render json: JSON.generate({ status: 'ok' }) else render json: JSON.parse({ status: 'error', result: result.errors.to_s }) end else render json: JSON.parse({ status: 'error', result: 'success was false' }) end end def json_body @body ||= request.body.read JSON.parse(@body) end end end
HTW-Webtech/ai-webtech-admin-app
spec/models/app_spec.rb
require 'rails_helper' describe App do subject { described_class.new(id: 1, name: 'funny-capybara') } describe '#public_url' do before do allow(subject).to receive(:cc).with(:site).and_return(double('Site', app_hostname: 'foo.bar')) end it 'returns the correct url' do expect(subject.public_url).to eq 'http://1-funny-capybara.foo.bar' end end end
HTW-Webtech/ai-webtech-admin-app
app/models/courses/winter2015.rb
<gh_stars>0 module Courses class Winter2015 < Base def self.exercises { 1 => [ 2, Date.new(2015, 11, 27) ], 2 => [ 2, Date.new(2015, 11, 24) ], 3 => [ 4, Date.new(2015, 12, 14) ], 4 => [ 2, Date.new(2016, 1, 12) ], 5 => [ 0, Date.current ], } end def self.exercise_names { } end def self.review_points { 1 => (0..2), 2 => (0..2), 3 => (0..4), 4 => (0..0), 5 => (0..16), } end end end
HTW-Webtech/ai-webtech-admin-app
spec/factories/app_factory.rb
<reponame>HTW-Webtech/ai-webtech-admin-app FactoryGirl.define do factory :app do name { AppName.generate_unique } association :user end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/admin/base_controller.rb
<filename>app/controllers/admin/base_controller.rb module Admin class BaseController < ::ApplicationController before_action :authenticate_user! before_action :redirect_non_admin_user before_action :set_current_course private def set_current_course if current_course = params[:current_course] || session[:current_course] @current_course = Courses.find current_course session[:current_course] = current_course end end def redirect_non_admin_user if !current_user.admin? redirect_to user_path(current_user) end end def current_course @current_course ||= Courses.current end end end
HTW-Webtech/ai-webtech-admin-app
app/models/notifier.rb
<filename>app/models/notifier.rb class Notifier def self.notifier @notifier ||= Slack::Notifier.new ENV.fetch('SLACK_WEBHOOK_URL'), channel: '#app-notifications', username: 'app-bot' end def self.notify(message) return unless Rails.env.production? notifier.ping message end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160403171727_prefill_timestamp_columns_for_users.rb
class PrefillTimestampColumnsForUsers < ActiveRecord::Migration def up execute <<-SQL UPDATE users SET created_at = '2015-10-01 12:00:00', updated_at = '2015-10-01 12:00:00' SQL change_column :users, :created_at, :datetime, null: false change_column :users, :updated_at, :datetime, null: false end def down change_column :users, :created_at, :datetime, null: true change_column :users, :updated_at, :datetime, null: true execute <<-SQL UPDATE users SET created_at = NULL, updated_at = NULL SQL end end
HTW-Webtech/ai-webtech-admin-app
app/validators/url_validator.rb
<gh_stars>1-10 class UrlValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) record.errors[attribute] << (options[:message] || "must be a valid URL") unless url_valid?(value) end # a URL may be technically well-formed but may # not actually be valid, so this checks for both. def url_valid?(url) url = URI.parse(url) rescue false url.kind_of?(URI::HTTP) || url.kind_of?(URI::HTTPS) end end
HTW-Webtech/ai-webtech-admin-app
app/models/courses/base.rb
<reponame>HTW-Webtech/ai-webtech-admin-app module Courses class Base def self.exercises { 1 => [ 2, Date.current ] } end def self.exercise_names_with_review ids = review_points.select { |_, points| points.max > 0 }.map(&:first) exercise_names.select { |exercise_id, _| ids.include?(exercise_id) } end def self.apps App.where(course: display_name) end def self.display_name name.demodulize end def self.students Group.where(name: display_name).first.users end def self.review_points { 1 => (0..5) } end def self.total_test_points exercises.values.sum(&:first) end def self.total_review_points review_points.values.sum(&:max) end def self.total_points total_test_points + total_review_points end end end require 'courses/winter2015' require 'courses/summer2016'
HTW-Webtech/ai-webtech-admin-app
spec/factories/exercise_result_factory.rb
FactoryGirl.define do factory :exercise_result do association :app exercise_id 1 end end
HTW-Webtech/ai-webtech-admin-app
app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base default from: "no-reply@#{cc(:site).hostname}" def sent_email(email:, subject:, body:, bcc: '') mail to: email, bcc: bcc, subject: subject, body: body, layout: 'email/base' end end
HTW-Webtech/ai-webtech-admin-app
app/models/exercise_result.rb
class ExerciseResult < ActiveRecord::Base belongs_to :app end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160420111351_rename_course_groups.rb
<reponame>HTW-Webtech/ai-webtech-admin-app class RenameCourseGroups < ActiveRecord::Migration def up Group.where(name: 'SS2016').update_all(name: 'Summer2016') Group.where(name: 'WS2015').update_all(name: 'Winter2015') end def down Group.where(name: 'Summer2016').update_all(name: 'SS2016') Group.where(name: 'Winter2015').update_all(name: 'WS2015') end end
HTW-Webtech/ai-webtech-admin-app
app/models/statistics/students_points.rb
<filename>app/models/statistics/students_points.rb # Point-Overview for all students # students.each do |student| # points["exercises"]["1"]["students"][student.id]["total_points"] => 6 # points["exercises"]["1"]["students"][student.id]["review_points"] => 2 # points["exercises"]["1"]["students"][student.id]["test_points"] => 4 # end # # { # "exercises" => { # "1" => { # "students" => { # "1" => { # "total_points" => 6, # "review_points" => 2, # "test_points" => 4 # }, # "2" => { # "total_points" => 4, # "review_points" => 0, # "test_points" => 4 # } # } # } # } # } module Statistics class StudentsPoints attr_accessor :students def initialize(students) @students = students end def to_json data.to_json end def data @data ||= begin exercise_ids.each_with_object({}) do |exercise_id, h| h['exercises'] ||= {} h['exercises'][exercise_id] = students_points(exercise_id) end end end def students_points(exercise_id) students.each_with_object({}) do |student, h| sh = h['students'] = {} app = student.apps.detect { |app| app.exercise_id == exercise_id } || App.new sh[student.id] = { "total_points" => app.total_points, "review_points" => app.review_points, "exercise_points" => app.exercise_points } end end def exercise_ids ExercisePointMaster.exercise_ids end end end
HTW-Webtech/ai-webtech-admin-app
spec/models/app_name_spec.rb
<filename>spec/models/app_name_spec.rb require 'rails_helper' RSpec.describe AppName do describe '.generate_unique' do it 'creates a name beginning with the probably upcoming sequential id' do expect(described_class.generate_unique).to match /.+-.+/ end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20151126172142_migrate_already_reviewed_apps.rb
<reponame>HTW-Webtech/ai-webtech-admin-app class MigrateAlreadyReviewedApps < ActiveRecord::Migration def up execute <<-SQL UPDATE apps SET review_points = 2 WHERE reviewed_at IS NOT NULL SQL end def down execute <<-SQL UPDATE apps SET review_points = 0 SQL end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController # POST /resource/sign_in def create if logged_in_user_blocked? env['warden'].logout redirect_to '/', alert: 'You account is blocked and you can not login anymore.' else super end end private def logged_in_user_blocked? current_user && current_user.blocked? end end
HTW-Webtech/ai-webtech-admin-app
app/models/exercise.rb
class Exercise def self.generate_next_id(user) user.app_count + 1 end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/admin/groups_controller.rb
<filename>app/controllers/admin/groups_controller.rb module Admin class GroupsController < BaseController def show @group = Group.find(params[:id]) end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20151111193830_drop_index_from_app_names.rb
<reponame>HTW-Webtech/ai-webtech-admin-app class DropIndexFromAppNames < ActiveRecord::Migration def up remove_index :apps, :name end def down add_index "apps", ["name"], name: "index_apps_on_name", unique: true, using: :btree end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160510142749_add_review_state_to_review_date.rb
class AddReviewStateToReviewDate < ActiveRecord::Migration def change add_column :review_dates, :reviewed_at, :datetime add_column :review_dates, :review_points, :integer, default: 0, null: false end end
HTW-Webtech/ai-webtech-admin-app
app/models/app_name.rb
class AppName PREFIX = %w( cherry alluring swift woopy sharp speedy wonky rocky cleary flashy snowy sweet sour angry funny silent crazy happy fluffy huge tiny mad loopy janky wild erratic funky kinky unique prominent rare spiky wise odd splendid ) NAMES = %w( blossom hound boar archid baham furud stewie brian richard bird elephant panda sheep tower castle rabbit eagle house dolphin whale tiger lion monkey shebang weasel wombat capybara ) def self.generate_unique "#{pick_prefix}-#{pick_name}" end private def self.pick_prefix PREFIX[rand(Range.new(0, PREFIX.count-1))] end def self.pick_name NAMES[rand(Range.new(0, NAMES.count-1))] end end
HTW-Webtech/ai-webtech-admin-app
spec/models/exercise_point_master_spec.rb
<reponame>HTW-Webtech/ai-webtech-admin-app require 'rails_helper' # TODO: Fix tests RSpec.describe ExercisePointMaster do let(:course) do Module.new do module_function def exercises { 1 => [ 2, Date.new(2015, 11, 27)], 2 => [ 4, Date.new(2015, 12, 14)], } end def points { 1 => (0..2), 2 => (0..4), } end end end subject { described_class.new(course) } describe '.points(exercise_result)' do let(:first) { ExerciseResult.new(exercise_id: 1) } let(:second) { ExerciseResult.new(exercise_id: 2) } it 'returns the correct points' do expect(subject.points(first)).to eq 2 expect(subject.points(second)).to eq 4 end end describe '.deadline(exercise_result)' do let(:first_exercise_result) { ExerciseResult.new(exercise_id: 1) } let(:second_exercise_result) { ExerciseResult.new(exercise_id: 2) } it 'returns the correct deadlines' do expect(subject.deadline(first_exercise_result)).to eq Date.parse('2015-11-27') expect(subject.deadline(second_exercise_result)).to eq Date.parse('2015-12-14') end end describe '.reached_deadline?(exercise_result)' do let(:sunday_night) { Date.parse('2015-11-22 23:55') } let(:in_time) { FactoryGirl.build_stubbed(:exercise_result, exercise_id: 1, created_at: sunday_night) } let(:saturday) { Date.parse('2015-11-28 08:00') } let(:too_late) { FactoryGirl.build_stubbed(:exercise_result, exercise_id: 1, created_at: saturday) } it 'returns true when the deadline is matched' do expect(subject.reached_deadline?(in_time)).to eq true expect(subject.reached_deadline?(too_late)).to eq false end end describe '.evaluate!(exercise_result)' do let(:sunday_night) { Date.parse('2015-11-22 23:55') } let(:in_time) { FactoryGirl.create(:exercise_result, exercise_id: 1, created_at: sunday_night) } let(:saturday) { Date.parse('2015-11-28 08:00') } let(:too_late) { FactoryGirl.create(:exercise_result, exercise_id: 1, created_at: saturday) } it 'adds the given points to the app' do pending 'Fixme' expect(in_time.app.exercise_points).to eq 0 expect(too_late.app.exercise_points).to eq 0 subject.evaluate!(in_time) subject.evaluate!(too_late) expect(in_time.app.exercise_points).to eq 2 expect(too_late.app.exercise_points).to eq 0 end end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/home_controller.rb
<reponame>HTW-Webtech/ai-webtech-admin-app class HomeController < ::ApplicationController end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160506135459_add_external_hosting_to_apps.rb
class AddExternalHostingToApps < ActiveRecord::Migration def change add_column :apps, :external_hosting, :boolean, default: false add_column :apps, :external_url, :string end end
HTW-Webtech/ai-webtech-admin-app
app/models/email/app_points_mailer.rb
module Email class AppPointsMailer attr_accessor :app, :points def initialize(app:, points:) @app = app @points = points end def subject "#{points} Punkt(e) für App: #{app.permalink}" end def body "Es wurden gerade für deine App #{app.permalink} #{points} Punkte im Aris eingetragen." end def run ApplicationMailer.sent_email( email: app.user.email, subject: subject, body: body ).deliver_now! end end end
HTW-Webtech/ai-webtech-admin-app
app/models/apiv1/client_auth.rb
require 'openssl' module Apiv1 class ClientAuth attr_reader :instance def initialize @instance = CipherBase64::Instance.new(auth_files_path) end def valid?(signature_base64, data) instance.valid?(signature_base64, data) end def auth_files_path Rails.root + "config/apiv1-auth" end end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/base_controller.rb
<filename>app/controllers/base_controller.rb class BaseController < ::ApplicationController # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :authenticate_user! before_action :redirect_users_to_users_namespace before_action :ensure_user_belongs_to_one_group before_action :ensure_user_belongs_to_one_course before_action :notify_users_without_name private def ensure_user_belongs_to_one_group if current_user && current_user.groups.empty? current_user.groups << Group.current_course end end def ensure_user_belongs_to_one_course if current_user && current_user.course.blank? current_user.update course: Courses.current.display_name end end def notify_users_without_name if current_user && current_user.name.blank? flash[:alert] = "Please set a name on your Profile page" end end def redirect_users_to_users_namespace if current_user && !current_user.admin? && !request.path.start_with?("/users/") redirect_to user_path(current_user) end end def after_sign_in_path_for(_) user_path(current_user) end def add_flash(type:, message:) flash.now[type] ||= [] flash.now[type] << message end end
HTW-Webtech/ai-webtech-admin-app
app/models/email/scheduler.rb
module Email class Scheduler attr_accessor :group, :subject, :body, :mails def initialize(group:, subject:, body:) @group = group @subject = subject @body = body end def run self.mails = group.users.map do |user| ApplicationMailer.sent_email( email: user.email, subject: subject, body: body, ) end mails.all? { |mail| mail.deliver_now! } Notifier.notify "#{mails.count} E-Mails (Subject: '#{subject}') have been sent to: #{group.users.map(&:email).join(', ')}" end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20151127041253_drop_postgress_feature.rb
<reponame>HTW-Webtech/ai-webtech-admin-app class DropPostgressFeature < ActiveRecord::Migration def up remove_column :apps, :pg_host remove_column :apps, :pg_database remove_column :apps, :pg_login remove_column :apps, :pg_passwd end def down add_column :apps, :pg_host, :string, default: 'localhost' add_column :apps, :pg_database, :string add_column :apps, :pg_login, :string add_column :apps, :pg_passwd, :string end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base force_ssl if: :ssl_configured? before_action :authorize_mini_profiler private def authorize_mini_profiler if current_user && current_user.admin? Rack::MiniProfiler.authorize_request end end def ssl_configured? Rails.env.production? end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160508205029_add_review_groups.rb
<gh_stars>0 class AddReviewGroups < ActiveRecord::Migration def change create_table :review_groups do |t| t.timestamps end create_table :review_dates do |t| t.integer :review_group_id, null: false t.datetime :begins_at, null: false t.integer :exercise_id, null: false t.timestamps end add_column :users, :review_group_id, :integer end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/admin/apps_controller.rb
<reponame>HTW-Webtech/ai-webtech-admin-app module Admin class AppsController < BaseController def create apps = Courses.current.apps apps.find_each do |app| ArisService.publish(app) end redirect_to root_path, notice: "Recreated the apps.yml file for #{apps.count} Apps." end def update app = App.for_permalink_or_id(params[:id]) ArisService.publish(app) redirect_to :back, notice: "Recreating app config for #{app.permalink}." end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160422182348_add_course_to_user.rb
class AddCourseToUser < ActiveRecord::Migration def up add_column :users, :course, :string %w(Summer2016 Winter2015).each do |course| group = Group.where(name: course).first! group.users.each do |user| user.update course: course end end end def down remove_column :users, :course end end
HTW-Webtech/ai-webtech-admin-app
app/helpers/feedbacks_helper.rb
<filename>app/helpers/feedbacks_helper.rb module FeedbacksHelper EXERCISE_TEMPLATES = { 8 => <<-EOF.strip_heredoc # Bewertung Abschlussprojekt: PatMan | Feature | Punkte: Erreicht/Von | Feedback | |----------------------------------------| | CRUD Patient | ?/3 | | |----------------------------------------| | CRUD Note | ?/3 | | |----------------------------------------| | CRUD Appointment | ?/4 | | |----------------------------------------| | Statistiken | ?/2 | | |----------------------------------------| | Auflistung: Upcoming Appointments | ?/1 | | |----------------------------------------| | Auflistung: Past Appointments | ?/1 | | |----------------------------------------| | Auflistung: Notizen p. Patient | ?/1 | | |----------------------------------------| | Auflistung: Appointments p. Patient | ?/1 | | |----------------------------------------| | **Gesamtpunkte** | ?/16 | | |----------------------------------------| {: .table } EOF } def feedback_template(feedback) return feedback.body if feedback.body.present? EXERCISE_TEMPLATES.fetch(feedback.app.exercise_id, "Kein Template") end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160403171845_block_all_old_users.rb
<filename>db/migrate/20160403171845_block_all_old_users.rb class BlockAllOldUsers < ActiveRecord::Migration def up execute <<-SQL UPDATE users SET blocked_at = '#{Time.current}' WHERE created_at < '2016-01-01 00:00' AND name != 'admin' SQL end def down execute <<-SQL UPDATE users SET blocked_at = NULL WHERE created_at < '2016-01-01 00:00' SQL end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/admin/jenkins_controller.rb
module Admin class JenkinsController < BaseController def create apps = Courses.current.apps JenkinsService.publish(apps) redirect_to root_path, notice: "Recreated jenkins_yaml for #{apps.count} apps." end def update app = App.for_permalink_or_id(params[:id]) JenkinsService.publish(app) redirect_to :back, notice: "Recreating jenkins config for #{app.permalink}." end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20151123093912_replace_exercise_passed_on_apps_with_points.rb
class ReplaceExercisePassedOnAppsWithPoints < ActiveRecord::Migration def up remove_column :apps, :exercise_passed_at add_column :apps, :exercise_points, :integer, default: 0 end def down add_column :apps, :exercise_passed_at, :datetime remove_column :apps, :exercise_points end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/review_groups_controller.rb
<gh_stars>0 class ReviewGroupsController < ::BaseController def show @review_group = current_user.review_group end def update review_group = current_user.review_group review_group.update review_group_params redirect_to :back, notice: 'Einstellungen aktualisiert' end private def review_group_params params.require(:review_group).permit(:order) end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/users_controller.rb
class UsersController < ::BaseController def show @announcements = Announcement.all @user = fetch_user @apps = @user.apps.order(id: :asc) @course = Courses.current end def edit @user = fetch_user end def update @user = fetch_user if @user.update_attributes(user_params) redirect_to @user else render :edit end end def index redirect_to current_user end private def fetch_user User.find(params[:id]).tap do |user| redirect_to current_user unless user == current_user || current_user.admin? end end def user_params params.require(:user).permit(:name, :ssh_key, :password, :password_<PASSWORD>, :reset_password_token) end end
HTW-Webtech/ai-webtech-admin-app
app/controllers/apiv1/base_controller.rb
<reponame>HTW-Webtech/ai-webtech-admin-app module Apiv1 class BaseController < ::ApplicationController AuthError = Class.new(Exception) # before_action :authenticate_client rescue_from AuthError, with: :handle_auth_error private def authenticate_client sign = request.headers['x-client-auth-signature'].to_s data = request.headers['x-client-data'].to_s if sign.blank? raise AuthError, 'x-client-auth-signature header missing' end if data.blank? raise AuthError, 'x-client-data header missing' end auth = Apiv1::ClientAuth.new if !auth.valid?(sign, data) raise AuthError, 'Unauthorized access' end end def handle_auth_error(exception) render json: JSON.generate({ result: 'unauthorized', message: exception.message }), status: :unauthorized end end end
HTW-Webtech/ai-webtech-admin-app
db/migrate/20160808080030_create_feedbacks.rb
<reponame>HTW-Webtech/ai-webtech-admin-app<filename>db/migrate/20160808080030_create_feedbacks.rb class CreateFeedbacks < ActiveRecord::Migration def change create_table :feedbacks do |t| t.text :body t.references :app t.timestamps null: false end add_foreign_key :feedbacks, :apps end end