def create_electric_demand_curve(self, aggregate_air_demand): curve = PolyLine() for point in aggregate_air_demand.points: curve.add(Point(price=point.y, quantity=self.calcTotalLoad(point.x))) self.buyBidCurve = curve _log.debug("Report aggregated curve : {}".format(curve.points)) return curve
def translate_aggregate_demand(self, air_demand, index): electric_demand_curve = PolyLine() oat = self.oat_predictions[index] if self.oat_predictions else None for point in air_demand.points: electric_demand_curve.add(Point(price=point.y, quantity=self.model.calculate_load(point.x, oat))) _log.debug("{}: electric demand : {}".format(self.agent_name, electric_demand_curve.points)) return electric_demand_curve
def create_demand_curve(self, market_index, sched_index, occupied): """ Create demand curve. market_index (0-23) where next hour is 0 (or for single market 0 for next market). sched_index (0-23) is hour of day corresponding to market that demand_curve is being created. :param market_index: int; current market index where 0 is the next hour. :param sched_index: int; 0-23 corresponding to hour of day :param occupied: bool; true if occupied :return: """ _log.debug("%s create_demand_curve - index: %s - sched: %s", self.core.identity, market_index, sched_index) demand_curve = PolyLine() prices = self.determine_prices() self.update_prediction_error() for control, price in zip(self.ct_flexibility, prices): if occupied: _set = control else: _set = self.off_setpoint q = self.get_q(_set, sched_index, market_index, occupied) demand_curve.add(Point(price=price, quantity=q)) topic_suffix = "DemandCurve" message = { "MarketIndex": market_index, "Curve": demand_curve.tuppleize(), "Commodity": self.commodity } _log.debug("%s debug demand_curve - curve: %s", self.core.identity, demand_curve.points) self.publish_record(topic_suffix, message) return demand_curve
def combine_withoutincrement(lines): # we return a new PolyLine which is a composite (summed horizontally) of inputs composite = PolyLine() if len(lines) < 2: if isinstance(lines[0], list): for point in lines[0]: composite.add(Point(point[0], point[1])) return composite return lines[0] # find the range defined by the curves ys = [] for l in lines: ys = ys + l.vectorize()[1] ys = remove(ys) ys.sort(reverse=True) for y in ys: xt = None for line in lines: x = line.x(y) if x is not None: xt = x if xt is None else xt + x composite.add(Point(xt, y)) return composite
def create_supply_curve(self, clear_price, supply_market): index = self.supplier_market.index(supply_market) supply_curve = PolyLine() min_quantity = self.aggregate_demand[index].min_x()*0.8 max_quantity = self.aggregate_demand[index].max_x()*1.2 supply_curve.add(Point(price=clear_price, quantity=min_quantity)) supply_curve.add(Point(price=clear_price, quantity=max_quantity)) return supply_curve
def create_air_supply_curve(self, electric_price, electric_quantity): supply_curve = PolyLine() price = 65 quantity = 100000 supply_curve.add(Point(price=price,quantity=quantity)) price = 65 quantity = 0 # negative quantities are not real -1*10000 supply_curve.add(Point(price=price,quantity=quantity)) return supply_curve
def create_air_supply_curve(self, electric_price, electric_quantity): supply_curve = PolyLine() price = 65 quantity = 100000 supply_curve.add(Point(price=price, quantity=quantity)) price = 65 quantity = 0 # negative quantities are not real -1*10000 supply_curve.add(Point(price=price, quantity=quantity)) return supply_curve
def create_supply_curve(): supply_curve = PolyLine() price = 0 quantity = 0 supply_curve.add(Point(price,quantity)) price = 1000 quantity = 1000 supply_curve.add(Point(price,quantity)) return supply_curve
def translate_aggregate_demand(self, air_demand, index): electric_demand_curve = PolyLine() oat = self.oat_predictions[index] if self.oat_predictions else None for point in air_demand.points: electric_demand_curve.add(Point(price=point.y, quantity=self.model.calculate_load(point.x, oat))) _log.debug("{}: electric demand : {}".format(self.agent_name, electric_demand_curve.points)) # Hard-coding the market names is not ideal. Need to come up with more robust solution for market in self.consumer_market: self.consumer_demand_curve[market][index] = electric_demand_curve
def create_demand_curve(): demand_curve = PolyLine() price = 0 quantity = 1000 demand_curve.add(Point(price,quantity)) price = 1000 quantity = 0 demand_curve.add(Point(price,quantity)) return demand_curve
def create_supply_curve(): supply_curve = PolyLine() price = 0 quantity = 0 supply_curve.add(Point(price, quantity)) price = 1000 quantity = 1000 supply_curve.add(Point(price, quantity)) return supply_curve
def create_demand_curve(): demand_curve = PolyLine() price = 0 quantity = 1000 demand_curve.add(Point(price, quantity)) price = 1000 quantity = 0 demand_curve.add(Point(price, quantity)) return demand_curve
def create_supply_curve(self): supply_curve = PolyLine() price = self.price quantity = self.infinity supply_curve.add(Point(price=price, quantity=quantity)) price = self.price quantity = 0 supply_curve.add(Point(price=price, quantity=quantity)) return supply_curve
def create_supply_curve(self, clear_price, supply_market): _log.debug("{}: clear consumer market price {}".format( self.agent_name, clear_price)) index = self.supplier_market.index(supply_market) supply_curve = PolyLine() min_quantity = self.aggregate_demand[index].min_x() * 0.8 max_quantity = self.aggregate_demand[index].max_x() * 1.2 supply_curve.add(Point(price=clear_price, quantity=min_quantity)) supply_curve.add(Point(price=clear_price, quantity=max_quantity)) return supply_curve
def create_demand_curve(self): if self.power_min is not None and self.power_max is not None: demand_curve = PolyLine() price_min, price_max = self.generate_price_points() demand_curve.add(Point(price=price_max, quantity=self.power_min)) demand_curve.add(Point(price=price_min, quantity=self.power_max)) else: demand_curve = None self.demand_curve = demand_curve return demand_curve
def create_electric_demand_curve(self, aggregate_air_demand): electric_demand_curve = PolyLine() self.load = [] for point in aggregate_air_demand.points: electric_demand_curve.add( Point(price=point.y, quantity=self.calcTotalLoad(point.x))) self.load.append(point.x) _log.debug("{}: aggregated curve : {}".format( self.agent_name, electric_demand_curve.points)) return electric_demand_curve
def create_air_supply_curve(self, electric_price): _log.debug("{}: clear air price {}".format(self.agent_name, electric_price)) air_supply_curve = PolyLine() price = electric_price min_quantity = self.load[0] max_quantity = self.load[-1] air_supply_curve.add(Point(price=price, quantity=min_quantity)) air_supply_curve.add(Point(price=price, quantity=max_quantity)) return air_supply_curve
def create_demand_curve(self, index): demand_curve = PolyLine() price_min, price_max = self.determine_prices() quantity = self.determin_quantity(index) price = np.linspace(price_max, price_min, num=len(quantity)).tolist() for pr, qt in zip(price, quantity): demand_curve.add(Point(price=pr, quantity=qt)) _log.debug("{}: demand curve for {} - {}".format( self.agent_name, self.market_name[index], demand_curve.points)) return demand_curve
def translate_aggregate_demand(self, agg_demand, index): electric_supply_curve = PolyLine() if self.market_prices is not None: self.price = self.market_prices[0] else: self.price = (agg_demand.min_y() + agg_demand.max_y()) / 2 electric_supply_curve.add(Point(price=self.price, quantity=0)) electric_supply_curve.add(Point(price=self.price, quantity=10000)) _log.debug("{}: electric demand : {}".format( self.agent_name, electric_supply_curve.points)) self.supplier_curve[index] = electric_supply_curve
def create_demand_curve(self, load_index, index): demand_curve = PolyLine() price_min, price_max = self.determine_prices() try: qMin = self.q_uc[load_index] qMax = self.q_uc[load_index] _log.debug("{}: demand curve for {} - {}".format(self.agent_name, self.market_name[index], [(qMin, price_max), (qMax, price_min)])) demand_curve.add(Point(price=max(price_min, price_max), quantity=min(qMin, qMax))) demand_curve.add(Point(price=min(price_min, price_max), quantity=max(qMin, qMax))) except: demand_curve.add(Point(price=max(price_min, price_max), quantity=0.1)) demand_curve.add(Point(price=min(price_min, price_max), quantity=0.1)) return demand_curve
def create_demand_curve(self, load_index, index): demand_curve = PolyLine() price_min, price_max = self.determine_prices() try: if len(self.market_name) > 1: qMin = self.q_uc[load_index] qMax = self.q_uc[load_index] else: qMin = self.single_timestep_power qMax = self.single_timestep_power demand_curve.add( Point(price=max(price_min, price_max), quantity=min(qMin, qMax))) demand_curve.add( Point(price=min(price_min, price_max), quantity=max(qMin, qMax))) except: demand_curve.add( Point(price=max(price_min, price_max), quantity=0.1)) demand_curve.add( Point(price=min(price_min, price_max), quantity=0.1)) topic_suffix = "/".join([self.agent_name, "DemandCurve"]) message = { "MarketIndex": index, "Curve": demand_curve.tuppleize(), "Commodity": "Electric" } self.publish_record(topic_suffix, message) _log.debug("{} debug demand_curve - curve: {}".format( self.agent_name, demand_curve.points)) return demand_curve
def create_demand_curve(self, index, hvac_index, temp, oat): _log.debug( "{} debug demand_curve1 - index: {} - hvac_index: {}".format( self.agent_name, index, hvac_index)) demand_curve = PolyLine() prices = self.determine_prices() for i in range(len(prices)): if self.hvac_avail[hvac_index]: temp_stpt = self.tsets[i] else: temp_stpt = self.tMinAdjUnoc ontime = self.on[index] offtime = self.off[index] on = 0 t = float(temp) for j in range(60): if ontime and t > temp_stpt + 0.8 and ontime > self.onmin: offtime = 1 ontime = 0 t = self.getT(t, oat, 0, hvac_index) elif ontime: offtime = 0 ontime += 1 on += 1 t = self.getT(t, oat, 1, hvac_index) elif offtime and t < temp_stpt - 0.8 and offtime > self.offmin: offtime = 0 ontime = 1 on += 1 t = self.getT(t, oat, 1, hvac_index) elif offtime: offtime += 1 ontime = 0 t = self.getT(t, oat, 0, hvac_index) _log.debug( "{} Debug demand_curve2 - t: {} - temp_stpt: {} - ontime: {} - on: {}" .format(self.agent_name, t, temp_stpt, ontime, on)) demand_curve.add( Point(price=prices[i], quantity=on / 60.0 * self.Qrate)) _log.debug("{} debug demand_curve3 on {} - curve: {}".format( self.agent_name, on, demand_curve.points)) _log.debug("{} debug demand_curve4 - curve: {}".format( self.agent_name, demand_curve.points)) return demand_curve
def electric_price_callback(self, timestamp, market_name, buyer_seller, price, quantity): _log.debug("{}: cleared price {} for {} at timestep {}".format( self.agent_name, price, market_name, timestamp)) self.report_cleared_price(buyer_seller, market_name, price, quantity, timestamp) if price is not None: self.make_air_market_offer(price) _log.debug("{}: agent making offer on air market".format( self.agent_name)) else: supply_curve = PolyLine() supply_curve.add(Point(price=10, quantity=0.1)) supply_curve.add(Point(price=10, quantity=0.1)) success, message = self.make_offer(self.air_market_name, SELLER, supply_curve) if success: _log.debug("price_check: just use the place holder")
def create_demand_curve(self, index): hvac_index = self.determine_hvac_index(index) demand_curve = PolyLine() oat = self.oat_predictions[index] if self.oat_predictions else self.tOut prices = self.determine_prices() price_max_bound = max( max(prices) + 0.1 * max(prices), max(self.prices) + max(self.prices) * 0.1) price_min_bound = min( min(prices) + 0.1 * min(prices), min(self.prices) - min(self.prices) * 0.1) temp = self.temp[index] quantities = [] for i in range(len(prices)): if self.hvac_avail[hvac_index]: temp_stpt = self.tsets[i] else: temp_stpt = self.tMinAdjUnoc quantity = min( max(self.getM(oat, temp, temp_stpt, hvac_index), self.mDotMin), self.mDotMax) quantities.append(quantity) demand_curve.add(Point(price=price_max_bound, quantity=min(quantities))) prices.sort(reverse=True) quantities.sort() for i in range(len(prices)): demand_curve.add(Point(price=prices[i], quantity=quantities[i])) demand_curve.add(Point(price=price_min_bound, quantity=max(quantities))) _log.debug("{} debug demand_curve4 - curve: {}".format( self.agent_name, demand_curve.points)) _log.debug("{} market {} has cleared airflow: {}".format( self.agent_name, index, demand_curve.x(self.prices[index]))) return demand_curve
def air_aggregate_callback(self, timestamp, market_name, buyer_seller, aggregate_air_demand): if buyer_seller == BUYER: _log.debug("{} - Received aggregated {} curve".format( self.agent_name, market_name)) electric_demand = self.create_electric_demand_curve( aggregate_air_demand) success, message = self.make_offer(self.electric_market_name, BUYER, electric_demand) if success: _log.debug("{}: make a offer for {}".format( self.agent_name, market_name)) else: _log.debug("{}: offer for the {} was rejected".format( self.agent_name, market_name)) supply_curve = PolyLine() supply_curve.add(Point(price=10, quantity=0.001)) supply_curve.add(Point(price=10, quantity=0.001)) success, message = self.make_offer(self.air_market_name, SELLER, supply_curve) _log.debug("{}: offer for {} was accepted: {}".format( self.agent_name, self.air_market_name, success))
def create_demand_curve(self, market_index, sched_index, occupied): _log.debug("{} debug demand_curve - index: {} - sched: {}".format(self.agent_name, market_index, sched_index)) demand_curve = PolyLine() prices = self.determine_prices() ct_flx = [] for i in range(len(prices)): if occupied: _set = self.ct_flexibility[i] else: _set = self.off_setpoint ct_flx.append(_set) q = self.get_q(_set, sched_index, market_index, occupied) demand_curve.add(Point(price=prices[i], quantity=q)) ct_flx = [min(ct_flx), max(ct_flx)] if ct_flx else [] topic_suffix = "/".join([self.agent_name, "DemandCurve"]) message = {"MarketIndex": market_index, "Curve": demand_curve.tuppleize(), "Commodity": self.commodity} _log.debug("{} debug demand_curve - curve: {}".format(self.agent_name, demand_curve.points)) self.publish_record(topic_suffix, message) return demand_curve
def offer_callback(self, timestamp, market_name, buyer_seller): if market_name in self.market_names: # Get the price for the corresponding market idx = int(market_name.split('_')[-1]) price = self.prices[idx+1] #price *= 1000. # Convert to mWh to be compatible with the mixmarket # Quantity min_quantity = 0 max_quantity = 10000 # float("inf") # Create supply curve supply_curve = PolyLine() supply_curve.add(Point(quantity=min_quantity, price=price)) supply_curve.add(Point(quantity=max_quantity, price=price)) # Make offer _log.debug("{}: offer for {} as {} at {} - Curve: {} {}".format(self.agent_name, market_name, SELLER, timestamp, supply_curve.points[0], supply_curve.points[1])) success, message = self.make_offer(market_name, SELLER, supply_curve) _log.debug("{}: offer has {} - Message: {}".format(self.agent_name, success, message))
def combine(lines, increment): # we return a new PolyLine which is a composite (summed horizontally) of inputs composite = PolyLine() # find the range defined by the curves minY = None maxY = None for l in lines: minY = PolyLine.min(minY, l.min_y()) maxY = PolyLine.max(maxY, l.max_y()) # special case if the lines are already horizontal or None if minY == maxY: minSumX = None maxSumX = None for line in lines: minX = None maxX = None for point in line.points: minX = PolyLine.min(minX, point.x) maxX = PolyLine.max(maxX, point.x) minSumX = PolyLine.sum(minSumX, minX) maxSumX = PolyLine.sum(maxSumX, maxX) composite.add(Point(minSumX, minY)) if minX != maxX: composite.add(Point(maxSumX, maxY)) return composite # create an array of ys in equal increments, with highest first # this is assuming that price decreases with increase in demand (buyers!) # but seems to work with multiple suppliers? ys = sorted(np.linspace(minY, maxY, num=increment), reverse=True) # print ys # print minY, maxY # now find the cumulative x associated with each y in the array # starting with the highest y for y in ys: xt = None for line in lines: x = line.x(y, left=np.nan) # print x, y if x is not None: xt = x if xt is None else xt + x composite.add(Point(xt, y)) return composite
def create_supply_curve(self): supply_curve = PolyLine() if self.demand_limit: min_price = self.price_min max_price = self.price_max supply_curve.add( Point(price=min_price, quantity=self.demand_limit_threshold)) supply_curve.add( Point(price=max_price, quantity=self.demand_limit_threshold)) else: if self.prices is None: price = self.price elif self.price_index < len(self.prices) - 1: price = float(self.prices[self.price_index]) self.price_index = self.price_index + 1 else: self.price_index = 0 price = float(self.prices[self.price_index]) supply_curve.add(Point(price=price, quantity=self.infinity)) supply_curve.add(Point(price=price, quantity=0.0)) return supply_curve
def translate_aggregate_demand(self, agg_demand, index): electric_supply_curve = PolyLine() if self.demand_limit is not None: electric_supply_curve.add(Point(price=0, quantity=self.demand_limit)) electric_supply_curve.add(Point(price=1000, quantity=self.demand_limit)) else: if self.market_prices is not None: if self.market_type == "rtp": self.price = self.current_price else: self.price = self.market_prices[0] else: self.price = (agg_demand.min_y() + agg_demand.max_y())/2 min_q = agg_demand.min_x()*0.9 max_q = agg_demand.max_x()*1.1 electric_supply_curve.add(Point(price=self.price, quantity=min_q)) electric_supply_curve.add(Point(price=self.price, quantity=max_q)) _log.debug("{}: electric demand : {}".format(self.agent_name, electric_supply_curve.points)) self.supplier_curve[index] = electric_supply_curve
class LightAgent(MarketAgent, FirstOrderZone): """ The SampleElectricMeterAgent serves as a sample of an electric meter that sells electricity for a single building at a fixed price. """ def __init__(self, market_name,agent_name,k,qmax,Pabsnom,nonResponsive,verbose_logging,subscribing_topic, **kwargs): super(LightAgent, self).__init__(verbose_logging, **kwargs) self.market_name = market_name self.agent_name = agent_name self.k = k self.qmax = qmax self.Pabsnom=Pabsnom self.nonResponsive = nonResponsive self.iniState() self.subscribing_topic=subscribing_topic self.join_market(self.market_name, BUYER, None, self.offer_callback, None, self.price_callback, self.error_callback) @Core.receiver('onstart') def setup(self, sender, **kwargs): _log.debug('Subscribing to '+'devices/CAMPUS/BUILDING1/AHU1/all') self.vip.pubsub.subscribe(peer='pubsub', prefix='devices/CAMPUS/BUILDING1/AHU1/all', callback=self.updateState) def offer_callback(self, timestamp, market_name, buyer_seller): result,message=self.make_offer(market_name, buyer_seller, self.create_demand_curve()) _log.debug("results of the make offer {}".format(result)) if not result: _log.debug("the new lightingt (maintain{}".format(self.qMax)) gevent.sleep(random.random()) self.vip.rpc.call('platform.actuator','set_point', self.agent_name,self.subscribing_topic+'/'+self.agent_name,round(self.qNorm,2)).get(timeout=6) def create_demand_curve(self): self.demand_curve = PolyLine() pMin = 10 pMax = 100 if (self.hvacAvail > 0): self.demand_curve.add(Point(price=min(pMin, pMax),quantity=max(self.qMin, self.qMax)*self.Pabsnom)) self.demand_curve.add(Point(price=max(pMin, pMax),quantity=min(self.qMin, self.qMax)*self.Pabsnom)) else: self.demand_curve.add(Point(price=max(pMin, pMax), quantity=0)) self.demand_curve.add(Point(price=min(pMin, pMax),quantity=0)) return self.demand_curve def iniState(self): self.hvacAvail = 1 self.pClear = None self.qMin = 0.7 self.qMax = self.qmax self.qNorm=self.qMax self.qClear=self.qNorm def updateState(self, peer, sender, bus, topic, headers, message): '''Subscribe to device data from message bus ''' _log.debug('Received one new dataset') info = {} for key, value in message[0].items(): info[key] = value self.hvacAvail = info['SupplyFanStatus'] if (self.hvacAvail > 0): self.qNorm=self.qMax else: self.qNorm=0 def updateSet(self): if self.pClear is not None and not self.nonResponsive and self.hvacAvail: self.qClear = self.clamp(self.demand_curve.x(self.pClear), self.qMax, self.qMin) else: self.qClear = 0 # if self.qClear is None: # self.qClear = 0. def clamp(self, value, x1, x2): minValue = min(x1, x2) maxValue = max(x1, x2) return min(max(value, minValue), maxValue) def price_callback(self, timestamp, market_name, buyer_seller, price, quantity): _log.debug("the price is {}".format(price)) self.pClear=price if self.pClear is not None: self.updateSet() _log.debug("the new lightingt is {}".format(self.qClear)) gevent.sleep(random.random()) self.vip.rpc.call('platform.actuator','set_point', self.agent_name,self.subscribing_topic+'/'+self.agent_name,round(self.qClear,2)).get(timeout=5) def error_callback(self, timestamp, market_name, buyer_seller, error_code, error_message, aux): _log.debug("the new lightingt is {}".format(self.qNorm)) self.vip.rpc.call('platform.actuator','set_point', self.agent_name,self.subscribing_topic+'/'+self.agent_name,round(self.qNorm,2)).get(timeout=5) def ease(self, target, current, limit): return current - np.sign(current-target)*min(abs(current-target), abs(limit))
def test_poly_line_add_points_is_sorted(): line = PolyLine() line.add(Point(4,8)) line.add(Point(2,4)) assert line.points[0].x == 2
class LightAgent(MarketAgent, FirstOrderZone): """ The SampleElectricMeterAgent serves as a sample of an electric meter that sells electricity for a single building at a fixed price. """ def __init__(self, market_name, agent_name, k, qmax, Pabsnom, nonResponsive, verbose_logging, subscribing_topic, **kwargs): super(LightAgent, self).__init__(verbose_logging, **kwargs) self.market_name = market_name self.agent_name = agent_name self.k = k self.qmax = qmax self.Pabsnom = Pabsnom self.nonResponsive = nonResponsive self.iniState() self.subscribing_topic = subscribing_topic self.join_market(self.market_name, BUYER, None, self.offer_callback, None, self.price_callback, self.error_callback) @Core.receiver('onstart') def setup(self, sender, **kwargs): _log.debug('Subscribing to ' + 'devices/CAMPUS/BUILDING1/AHU1/all') self.vip.pubsub.subscribe(peer='pubsub', prefix='devices/CAMPUS/BUILDING1/AHU1/all', callback=self.updateState) def offer_callback(self, timestamp, market_name, buyer_seller): result, message = self.make_offer(market_name, buyer_seller, self.create_demand_curve()) _log.debug("results of the make offer {}".format(result)) if not result: _log.debug("the new lightingt (maintain{}".format(self.qMax)) gevent.sleep(random.random()) self.vip.rpc.call('platform.actuator', 'set_point', self.agent_name, self.subscribing_topic + '/' + self.agent_name, round(self.qNorm, 2)).get(timeout=6) def create_demand_curve(self): self.demand_curve = PolyLine() pMin = 10 pMax = 100 if (self.hvacAvail > 0): self.demand_curve.add( Point(price=min(pMin, pMax), quantity=max(self.qMin, self.qMax) * self.Pabsnom)) self.demand_curve.add( Point(price=max(pMin, pMax), quantity=min(self.qMin, self.qMax) * self.Pabsnom)) else: self.demand_curve.add(Point(price=max(pMin, pMax), quantity=0)) self.demand_curve.add(Point(price=min(pMin, pMax), quantity=0)) return self.demand_curve def iniState(self): self.hvacAvail = 1 self.pClear = None self.qMin = 0.7 self.qMax = self.qmax self.qNorm = self.qMax self.qClear = self.qNorm def updateState(self, peer, sender, bus, topic, headers, message): '''Subscribe to device data from message bus ''' _log.debug('Received one new dataset') info = message[0].copy() self.hvacAvail = info['SupplyFanStatus'] if (self.hvacAvail > 0): self.qNorm = self.qMax else: self.qNorm = 0 def updateSet(self): if self.pClear is not None and not self.nonResponsive and self.hvacAvail: self.qClear = self.clamp(self.demand_curve.x(self.pClear), self.qMax, self.qMin) else: self.qClear = 0 # if self.qClear is None: # self.qClear = 0. def clamp(self, value, x1, x2): minValue = min(x1, x2) maxValue = max(x1, x2) return min(max(value, minValue), maxValue) def price_callback(self, timestamp, market_name, buyer_seller, price, quantity): _log.debug("the price is {}".format(price)) self.pClear = price if self.pClear is not None: self.updateSet() _log.debug("the new lightingt is {}".format(self.qClear)) gevent.sleep(random.random()) self.vip.rpc.call('platform.actuator', 'set_point', self.agent_name, self.subscribing_topic + '/' + self.agent_name, round(self.qClear, 2)).get(timeout=5) def error_callback(self, timestamp, market_name, buyer_seller, error_code, error_message, aux): _log.debug("the new lightingt is {}".format(self.qNorm)) self.vip.rpc.call('platform.actuator', 'set_point', self.agent_name, self.subscribing_topic + '/' + self.agent_name, round(self.qNorm, 2)).get(timeout=5) def ease(self, target, current, limit): return current - np.sign(current - target) * min( abs(current - target), abs(limit))
class VAVAgent(MarketAgent, FirstOrderZone): """ The SampleElectricMeterAgent serves as a sample of an electric meter that sells electricity for a single building at a fixed price. """ def __init__(self, market_name, agent_name, x0, x1, x2, x3, x4, c0, c1, c2, c3, c4, tMinAdj, tMaxAdj, mDotMin, mDotMax, tIn, nonResponsive, verbose_logging, subscribing_topic, **kwargs): super(VAVAgent, self).__init__(verbose_logging, **kwargs) self.market_name = market_name self.agent_name = agent_name self.x0 = x0 self.x1 = x1 self.x2 = x2 self.x3 = x3 self.x4 = x4 self.c0 = c0 self.c1 = c1 self.c2 = c2 self.c3 = c3 self.c4 = c4 self.tMinAdj = tMinAdj self.tMaxAdj = tMaxAdj self.tNomAdj = tIn self.tIn = tIn self.mDotMin = mDotMin self.mDotMax = mDotMax self.nonResponsive = nonResponsive self.iniState() self.subscribing_topic = subscribing_topic self.join_market(self.market_name, BUYER, None, self.offer_callback, None, self.price_callback, self.error_callback) @Core.receiver('onstart') def setup(self, sender, **kwargs): _log.debug('Subscribing to ' + self.subscribing_topic) self.vip.pubsub.subscribe(peer='pubsub', prefix=self.subscribing_topic, callback=self.updateState) def offer_callback(self, timestamp, market_name, buyer_seller): self.make_offer(market_name, buyer_seller, self.create_demand_curve()) def create_demand_curve(self): self.demand_curve = PolyLine() pMin = 10 pMax = 100 qMin = abs(self.getQMin()) qMax = abs(self.getQMax()) if (self.hvacAvail > 0): self.demand_curve.add( Point(price=max(pMin, pMax), quantity=min(qMin, qMax))) self.demand_curve.add( Point(price=min(pMin, pMax), quantity=max(qMin, qMax))) else: self.demand_curve.add(Point(price=max(pMin, pMax), quantity=0)) self.demand_curve.add(Point(price=min(pMin, pMax), quantity=0)) return self.demand_curve def iniState(self): self.hvacAvail = 1 self.tSupHvac = 12.78 self.tOut = 32 self.mDot = 1.0 self.tSup = 12.78 self.standby = 0 self.occupied = 0 self.tSet = 22 self.tDel = 0.5 self.tEase = 0.25 self.qHvacSens = self.mDot * 1006. * (self.tSup - self.tNomAdj) self.qMin = min(0, self.mDotMin * 1006. * (self.tSupHvac - self.tNomAdj)) self.qMax = min(0, self.mDotMax * 1006. * (self.tSupHvac - self.tNomAdj)) self.pClear = None def updateState(self, peer, sender, bus, topic, headers, message): '''Subscribe to device data from message bus ''' _log.debug('Received one new dataset') info = message[0].copy() self.hvacAvail = info['SupplyFanStatus'] self.tSupHvac = info['DischargeAirTemperature'] self.tOut == info['OutdoorAirTemperature'] self.mDot = info['VAV' + self.agent_name + '_ZoneAirFlow'] self.tSup = info['VAV' + self.agent_name + '_ZoneDischargeAirTemperature'] self.tIn = info['VAV' + self.agent_name + '_ZoneTemperature'] self.qHvacSens = self.mDot * 1006. * (self.tSup - self.tIn) self.qMin = min(0, self.mDotMin * 1006. * (self.tSupHvac - self.tIn)) self.qMax = min(0, self.mDotMax * 1006. * (self.tSupHvac - self.tIn)) def updateTSet(self): if self.pClear is not None and not self.nonResponsive and self.hvacAvail: self.qClear = self.clamp(-self.demand_curve.y(self.pClear), self.qMax, self.qMin) self.tSet = self.clamp(self.getT(self.qClear), self.tMinAdj, self.tMaxAdj) else: self.tSet = self.clamp( self.ease(self.tNomAdj, self.tSet, self.tEase), self.tMinAdj, self.tMaxAdj) self.qClear = self.clamp(self.getQ(self.tSet), self.qMax, self.qMin) if self.qClear is None: self.qClear = 0. def getQMin(self): t = self.clamp(self.tSet + self.tDel, self.tMinAdj, self.tMaxAdj) q = self.clamp(self.getQ(t), self.qMax, self.qMin) return q def getQMax(self): t = self.clamp(self.tSet - self.tDel, self.tMinAdj, self.tMaxAdj) q = self.clamp(self.getQ(t), self.qMax, self.qMin) return q def clamp(self, value, x1, x2): minValue = min(x1, x2) maxValue = max(x1, x2) return min(max(value, minValue), maxValue) def price_callback(self, timestamp, market_name, buyer_seller, price, quantity): _log.debug("the price is {}".format(price)) self.pClear = price self.updateTSet() _log.debug("the new set point is {}".format(self.tSet)) _log.debug("the set point is {}".format( self.subscribing_topic.replace('all', '') + 'VAV' + self.agent_name + '/ZoneCoolingTemperatureSetPoint')) self.vip.rpc.call( 'platform.actuator', 'set_point', self.agent_name, self.subscribing_topic.replace('all', '') + 'VAV' + self.agent_name + '/ZoneCoolingTemperatureSetPoint', self.tSet).get(timeout=5) def error_callback(self, timestamp, market_name, buyer_seller, error_code, error_message, aux): if error_code == NO_INTERSECT: self.vip.rpc.call( 'platform.actuator', 'set_point', self.agent_name, self.subscribing_topic.replace('all', '') + 'VAV' + self.agent_name + '/ZoneCoolingTemperatureSetPoint', self.tNomAdj).get(timeout=5) def ease(self, target, current, limit): return current - np.sign(current - target) * min( abs(current - target), abs(limit))
def fromTupples(points): polyLine = PolyLine() for p in points: if p is not None and len(p) == 2: polyLine.add(Point(p[0], p[1])) return polyLine
class VAVAgent(MarketAgent, FirstOrderZone): """ The SampleElectricMeterAgent serves as a sample of an electric meter that sells electricity for a single building at a fixed price. """ def __init__(self, market_name, agent_name, x0, x1, x2, x3, x4, c0, c1, c2, c3, c4, tMinAdj, tMaxAdj, mDotMin, mDotMax, tIn, nonResponsive, verbose_logging, device_topic, device_points, parent_device_topic, parent_device_points, base_rpc_path, activate_topic, actuator, mode, setpoint_mode, sim_flag, **kwargs): super(VAVAgent, self).__init__(verbose_logging, **kwargs) self.market_name = market_name self.agent_name = agent_name self.x0 = x0 self.x1 = x1 self.x2 = x2 self.x3 = x3 self.x4 = x4 self.c0 = c0 self.c1 = c1 self.c2 = c2 self.c3 = c3 self.c4 = c4 self.hvac_avail = 0 self.tOut = 32 self.zone_airflow = 10 self.zone_datemp = 12.78 self.tDel = 0.25 self.t_ease = 0.25 self.tNomAdj = tIn self.temp_stpt = self.tNomAdj self.tIn = self.tNomAdj self.p_clear = None self.q_clear = None self.demand_curve = None self.tMinAdj = tMinAdj self.tMaxAdj = tMaxAdj self.mDotMin = mDotMin self.mDotMax = mDotMax self.qHvacSens = self.zone_airflow * 1006. * (self.zone_datemp - self.tIn) self.qMin = min(0, self.mDotMin * 1006. * (self.zone_datemp - self.tIn)) self.qMax = min(0, self.mDotMax * 1006. * (self.zone_datemp - self.tIn)) self.default = None self.actuator = actuator self.mode = mode self.nonResponsive = nonResponsive self.sim_flag = sim_flag if self.sim_flag: self.actuate_enabled = 1 else: self.actuate_enabled = 0 self.setpoint_offset = 0.0 if isinstance(setpoint_mode, dict): self.mode_status = True self.status_point = setpoint_mode["point"] self.setpoint_mode_true_offset = setpoint_mode["true_value"] self.setpoint_mode_false_offset = setpoint_mode["false_value"] else: self.mode_status = False self.device_topic = device_topic self.parent_device_topic = parent_device_topic self.actuator_topic = base_rpc_path self.activate_topic = activate_topic # Parent device point mapping (AHU level points) self.supply_fan_status = parent_device_points.get("supply_fan_status", "SupplyFanStatus") self.outdoor_air_temperature = parent_device_points.get("outdoor_air_temperature", "OutdoorAirTemperature") # Device point mapping (VAV level points) self.zone_datemp_name = device_points.get("zone_dat", "ZoneDischargeAirTemperature") self.zone_airflow_name = device_points.get("zone_airflow", "ZoneAirFlow") self.zone_temp_name = device_points.get("zone_temperature", "ZoneTemperature") self.join_market(self.market_name, BUYER, None, self.offer_callback, None, self.price_callback, self.error_callback) @Core.receiver('onstart') def setup(self, sender, **kwargs): _log.debug('Subscribing to device' + self.device_topic) self.vip.pubsub.subscribe(peer='pubsub', prefix=self.device_topic, callback=self.update_zone_state) _log.debug('Subscribing to parent' + self.parent_device_topic) self.vip.pubsub.subscribe(peer='pubsub', prefix=self.parent_device_topic, callback=self.update_state) _log.debug('Subscribing to ' + self.activate_topic) self.vip.pubsub.subscribe(peer='pubsub', prefix=self.activate_topic, callback=self.update_actuation_state) def offer_callback(self, timestamp, market_name, buyer_seller): result, message = self.make_offer(market_name, buyer_seller, self.create_demand_curve()) _log.debug("{}: demand max {} and min {} at {}".format(self.agent_name, -self.demand_curve.x(10), -self.demand_curve.x(100), timestamp)) _log.debug("{}: result of the make offer {} at {}".format(self.agent_name, result, timestamp)) if not result: _log.debug("{}: maintain old set point {}".format(self.agent_name, self.temp_stpt)) if self.sim_flag: self.actuate_setpoint() def create_demand_curve(self): self.demand_curve = PolyLine() p_min = 10. p_max = 100. qMin = abs(self.get_q_min()) qMax = abs(self.get_q_max()) if self.hvac_avail: self.demand_curve.add(Point(price=max(p_min, p_max), quantity=min(qMin, qMax))) self.demand_curve.add(Point(price=min(p_min, p_max), quantity=max(qMin, qMax))) else: self.demand_curve.add(Point(price=max(p_min, p_max), quantity=0.1)) self.demand_curve.add(Point(price=min(p_min, p_max), quantity=0.1)) if self.hvac_avail: _log.debug("{} - Tout {} - Tin {} - q {}".format(self.agent_name, self.tOut, self.tIn, self.qHvacSens)) return self.demand_curve def update_zone_state(self, peer, sender, bus, topic, headers, message): """ Subscribe to device data from message bus :param peer: :param sender: :param bus: :param topic: :param headers: :param message: :return: """ _log.debug('{} received zone info'.format(self.agent_name)) info = message[0] if not self.sim_flag: self.zone_datemp = temp_f2c(info[self.zone_datemp_name]) self.zone_airflow = flow_cfm2cms(info[self.zone_airflow_name]) self.tIn = temp_f2c(info[self.zone_temp_name]) else: self.zone_datemp = info[self.zone_datemp_name] self.zone_airflow = info[self.zone_airflow_name] self.tIn = info[self.zone_temp_name] if self.mode_status: if info[self.status_point]: self.setpoint_offset = self.setpoint_mode_true_offset _log.debug("Setpoint offset: {}".format(self.setpoint_offset)) else: self.setpoint_offset = self.setpoint_mode_false_offset _log.debug("Setpoint offset: {}".format(self.setpoint_offset)) self.qHvacSens = self.zone_airflow * 1006. * (self.zone_datemp - self.tIn) self.qMin = min(0, self.mDotMin * 1006. * (self.zone_datemp - self.tIn)) self.qMax = min(0, self.mDotMax * 1006. * (self.zone_datemp - self.tIn)) def update_state(self, peer, sender, bus, topic, headers, message): """ Subscribe to device data from message bus. :param peer: :param sender: :param bus: :param topic: :param headers: :param message: :return: """ _log.debug('{} received one parent_device ' 'information on: {}'.format(self.agent_name, topic)) info = message[0] if not self.sim_flag: self.tOut = temp_f2c(info[self.outdoor_air_temperature]) else: self.tOut = info[self.outdoor_air_temperature] self.hvac_avail = info[self.supply_fan_status] def update_actuation_state(self, peer, sender, bus, topic, headers, message): """ Subscribe to device data from message bus. :param peer: :param sender: :param bus: :param topic: :param headers: :param message: :return: """ _log.debug('{} received update actuation.'.format(self.agent_name)) _log.debug("Current actuation state: {} - '" "update actuation state: {}".format(self.actuate_enabled, message)) if not self.actuate_enabled and message: self.default = self.vip.rpc.call(self.actuator, 'get_point', self.actuator_topic).get(timeout=10) self.actuate_enabled = message if not self.actuate_enabled: if self.mode == 1: self.vip.rpc.call(self.actuator, 'set_point', self.agent_name, self.actuator_topic, None).get(timeout=10) else: if self.default is not None: self.vip.rpc.call(self.actuator, 'set_point', self.agent_name, self.actuator_topic, self.default).get(timeout=10) def update_setpoint(self): if self.p_clear is not None and not self.nonResponsive and self.hvac_avail: self.q_clear = clamp(-self.demand_curve.x(self.p_clear), self.qMax, self.qMin) self.temp_stpt = clamp(self.getT(self.q_clear), self.tMinAdj, self.tMaxAdj) else: self.temp_stpt = clamp(ease(self.tNomAdj, self.temp_stpt, self.t_ease), self.tMinAdj, self.tMaxAdj) self.q_clear = clamp(self.getQ(self.temp_stpt), self.qMax, self.qMin) if self.q_clear is None: self.q_clear = 0. def get_q_min(self): t = self.tMaxAdj q = clamp(self.getQ(t), self.qMax, self.qMin) return q def get_q_max(self): # t = self.clamp(self.temp_stpt-self.tDel, self.tMinAdj, self.tMaxAdj) t = self.tMinAdj q = clamp(self.getQ(t), self.qMax, self.qMin) return q def price_callback(self, timestamp, market_name, buyer_seller, price, quantity): _log.debug("{} - price of {} for market: {}".format(self.agent_name, price, market_name)) self.p_clear = price if not self.qMax and not self.qMin and not self.sim_flag: self.update_actuation_state(None, None, None, None, None, 0) return if self.p_clear is not None: self.update_setpoint() _log.debug("New set point is {}".format(self.temp_stpt)) self.actuate_setpoint() def error_callback(self, timestamp, market_name, buyer_seller, error_code, error_message, aux): _log.debug("{} - error for Market: {} {}, Message: {}".format(self.agent_name, market_name, buyer_seller, aux)) if self.actuate_enabled: if market_name == "electric": if aux.get('SQx,DQn', 0) == -1: self.temp_stpt = self.tMaxAdj self.actuate_setpoint() return if self.sim_flag: self.temp_stpt = self.tNomAdj self.actuate_setpoint() def actuate_setpoint(self): temp_stpt = self.temp_stpt - self.setpoint_offset if self.actuate_enabled: _log.debug("{} - setting {} with value {}".format(self.agent_name, self.actuator_topic, temp_stpt)) self.vip.rpc.call(self.actuator, 'set_point', self.agent_name, self.actuator_topic, temp_stpt).get(timeout=10)
def test_poly_line_add_one_point(): line = PolyLine() line.add(Point(4,8)) assert len(line.points) == 1
def test_poly_line_add_two_points(): line = PolyLine() line.add(Point(4,8)) line.add(Point(2,4)) assert len(line.points) == 2