def buildFourChildTreeTopology(): print("\n\nBuilding four-child-tree topology") nodeA = Node("A") nodeB = Node("B") nodeC = Node("C") nodeD = Node("D") nodeE = Node("E", router=True) # Add connection to parent nodeA.addNeighbor(Neighbor(nodeE)) nodeB.addNeighbor(Neighbor(nodeE)) nodeC.addNeighbor(Neighbor(nodeE)) nodeD.addNeighbor(Neighbor(nodeE)) # Add reverse connection nodeE.addNeighbor(Neighbor(nodeA)) nodeE.addNeighbor(Neighbor(nodeB)) nodeE.addNeighbor(Neighbor(nodeC)) nodeE.addNeighbor(Neighbor(nodeD)) topologyName = "four-child-tree" nodes = [nodeA, nodeB, nodeC, nodeD, nodeE] printTopology(nodes) NlsrBuilder(topologyName).buildNlsrFiles(nodes) ComposeBuilder(topologyName, nodes).buildComposeFile()
def buildLinearTwoTopology(): print("\n\nBuilding linear-two topology") # A <--10--> B nodeA = Node("A") nodeB = Node("B") nodeA.addNeighbor(Neighbor(nodeB)) nodeB.addNeighbor(Neighbor(nodeA)) topologyName = "linear" nodes = [nodeA, nodeB] printTopology(nodes) NlsrBuilder(topologyName).buildNlsrFiles(nodes) ComposeBuilder(topologyName, nodes).buildComposeFile()
def __init__(self, iterate, **kwargs): self.iterate = iterate self.startState = file.read() self.neighbor = Neighbor(self.startState) self.update_states = None if "update_states" in kwargs: self.update_states = True
def make_bldg_neighbor(self, name): bldg_powers = self.building_powers[name] # Create neighbor bldg = Neighbor() bldg.name = name bldg.maximumPower = bldg_powers[ 0] # Remember loads have negative power [avg.kW] bldg.minimumPower = bldg_powers[1] # [avg.kW] _log.debug("{} has minPower of {} and maxPower of {}".format( bldg.name, bldg.minimumPower, bldg.maximumPower)) # Create neighbor model bldg_model = NeighborModel() bldg_model.name = name + '_Model' bldg_model.location = self.name bldg_model.convergenceThreshold = 0.02 bldg_model.friend = True bldg_model.transactive = True bldg_model.costParameters = [0, 0, 0] # This is different building to building bldg_model.defaultPower = bldg.minimumPower / 2 # bldg_powers[2] # [avg.kW] bldg_model.defaultVertices = [ Vertex(float("inf"), 0, bldg_model.defaultPower, True) ] # Cross reference object & model bldg.model = bldg_model bldg_model.object = bldg return bldg
def main(): with open('config.json') as data: config = json.load(data) neighbors = [] for item in config['neighbor_list']: neighbors.append(Neighbor(str(item))) ip, p2p_port = neighbors[0].getP2PConfig() diff = config['target'] beneficiary = config['beneficiary'] delay = config['delay'] is_miner = config['mining'] public_key = config['wallet']['public_key'] private_key = config['wallet']['private_key'] fee = config['fee'] chain = minichain(diff) user_wallet = wallet(public_key, private_key) node1 = node(config['p2p_port'], config['user_port'], neighbors, chain, beneficiary, user_wallet, fee, delay, is_miner) try: node1.start_node() except KeyboardInterrupt: sys.exit(1) except: print("[ERROR] UNKNOWN ERROR") sys.exit(1)
def hill(self): currentState = self.startState nextEval = Heuristic(currentState).attacks() i = 0 while i < self.iterate and nextEval != 0: newState = self.neighbor.generateState() currentEval = Heuristic(newState).attacks() if self.update_states: print Heuristic(currentState).queensPosition( ), " -> ", Heuristic(newState).queensPosition() if currentEval <= nextEval: currentState = newState nextEval = Heuristic(currentState).attacks() i += 1 self.neighbor = Neighbor(currentState) file.write(Heuristic(currentState).queensPosition(), self.neighbor.createBoard(), url="./resource/newBoard.txt") print "Hill Comum > Iteracao : ", i print "Posicao Inicial das ", len( self.startState), " rainhas : ", Heuristic( self.startState).queensPosition() print "Posicao Final das ", len( self.startState), " rainhas : ", Heuristic( currentState).queensPosition() print "\tNumero de rainhas atacando : ", Heuristic( currentState).attacks() self.startState = currentState return Heuristic(currentState).attacks()
def simulate(self): i = 0 success = sys.maxsize currentState = self.startState t = self.startTemp solutions = [] while not (success == 0) and i < self.iterate: j = 0 success = 0 while success <= self.maxSuc and j < self.maxDis: f1 = Heuristic(currentState).attacks() newState = self.neighbor.generateState() if Heuristic(newState).attacks() == 0: if not Heuristic(newState).queensPosition() in solutions: solutions.append(Heuristic(newState).queensPosition()) if self.state_update: print Heuristic(currentState).queensPosition( ), " -> ", Heuristic(newState).queensPosition() f2 = Heuristic(newState).attacks() deltaF = f2 - f1 if not t == 0.0: if (deltaF <= 0) or (exp(-deltaF / t) > random.random()): currentState = newState success += 1 j += 1 self.neighbor = Neighbor(currentState) t = self.alpha * t i += 1 file.write(Heuristic(currentState).queensPosition(), self.neighbor.createBoard(), url='./resource/newBoard.txt') print "Contagem final de sucessos : ", success print "Temperatura final : ", t print "Numero de iteracoes : ", i print "Posicao Inicial das ", len( self.startState), " rainhas : ", Heuristic( self.startState).queensPosition() print "Posicao Final das ", len( self.startState), " rainhas : ", Heuristic( currentState).queensPosition() print "\tNumero de rainhas atacando : ", Heuristic( currentState).attacks() print "Solucoes encontradas: " for solution in solutions: print solution return Heuristic(currentState).attacks()
def __init__(self, iterate, maxDis, maxSuc, alpha, startTemp, **kwargs): self.iterate = iterate self.maxDis = maxDis self.maxSuc = maxSuc self.alpha = alpha self.startState = file.read() self.neighbor = Neighbor(self.startState) self.startTemp = startTemp self.state_update = None if 'state_update' in kwargs: self.state_update = True
def buildLinearThreeTopology(): print("\n\nBuilding linear-three topology") """ A <--10--> B <--20--> C | 10 X """ nodeA = Node("A") nodeB = Node("B") nodeC = Node("C") # Adding my local machine to the mix nodeX = Node("X") nodeX.addNeighbor(Neighbor(nodeB)) nodeA.addNeighbor(Neighbor(nodeB)) nodeB.addNeighbor(Neighbor(nodeA)) nodeB.addNeighbor(Neighbor(nodeC)) nodeB.addNeighbor(Neighbor(nodeX)) nodeC.addNeighbor(Neighbor(nodeB)) topologyName = "linear-three" nodes = [nodeA, nodeB, nodeC, nodeX] printTopology(nodes) NlsrBuilder(topologyName).buildNlsrFiles(nodes) ComposeBuilder(topologyName, nodes).buildComposeFile()
def buildDumbbellTopology(): print("\n\nBuilding dumbbell topology") # Left side nodeA = Node("A") nodeB = Node("B") # Right side nodeC = Node("C") nodeD = Node("D") # Left router nodeE = Node("E", router=True) # Right router nodeF = Node("F", router=True) # Each of left nodes are connected to E nodeA.addNeighbor(Neighbor(nodeE)) nodeB.addNeighbor(Neighbor(nodeE)) # Each of right nodes are connected to F nodeC.addNeighbor(Neighbor(nodeF)) nodeD.addNeighbor(Neighbor(nodeF)) # E is connected to all left nodes and F nodeE.addNeighbor(Neighbor(nodeA)) nodeE.addNeighbor(Neighbor(nodeB)) nodeE.addNeighbor(Neighbor(nodeF)) # F is connected to all right nodes and E nodeF.addNeighbor(Neighbor(nodeC)) nodeF.addNeighbor(Neighbor(nodeD)) nodeF.addNeighbor(Neighbor(nodeE)) topologyName = "dumbbell" nodes = [nodeA, nodeB, nodeC, nodeD, nodeE, nodeF] printTopology(nodes) NlsrBuilder(topologyName).buildNlsrFiles(nodes) ComposeBuilder(topologyName, nodes).buildComposeFile()
def _parse_config_file(self, config_file): ''' Config file has general configuration, such as href prefix. Config file has information for Switches - Name - Connection info - List of reserved bridge numbers - Neighbors ''' with open(config_file) as data_file: data = json.load(data_file) self.base_url = data['adaptor-href-base'] for switch in data['switches']: switch_name = switch['name'] connection_info = switch['connection-info'] reserved_bridges = switch['reserved-bridges'] neighbors = switch['neighbors'] # Determine the correct href for the switch we're creating switch_href = self.base_url + "switches/" + switch_name # Create Switch object switch = Switch(switch_name, switch_href, self.no_switch) # Create the ConnectionInfo object and add it to the switch cxn_info_object = ConnectionInfo(connection_info['address'], connection_info['rest_key']) switch.set_connection_info(cxn_info_object) # Add list of reserved bridges switch.set_reserved_bridges(reserved_bridges) # Create all the neighbors and add them to the switch object for neighbor in neighbors: neighbor_name = neighbor['name'] neighbor_type = neighbor['type'] neighbor_physport = neighbor['port'] neighbor_vlans = neighbor['vlans'] neighbor_href = switch_href + "/neighbors/" + neighbor_name neighbor_object = Neighbor(neighbor_name, neighbor_href, neighbor_vlans, neighbor_physport, neighbor_type) switch.add_neighbor(neighbor_object) # Save off switch self.switches[switch_name] = switch
def hill_random(self): colision = sys.maxsize count = 0 stagnate = sys.maxsize old_col = -1 while colision != 0 and not stagnate == 100: print "Hill Random > Iteracao: ", count + 1 print "------------------------------------------\n" start = time.time() colision = self.hill() end = time.time() - start print "\tTempo de execucao : ", end, " segundos" self.neighbor = Neighbor(self.startState) count += 1 print "\n------------------------------------------\n" if not old_col == colision: old_col = colision stagnate = 0 else: stagnate += 1
def make_campus(self): # Campus object campus = Neighbor() campus.name = 'PNNL_Campus' campus.description = 'PNNL_Campus' campus.maximumPower = 0.0 # Remember loads have negative power [avg.kW] campus.minimumPower = -20000 # [avg.kW] # Campus model campus_model = NeighborModel() campus_model.name = 'PNNL_Campus_Model' campus_model.location = self.name campus_model.defaultPower = -10000 # [avg.kW] campus_model.defaultVertices = [Vertex(0.045, 0.0, -10000.0)] #campus_model.demandThreshold = 0.8 * campus.maximumPower campus_model.transactive = True # Cross-reference object & model campus_model.object = campus campus.model = campus_model return campus
def particleCalculations(self): for i in range(len(self.particles)): # Density calculations densityFar = densityNear = 0 targetParticle = self.particles[i] targetParticle.rho = targetParticle.rhoNear = 0 for j in range(i + 1, len(self.particles)): neighborParticle = self.particles[j] distanceVector = neighborParticle.pos - targetParticle.pos distance = np.linalg.norm(distanceVector) if distance**2 < self.supportRadius**2: weightedDistance = 1 - distance / self.supportRadius densityFar += weightedDistance**2 densityNear += weightedDistance**3 neighborParticle.rho += weightedDistance**2 neighborParticle.rhoNear += weightedDistance**3 newNeighbor = Neighbor(neighborParticle, weightedDistance) targetParticle.neighbors.append(newNeighbor) targetParticle.rho += densityFar targetParticle.rhoNear += densityNear # Pressure calculations targetParticle.press = self.k * (targetParticle.rho - self.restDensity) targetParticle.pressNear = self.kNear * targetParticle.rhoNear dX = np.array([0, 0]) for neighborEntry in targetParticle.neighbors: neighborParticle = neighborEntry.particle distanceVector = neighborParticle.pos - targetParticle.pos dm = (targetParticle.pressure + neighborParticle.pressure ) * neighborEntry.weightedDistance + ( targetParticle.pressNear + neighborParticle. pressureNear) * (neighborEntry.weightedDistance**2) directionOfForce = (distanceVector / np.linalg.norm(distanceVector)) * dm dX = dX + directionOfForce neighborParticle.force = neighborParticle.force + directionOfForce targetParticle.force = targetParticle.force - dX
def make_supplier(self): # Add supplier supplier = Neighbor() supplier.name = 'BPA' supplier.description = 'The Bonneville Power Administration as electricity supplier to the City of Richland, WA' supplier.lossFactor = self.supplier_loss_factor supplier.maximumPower = 200800 # [avg.kW, twice the average COR load] supplier.minimumPower = 0.0 # [avg.kW, will not export] # Add supplier model supplierModel = BulkSupplier_dc() supplierModel.name = 'BPAModel' #supplierModel.demandThreshold = 0.75 * supplier.maximumPower supplierModel.converged = False # Dynamically assigned supplierModel.convergenceThreshold = 0 # Not yet implemented supplierModel.effectiveImpedance = 0.0 # Not yet implemented supplierModel.friend = False # Separate business entity from COR supplierModel.transactive = False # Not a transactive neighbor # Add vertices # The first default vertex is, for now, based on the flat COR rate to # PNNL. The second vertex includes 2# losses at a maximum power that # is twice the average electric load for COR. This is helpful to # ensure that a unique price, power point will be found. In this # model the recipient pays the cost of energy losses. # The first vertex is based on BPA Jan HLH rate at zero power # importation. d1 = Vertex(0, 0, 0) # create first default vertex d1.marginalPrice = 0.04196 # HLH BPA rate Jan 2018 [$/kWh] d1.cost = 2000.0 # Const. price shift to COR customer rate [$/h] d1.power = 0.0 # [avg.kW] # The second default vertex represents imported and lost power at a power # value presumed to be the maximum deliverable power from BPA to COR. d2 = Vertex(0, 0, 0) # create second default vertex # COR pays for all sent power but receives an amount reduced by # losses. This creates a quadratic term in the production cost and # a slope to the marginal price curve. d2.marginalPrice = d1.marginalPrice / (1 - supplier.lossFactor ) # [$/kWh] # From the perspective of COR, it receives the power sent by BPA, # less losses. d2.power = (1 - supplier.lossFactor) * supplier.maximumPower # [avg.kW] # The production costs can be estimated by integrating the # marginal-price curve. d2.cost = d1.cost + d2.power * (d1.marginalPrice + 0.5 * (d2.marginalPrice - d1.marginalPrice) ) # [$/h] supplierModel.defaultVertices = [d1, d2] # COST PARAMTERS # A constant cost parameter is being used here to account for the # difference between wholesale BPA rates to COR and COR distribution # rates to customers like PNNL. A constant of $2,000/h steps the rates # from about 0.04 $/kWh to about 0.06 $/kWh. This may be refined later. # IMPORTANT: This shift has no affect on marginal pricing. supplierModel.costParameters[0] = 2000.0 # [$/h] # Cross-reference object & model supplierModel.object = supplier supplier.model = supplierModel # Meter bpaElectricityMeter = MeterPoint() # Instantiate an electricity meter bpaElectricityMeter.name = 'BpaElectricityMeter' bpaElectricityMeter.description = 'BPA electricity to COR' bpaElectricityMeter.measurementType = MeasurementType.PowerReal bpaElectricityMeter.measurementUnit = MeasurementUnit.kWh supplierModel.meterPoints = [bpaElectricityMeter] return supplier
def test_schedule(): print('Running Market.test_schedule()') print('WARNING: This test may be affected by NeighborModel.schedule()') print('WARNING: This test may be affected by NeighborModel.schedule()') pf = 'pass' # Establish a myTransactiveNode object mtn = myTransactiveNode() # Establish a test market test_mkt = Market() # Create and store one TimeInterval dt = datetime(2018, 1, 1, 12, 0, 0) # Noon Jan 1, 2018 at = dt dur = timedelta(hours=1) mkt = test_mkt mct = dt st = dt ti = TimeInterval(at, dur, mkt, mct, st) test_mkt.timeIntervals = [ti] # Create and store a marginal price in the active interval. test_mkt.marginalPrices = [ IntervalValue(test_mkt, ti, test_mkt, MeasurementType.MarginalPrice, 0.01) ] print('- configuring a test Neighbor and its NeighborModel') # Create a test object that is a Neighbor test_obj1 = Neighbor() test_obj1.maximumPower = 100 # Create the corresponding model that is a NeighborModel test_mdl1 = NeighborModel() test_mdl1.defaultPower = 10 test_obj1.model = test_mdl1 test_mdl1.object = test_obj1 mtn.neighbors = [test_obj1] print('- configuring a test LocalAsset and its LocalAssetModel') # Create a test object that is a Local Asset test_obj2 = LocalAsset test_obj2.maximumPower = 100 # Create the corresponding model that is a LocalAssetModel test_mdl2 = LocalAssetModel() test_mdl2.defaultPower = 10 test_obj2.model = test_mdl2 test_mdl2.object = test_obj2 mtn.localAssets = [test_obj2] try: test_mkt.schedule(mtn) print('- method ran without errors') except: raise ('- method did not run due to errors') if len(test_mdl1.scheduledPowers) != 1: raise ( '- the wrong numbers of scheduled powers were stored for the Neighbor' ) else: print( '- the right number of scheduled powers were stored for the Neighbor' ) if len(test_mdl2.scheduledPowers) != 1: raise ( '- the wrong numbers of scheduled powers were stored for the LocalAsset' ) else: print( '- the right number of scheduled powers were stored for the LocalAsset' ) # Success print('- the test ran to completion') print('Result: #s\n\n', pf)
def test_sum_vertices(): print('Running Market.test_sum_vertices()') pf = 'pass' # Create a test myTransactiveNode object. test_node = myTransactiveNode() # Create a test Market object. test_market = Market() # List the test market with the test_node. test_node.markets = test_market # Create and store a time interval to work with. dt = datetime.now() at = dt dur = timedelta(hours=1) mkt = test_market mct = dt st = dt time_interval = TimeInterval(at, dur, mkt, mct, st) test_market.timeIntervals = [time_interval] # Create test LocalAsset and LocalAssetModel objects test_asset = LocalAsset() test_asset_model = LocalAssetModel() # Add the test_asset to the test node list. test_node.localAssets = [test_asset] # Have the test asset and its model cross reference one another. test_asset.model = test_asset_model test_asset_model.object = test_asset # Create and store an active Vertex or two for the test asset test_vertex = [Vertex(0.2, 0, -110), Vertex(0.2, 0, -90)] interval_values = [ IntervalValue(test_node, time_interval, test_market, MeasurementType.ActiveVertex, test_vertex[0]), IntervalValue(test_node, time_interval, test_market, MeasurementType.ActiveVertex, test_vertex[1]) ] test_asset_model.activeVertices = [interval_values[0], interval_values[1] ] # interval_value(1:2) # Create test Neighbor and NeighborModel objects. test_neighbor = Neighbor() test_neighbor_model = NeighborModel() # Add the test neighbor to the test node list. test_node.neighbors = [test_neighbor] # Have the test neighbor and its model cross reference one another. test_neighbor.model = test_neighbor_model test_neighbor.model.object = test_neighbor # Create and store an active Vertex or two for the test neighbor test_vertex.append(Vertex(0.1, 0, 0)) test_vertex.append(Vertex(0.3, 0, 200)) interval_values.append( IntervalValue(test_node, time_interval, test_market, MeasurementType.ActiveVertex, test_vertex[2])) interval_values.append( IntervalValue(test_node, time_interval, test_market, MeasurementType.ActiveVertex, test_vertex[3])) test_neighbor_model.activeVertices = [ interval_values[2], interval_values[3] ] ## Case 1 print('- Case 1: Basic case with interleaved vertices') # Run the test. try: vertices = test_market.sum_vertices(test_node, time_interval) print(' - the method ran without errors') except: pf = 'fail' print(' - the method had errors when called and stopped') if len(vertices) != 4: pf = 'fail' print(' - an unexpected number of vertices was returned') else: print(' - the expected number of vertices was returned') powers = [x.power for x in vertices] # if any(~ismember(single(powers), single([-110.0000, -10.0000, 10.0000, 110.0000]))) if len([ x for x in powers if round(x, 4) not in [-110.0000, -10.0000, 10.0000, 110.0000] ]) > 0: pf = 'fail' print(' - the vertex powers were not as expected') else: print(' - the vertex powers were as expected') marginal_prices = [round(x.marginalPrice, 4) for x in vertices] # if any(~ismember(single(marginal_prices), single([0.1000, 0.2000, 0.3000]))) if len([ x for x in marginal_prices if round(x, 4) not in [0.1000, 0.2000, 0.3000] ]) > 0: pf = 'fail' print(' - the vertex powers were not as expected') else: print(' - the vertex marginal prices were as expected') ## CASE 2: NEIGHBOR MODEL TO BE EXCLUDED # This case is needed when a demand or supply curve must be created for a # transactive Neighbor object. The active vertices of the target Neighbor # must be excluded, leaving a residual supply or demand curve against which # the Neighbor may plan. print('- Case 2: Exclude test Neighbor model') # Run the test. try: # [vertices] = test_market.sum_vertices(test_node, time_interval, test_neighbor_model) vertices = test_market.sum_vertices(test_node, time_interval, test_neighbor_model) print(' - the method ran without errors') except: pf = 'fail' print(' - the method encountered errors and stopped') if len(vertices) != 2: pf = 'fail' print(' - an unexpected number of vertices was returned') else: print(' - the expected number of vertices was returned') powers = [round(x.power, 4) for x in vertices] # if any(~ismember(single(powers), single([-110.0000, -90.0000]))) if len([x for x in powers if x not in [-110.0000, -90.0000]]) > 0: pf = 'fail' print(' - the vertex powers were not as expected') else: print(' - the vertex powers were as expected') marginal_prices = [x.marginalPrice for x in vertices] # if any(~ismember(single(marginal_prices), single([0.2000]))) if len([x for x in marginal_prices if round(x, 4) not in [0.2000]]) > 0: pf = 'fail' print(' - the vertex powers were not as expected') else: print(' - the vertex marginal prices were as expected') ## CASE 3: CONSTANT SHOULD NOT CREATE NEW NET VERTEX print('- Case 3: Include a constant vertex. No net vertex should be added') # Change the test asset to NOT have any flexibility. A constant should # not introduce a net vertex at a constant's marginal price. Marginal # price is NOT meaningful for an inelastic device. test_asset_model.activeVertices = [interval_values[0]] # Run the test. try: # [vertices] = test_market.sum_vertices(test_node, time_interval) vertices = test_market.sum_vertices(test_node, time_interval) print(' - the method ran without errors') except: pf = 'fail' print(' - the method encountered errors and stopped') #%[180907DJH: THIS TEST IS CORRECTED. THE NEIGHBOR HAS TWO VERTICES. ADDING #AN ASSET WITH ONE VERTEX (NO FLEXIBILITY) SHOULD NOT CHANGE THE NUMBER OF #ACTIVE VERTICES, SO THE CORRECTED TEST CONFIRMS TWO VERTICES. THE CODE HAS #BEEN CORRECTED ACCORDINGLY.] if len(vertices) != 2: pf = 'fail' print(' - an unexpected number of vertices was returned') else: print(' - the expected number of vertices was returned') powers = [x.power for x in vertices] # if any(~ismember(single(powers), single([-110.0000, 90]))) if len([x for x in powers if round(x, 4) not in [-110.0000, 90]]) > 0: pf = 'fail' print(' - the vertex powers were not as expected') else: print(' - the vertex powers were as expected') marginal_prices = [x.marginalPrice for x in vertices] # if any(~ismember(single(marginal_prices), single([0.1000, 0.3000, Inf]))) if len([ x for x in marginal_prices if round(x, 4) not in [0.1000, 0.3000, float("inf")] ]) > 0: pf = 'fail' print(' - the vertex powers were not as expected') else: print(' - the vertex marginal prices were as expected') # CASE 4: More than two vertices at any marginal price print('- Case 4: More than two vertices at same marginal price') # Move the two active vertices of the test asset to be at the same # marginal price as one of the neighbor active vertices. test_vertex = [Vertex(0.1, 0, -110), Vertex(0.1, 0, -90)] interval_values = [ IntervalValue(test_node, time_interval, test_market, MeasurementType.ActiveVertex, test_vertex[0]), IntervalValue(test_node, time_interval, test_market, MeasurementType.ActiveVertex, test_vertex[1]) ] test_asset_model.activeVertices = [interval_values[0], interval_values[1] ] # interval_value(1:2) # Run the test. try: vertices = test_market.sum_vertices(test_node, time_interval) print(' - the method ran without errors') except: pf = 'fail' print(' - the method encountered errors and stopped') if len(vertices) != 3: pf = 'fail' print(' - an unexpected number of vertices was returned') else: print(' - the expected number of vertices was returned') powers = [x.power for x in vertices] # if any(~ismember(single(powers), single([-110.0000, -90.0000, 110.0000]))) if len([ x for x in powers if round(x, 4) not in [-110.0000, -90.0000, 110.0000] ]) > 0: pf = 'fail' print(' - the vertex powers were not as expected') else: print(' - the vertex powers were as expected') marginal_prices = [x.marginalPrice for x in vertices] # if any(~ismember(single(marginal_prices), single([0.1000, 0.3000]))) if len([x for x in marginal_prices if round(x, 4) not in [0.1000, 0.3000] ]) > 0: pf = 'fail' print(' - the vertex powers were not as expected') else: print(' - the vertex marginal prices were as expected') # Success print('- the test ran to completion') print('Result: #s\n\n', pf)
def init_objects(self): # Add meter # meter = MeterPoint() # meter.name = 'BuildingElectricMeter' # meter.measurementType = MeasurementType.PowerReal # meter.measurementUnit = MeasurementUnit.kWh # self.meterPoints.append(meter) # Add weather forecast service weather_service = TemperatureForecastModel(self.config_path, self) self.informationServiceModels.append(weather_service) # # Add inelastive asset # inelastive_load = LocalAsset() # inelastive_load.name = 'InelasticBldgLoad' # inelastive_load.maximumPower = 0 # Remember that a load is a negative power [kW] # inelastive_load.minimumPower = -200 # # # Add inelastive asset model # inelastive_load_model = LocalAssetModel() # inelastive_load_model.name = 'InelasticBuildingModel' # inelastive_load_model.defaultPower = -100 # [kW] # inelastive_load_model.defaultVertices = [Vertex(float("inf"), 0, -100, True)] # # # Cross-reference asset & asset model # inelastive_load_model.object = inelastive_load # inelastive_load.model = inelastive_load_model # Add elastive asset elastive_load = LocalAsset() elastive_load.name = 'TccLoad' elastive_load.maximumPower = 0 # Remember that a load is a negative power [kW] elastive_load.minimumPower = -self.max_deliver_capacity # Add inelastive asset model # self.elastive_load_model = LocalAssetModel() self.elastive_load_model = TccModel() self.elastive_load_model.name = 'TccModel' self.elastive_load_model.defaultPower = -0.5*self.max_deliver_capacity # [kW] self.elastive_load_model.defaultVertices = [Vertex(0.055, 0, -self.elastive_load_model.defaultPower, True), Vertex(0.06, 0, -self.elastive_load_model.defaultPower/2, True)] # Cross-reference asset & asset model self.elastive_load_model.object = elastive_load elastive_load.model = self.elastive_load_model # Add inelastive and elastive loads as building' assets self.localAssets.extend([elastive_load]) # Add Market market = Market() market.name = 'dayAhead' market.commitment = False market.converged = False market.defaultPrice = 0.0428 # [$/kWh] market.dualityGapThreshold = self.duality_gap_threshold # [0.02 = 2#] market.initialMarketState = MarketState.Inactive market.marketOrder = 1 # This is first and only market market.intervalsToClear = 1 # Only one interval at a time market.futureHorizon = timedelta(hours=24) # Projects 24 hourly future intervals market.intervalDuration = timedelta(hours=1) # [h] Intervals are 1 h long market.marketClearingInterval = timedelta(hours=1) # [h] market.marketClearingTime = Timer.get_cur_time().replace(hour=0, minute=0, second=0, microsecond=0) # Aligns with top of hour market.nextMarketClearingTime = market.marketClearingTime + timedelta(hours=1) self.markets.append(market) # Campus object campus = Neighbor() campus.name = 'PNNL_Campus' campus.description = 'PNNL_Campus' campus.maximumPower = self.max_deliver_capacity campus.minimumPower = 0. # [avg.kW] campus.lossFactor = self.campus_loss_factor # Campus model campus_model = NeighborModel() campus_model.name = 'PNNL_Campus_Model' campus_model.location = self.name campus_model.defaultVertices = [Vertex(0.045, 25, 0, True), Vertex(0.048, 0, self.max_deliver_capacity, True)] campus_model.demand_threshold_coef = self.demand_threshold_coef # campus_model.demandThreshold = self.demand_threshold_coef * self.monthly_peak_power campus_model.demandThreshold = self.monthly_peak_power campus_model.transactive = True campus_model.inject(self, system_loss_topic=self.system_loss_topic) # Avg building meter building_meter = MeterPoint() building_meter.name = self.name + ' ElectricMeter' building_meter.measurementType = MeasurementType.AverageDemandkW building_meter.measurementUnit = MeasurementUnit.kWh campus_model.meterPoints.append(building_meter) # Cross-reference object & model campus_model.object = campus campus.model = campus_model self.campus = campus # Add campus as building's neighbor self.neighbors.append(campus)
image_conv_encoding_ph = tf.placeholder( dtype=tf.float32, shape=[None, k, k, FLAGS.conv_size]) image_fc_encoding_ph = tf.placeholder(dtype=tf.float32, shape=[None, k, k, 4096]) image_ph = tf.placeholder( dtype=tf.float32, shape=[None, FLAGS.train_height, FLAGS.train_width, 3]) rnn_inputs_ph = tf.placeholder(dtype=tf.float32, shape=[None, None]) training_fc_encodings_ph = tf.placeholder(dtype=tf.float32, shape=[None, k, k, 4096]) training_filenames_ph = tf.placeholder(dtype=tf.string, shape=[helpers.get_training_size()]) # Initialize auxiliary image_shape = [1, FLAGS.train_height, FLAGS.train_width, 3] neighbor = Neighbor(image_fc_encoding_ph, training_fc_encodings_ph, training_filenames_ph) # Initialize image encoder vgg = Vgg16() vgg.build(image_ph, image_shape[1:]) conv_encoding = vgg.pool5 fc_encoding = vgg.fc7 # Initialize caption encoder stv = EncoderManager() stv_uni_config = stv_configuration.model_config() stv.load_model(stv_uni_config, FLAGS.stv_vocab_file, FLAGS.stv_embeddings_file, FLAGS.stv_checkpoint_path) with tf.variable_scope('trained'): tatt = Attention(image_conv_encoding_ph, caption_encoding_ph)
def init_objects(self): # Add meter meter = MeterPoint() meter.measurementType = MeasurementType.PowerReal meter.name = 'CampusElectricityMeter' meter.measurementUnit = MeasurementUnit.kWh self.meterPoints.append(meter) # Add weather forecast service weather_service = TemperatureForecastModel(self.config_path, self) self.informationServiceModels.append(weather_service) # Add inelastive asset inelastive_load = LocalAsset() inelastive_load.name = 'InelasticBuildings' # Campus buildings that are not responsive inelastive_load.maximumPower = 0 # Remember that a load is a negative power [kW] inelastive_load.minimumPower = -2 * 8200 # Assume twice the average PNNL load [kW] # Add inelastive asset model inelastive_load_model = OpenLoopPnnlLoadPredictor(weather_service) inelastive_load_model.name = 'InelasticBuildingsModel' inelastive_load_model.engagementCost = [ 0, 0, 0 ] # Transition costs irrelevant inelastive_load_model.defaultPower = -6000 # [kW] inelastive_load_model.defaultVertices = [Vertex(0, 0, -6000.0, 1)] # Cross-reference asset & asset model inelastive_load_model.object = inelastive_load inelastive_load.model = inelastive_load_model # Add solar PV asset solar_pv = SolarPvResource() solar_pv.maximumPower = self.PV_max_kW # [avg.kW] solar_pv.minimumPower = 0.0 # [avg.kW] solar_pv.name = 'SolarPv' solar_pv.description = '120 kW solar PV site on the campus' # Add solar PV asset model solar_pv_model = SolarPvResourceModel() solar_pv_model.cloudFactor = 1.0 # dimensionless solar_pv_model.engagementCost = [0, 0, 0] solar_pv_model.name = 'SolarPvModel' solar_pv_model.defaultPower = 0.0 # [avg.kW] solar_pv_model.defaultVertices = [Vertex(0, 0, 30.0, True)] solar_pv_model.costParameters = [0, 0, 0] solar_pv_model.inject(self, power_topic=self.solar_topic) # Cross-reference asset & asset model solar_pv.model = solar_pv_model solar_pv_model.object = solar_pv # Add inelastive and solar_pv as campus' assets self.localAssets.extend([inelastive_load, solar_pv]) # Add Market market = Market() market.name = 'dayAhead' market.commitment = False market.converged = False market.defaultPrice = 0.04 # [$/kWh] market.dualityGapThreshold = self.duality_gap_threshold # [0.02 = 2#] market.initialMarketState = MarketState.Inactive market.marketOrder = 1 # This is first and only market market.intervalsToClear = 1 # Only one interval at a time market.futureHorizon = timedelta( hours=24) # Projects 24 hourly future intervals market.intervalDuration = timedelta( hours=1) # [h] Intervals are 1 h long market.marketClearingInterval = timedelta(hours=1) # [h] market.marketClearingTime = Timer.get_cur_time().replace( hour=0, minute=0, second=0, microsecond=0) # Aligns with top of hour market.nextMarketClearingTime = market.marketClearingTime + timedelta( hours=1) self.markets.append(market) # City object city = Neighbor() city.name = 'CoR' city.description = 'City of Richland (COR) electricity supplier node' city.maximumPower = 20000 # Remember loads have negative power [avg.kW] city.minimumPower = 0 # [avg.kW] city.lossFactor = self.city_loss_factor # City model city_model = NeighborModel() city_model.name = 'CoR_Model' city_model.location = self.name city_model.transactive = True city_model.defaultPower = 10000 # [avg.kW] city_model.defaultVertices = [ Vertex(0.046, 160, 0, True), Vertex(0.048, 160 + city.maximumPower * (0.046 + 0.5 * (0.048 - 0.046)), city.maximumPower, True) ] city_model.costParameters = [0, 0, 0] city_model.demand_threshold_coef = self.demand_threshold_coef city_model.demandThreshold = self.monthly_peak_power city_model.inject(self, system_loss_topic=self.system_loss_topic, dc_threshold_topic=self.dc_threshold_topic) # Cross-reference object & model city_model.object = city city.model = city_model self.city = city # Add city as campus' neighbor self.neighbors.append(city) # Add buildings for bldg_name in self.building_names: bldg_neighbor = self.make_bldg_neighbor(bldg_name) self.neighbors.append(bldg_neighbor)
### 1.2 only_title chage to tags val = Title_to_tag(train_path=train_path, val_path=val_path).change() ### 1.3 convert "tag" to "tag_id" tag_to_id, id_to_tag = tag_id_meta(train, val) train = convert_tag_to_id(train, tag_to_id) val = convert_tag_to_id(val, tag_to_id) ### 2. modeling : Neighbor ### 2.1 hyperparameters: pow_alpha, pow_beta pow_alpha = 0.65 pow_beta = 0.0 ### 2.2 run Neighbor.predict() : returns pandas.DataFrame pred = Neighbor(pow_alpha=pow_alpha, pow_beta=pow_beta, \ train=train, val=val, song_meta=song_meta).predict() ### 3. modeling : KNN ### 3.1 hyperparameters: k, rho, weights ### 3.2 parameters: sim_songs, sim_tags, sim_normalize song_k = 500 tag_k = 90 song_k_step = 50 tag_k_step = 10 rho = 0.4 weight_val_songs = 0.9 weight_pred_songs = 1 - weight_val_songs weight_val_tags = 0.7 weight_pred_tags = 1 - weight_val_tags sim_songs = 'idf'
def test_schedule(): print('Running AbstractModel.test_schedule()') pf = 'pass' # Create a test market test_mkt test_mkt = Market() # Create a sample time interval ti dt = datetime.now() at = dt # NOTE: Function Hours() corrects behavior of Matlab hours(). dur = timedelta(hours=1) mkt = test_mkt mct = dt # NOTE: Function Hours() corrects behavior of Matlab hours(). st = datetime.combine(date.today(), time()) + timedelta(hours=20) ti = TimeInterval(at, dur, mkt, mct, st) # Save the time interval test_mkt.timeIntervals = [ti] # Assign a marginal price in the time interval test_mkt.check_marginal_prices() # Create a Neighbor test object and give it a default maximum power value test_obj = Neighbor() test_obj.maximumPower = 100 # Create a corresponding NeighborModel test_mdl = NeighborModel() # Make sure that the model and object cross-reference one another test_obj.model = test_mdl test_mdl.object = test_obj # Run a test with a NeighborModel object print('- running test with a NeighborModel:') test_mdl.schedule(test_mkt) print(' - the method encountered no errors') if len(test_mdl.scheduledPowers) != 1: pf = 'fail' raise ' - the method did not store a scheduled power' else: print(' - the method calculated and stored a scheduled power') if len(test_mdl.reserveMargins) != 1: pf = 'fail' raise ' - the method did not store a reserve margin' else: print(' - the method stored a reserve margin') if len(test_mdl.activeVertices) != 1: pf = 'fail' raise ' - the method did not store an active vertex' else: print(' - the method stored an active vertex') # Run a test again with a LocalAssetModel object test_obj = LocalAsset() test_obj.maximumPower = 100 test_mdl = LocalAssetModel() test_obj.model = test_mdl test_mdl.object = test_obj print('- running test with a LocalAssetModel:') test_mdl.schedule(test_mkt) print(' - the method encountered no errors') if len(test_mdl.scheduledPowers) != 1: pf = 'fail' raise ' - the method did not store a scheduled power' else: print(' - the method calculated and stored a scheduled power') if len(test_mdl.reserveMargins) != 1: pf = 'fail' raise ' - the method did not store a reserve margin' else: print(' - the method stored a reserve margin') if len(test_mdl.activeVertices) != 1: pf = 'fail' raise ' - the method did not store an active vertex' else: print(' - the method stored an active vertex') # Success print('- the test ran to completion') print('Result: %s', pf)
def test_update_costs(): print('Running AbstractModel.test_update_costs()') pf = 'pass' # Create a test market test_mkt test_mkt = Market() # Create a sample time interval ti dt = datetime.now() at = dt # NOTE: Function Hours() corrects behavior of Matlab hours(). dur = timedelta(hours=1) mkt = test_mkt mct = dt st = datetime.combine(date.today(), time()) + timedelta(hours=20) ti = TimeInterval(at, dur, mkt, mct, st) # Save the time interval test_mkt.timeIntervals = [ti] # Assign a marginal price in the time interval test_mkt.check_marginal_prices() # Create a Neighbor test object and give it a default maximum power value test_obj = Neighbor() # test_obj.maximumPower = 100 # Create a corresponding NeighborModel test_mdl = NeighborModel() # Make sure that the model and object cross-reference one another test_obj.model = test_mdl test_mdl.object = test_obj test_mdl.scheduledPowers = [ IntervalValue(test_mdl, ti, test_mkt, MeasurementType.ScheduledPower, 100) ] test_mdl.activeVertices = [ IntervalValue(test_mdl, ti, test_mkt, MeasurementType.ActiveVertex, Vertex(0.05, 0, 100)) ] # Run a test with a NeighborModel object print('- running test with a NeighborModel:') try: test_mdl.update_costs(test_mkt) print(' - the method encountered no errors') except: pf = 'fail' raise ' - the method did not run without errors' if len(test_mdl.productionCosts) != 1: pf = 'fail' raise ' - the method did not store a production cost' else: print(' - the method calculated and stored a production cost') if len(test_mdl.dualCosts) != 1: pf = 'fail' raise ' - the method did not store a dual cost' else: print(' - the method stored a dual cost') if test_mdl.totalProductionCost != sum( [x.value for x in test_mdl.productionCosts]): pf = 'fail' raise ' - the method did not store a total production cost' else: print(' - the method stored an total production cost') if test_mdl.totalDualCost != sum([x.value for x in test_mdl.dualCosts]): pf = 'fail' raise ' - the method did not store a total dual cost' else: print(' - the method stored an total dual cost') # Run a test again with a LocalAssetModel object test_obj = LocalAsset() # test_obj.maximumPower = 100 test_mdl = LocalAssetModel() test_obj.model = test_mdl test_mdl.object = test_obj test_mdl.scheduledPowers = [ IntervalValue(test_mdl, ti, test_mkt, MeasurementType.ScheduledPower, 100) ] test_mdl.activeVertices = [ IntervalValue(test_mdl, ti, test_mkt, MeasurementType.ActiveVertex, Vertex(0.05, 0, 100)) ] print('- running test with a LocalAssetModel:') try: test_mdl.update_costs(test_mkt) print(' - the method encountered no errors') except: pf = 'fail' raise ' - the method did not run without errors' if len(test_mdl.productionCosts) != 1: pf = 'fail' raise ' - the method did not store a production cost' else: print(' - the method calculated and stored a production cost') if len(test_mdl.dualCosts) != 1: pf = 'fail' raise ' - the method did not store a dual cost' else: print(' - the method stored a dual cost') if test_mdl.totalProductionCost != sum( [x.value for x in test_mdl.productionCosts]): pf = 'fail' raise ' - the method did not store a total production cost' else: print(' - the method stored an total production cost') if test_mdl.totalDualCost != sum([x.value for x in test_mdl.dualCosts]): pf = 'fail' raise ' - the method did not store a total dual cost' else: print(' - the method stored an total dual cost') # Success print('- the test ran to completion') print('Result: %s', pf)
def add_neighbor(self, name, x, y): yield Neighbor(name=name, x=x, y=y).save(collection=self.neighbors)
def linkNodes(node1: Node, node2: Node): node1.addNeighbor(Neighbor(node2)) node2.addNeighbor(Neighbor(node1))