text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def if_none_match(self): """ Get the if-none-match option of a request. :return: True, if if-none-match is present :rtype : bool """
for option in self.options: if option.number == defines.OptionRegistry.IF_NONE_MATCH.number: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_if_none_match(self): """ Add the if-none-match option to the request. """
option = Option() option.number = defines.OptionRegistry.IF_NONE_MATCH.number option.value = None self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proxy_uri(self): """ Get the Proxy-Uri option of a request. :return: the Proxy-Uri values or None if not specified by the request :rtype : String """
for option in self.options: if option.number == defines.OptionRegistry.PROXY_URI.number: return option.value return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proxy_uri(self, value): """ Set the Proxy-Uri option of a request. :param value: the Proxy-Uri value """
option = Option() option.number = defines.OptionRegistry.PROXY_URI.number option.value = str(value) self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proxy_schema(self): """ Get the Proxy-Schema option of a request. :return: the Proxy-Schema values or None if not specified by the request :rtype : String """
for option in self.options: if option.number == defines.OptionRegistry.PROXY_SCHEME.number: return option.value return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proxy_schema(self, value): """ Set the Proxy-Schema option of a request. :param value: the Proxy-Schema value """
option = Option() option.number = defines.OptionRegistry.PROXY_SCHEME.number option.value = str(value) self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_add(self, request, response): """ checks for full cache and valid code before updating the cache :param request: :param response: :return: """
logger.debug("adding response to the cache") """ checking for valid code - """ code = response.code try: utils.check_code(code) except utils.InvalidResponseCode: # pragma no cover logger.error("Invalid response code") return """ return if max_age is 0 """ if response.max_age == 0: return """ Initialising new cache element based on the mode and updating the cache """ if self.mode == defines.FORWARD_PROXY: new_key = CacheKey(request) else: new_key = ReverseCacheKey(request) logger.debug("MaxAge = {maxage}".format(maxage=response.max_age)) new_element = CacheElement(new_key, response, request, response.max_age) self.cache.update(new_key, new_element) logger.debug("Cache Size = {size}".format(size=self.cache.debug_print()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_related(self, request): logger.debug("Cache Search Request") if self.cache.is_empty() is True: logger.debug("Empty Cache") return None """ extracting everything from the cache """
result = [] items = list(self.cache.cache.items()) for key, item in items: element = self.cache.get(item.key) logger.debug("Element : {elm}".format(elm=str(element))) if request.proxy_uri == element.uri: result.append(item) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_response(self, request): """ creates a key from the request and searches the cache with it :param request: :return CacheElement: returns None if there's a cache miss """
logger.debug("Cache Search Response") if self.cache.is_empty() is True: logger.debug("Empty Cache") return None """ create a new cache key from the request """ if self.mode == defines.FORWARD_PROXY: search_key = CacheKey(request) else: search_key = ReverseCacheKey(request) response = self.cache.get(search_key) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, request, response): """ refreshes a resource when a validation response is received :param request: :param response: :return: """
element = self.search_response(request) if element is not None: element.cached_response.options = response.options element.freshness = True element.max_age = response.max_age element.creation_time = time.time() element.uri = request.proxy_uri
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _forward_request(transaction, destination, path): """ Forward requests. :type transaction: Transaction :param transaction: the transaction that owns the request :param destination: the destination of the request (IP, port) :param path: the path of the request. :rtype : Transaction :return: the edited transaction """
client = HelperClient(destination) request = Request() request.options = copy.deepcopy(transaction.request.options) del request.block2 del request.block1 del request.uri_path del request.proxy_uri del request.proxy_schema # TODO handle observing del request.observe # request.observe = transaction.request.observe request.uri_path = path request.destination = destination request.payload = transaction.request.payload request.code = transaction.request.code response = client.send_request(request) client.stop() if response is not None: transaction.response.payload = response.payload transaction.response.code = response.code transaction.response.options = response.options else: transaction.response.code = defines.Codes.SERVICE_UNAVAILABLE.number return transaction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Stop the client. """
self.stopped.set() for event in self.to_be_stopped: event.set() if self._receiver_thread is not None: self._receiver_thread.join() self._socket.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_message(self, message): """ Prepare a message to send on the UDP socket. Eventually set retransmissions. :param message: the message to send """
if isinstance(message, Request): request = self._requestLayer.send_request(message) request = self._observeLayer.send_request(request) request = self._blockLayer.send_request(request) transaction = self._messageLayer.send_request(request) self.send_datagram(transaction.request) if transaction.request.type == defines.Types["CON"]: self._start_retransmission(transaction, transaction.request) elif isinstance(message, Message): message = self._observeLayer.send_empty(message) message = self._messageLayer.send_empty(None, None, message) self.send_datagram(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wait_for_retransmit_thread(transaction): """ Only one retransmit thread at a time, wait for other to finish """
if hasattr(transaction, 'retransmit_thread'): while transaction.retransmit_thread is not None: logger.debug("Waiting for retransmit thread to finish ...") time.sleep(0.01) continue
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_datagram(self, message): """ Send a message over the UDP socket. :param message: the message to send """
host, port = message.destination logger.debug("send_datagram - " + str(message)) serializer = Serializer() raw_message = serializer.serialize(message) try: self._socket.sendto(raw_message, (host, port)) except Exception as e: if self._cb_ignore_write_exception is not None and isinstance(self._cb_ignore_write_exception, collections.Callable): if not self._cb_ignore_write_exception(e, self): raise # if you're explicitly setting that you don't want a response, don't wait for it # https://tools.ietf.org/html/rfc7967#section-2.1 for opt in message.options: if opt.number == defines.OptionRegistry.NO_RESPONSE.number: if opt.value == 26: return if self._receiver_thread is None or not self._receiver_thread.isAlive(): self._receiver_thread = threading.Thread(target=self.receive_datagram) self._receiver_thread.daemon = True self._receiver_thread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start_retransmission(self, transaction, message): """ Start the retransmission task. :type transaction: Transaction :param transaction: the transaction that owns the message that needs retransmission :type message: Message :param message: the message that needs the retransmission task """
with transaction: if message.type == defines.Types['CON']: future_time = random.uniform(defines.ACK_TIMEOUT, (defines.ACK_TIMEOUT * defines.ACK_RANDOM_FACTOR)) transaction.retransmit_stop = threading.Event() self.to_be_stopped.append(transaction.retransmit_stop) transaction.retransmit_thread = threading.Thread(target=self._retransmit, name=str('%s-Retry-%d' % (threading.current_thread().name, message.mid)), args=(transaction, message, future_time, 0)) transaction.retransmit_thread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_datagram(self): """ Receive datagram from the UDP socket and invoke the callback function. """
logger.debug("Start receiver Thread") while not self.stopped.isSet(): self._socket.settimeout(0.1) try: datagram, addr = self._socket.recvfrom(1152) except socket.timeout: # pragma: no cover continue except Exception as e: # pragma: no cover if self._cb_ignore_read_exception is not None and isinstance(self._cb_ignore_read_exception, collections.Callable): if self._cb_ignore_read_exception(e, self): continue return else: # pragma: no cover if len(datagram) == 0: logger.debug("Exiting receiver Thread due to orderly shutdown on server end") return serializer = Serializer() try: host, port = addr except ValueError: host, port, tmp1, tmp2 = addr source = (host, port) message = serializer.deserialize(datagram, source) if isinstance(message, Response): logger.debug("receive_datagram - " + str(message)) transaction, send_ack = self._messageLayer.receive_response(message) if transaction is None: # pragma: no cover continue self._wait_for_retransmit_thread(transaction) if send_ack: self._send_ack(transaction) self._blockLayer.receive_response(transaction) if transaction.block_transfer: self._send_block_request(transaction) continue elif transaction is None: # pragma: no cover self._send_rst(transaction) return self._observeLayer.receive_response(transaction) if transaction.notification: # pragma: no cover ack = Message() ack.type = defines.Types['ACK'] ack = self._messageLayer.send_empty(transaction, transaction.response, ack) self.send_datagram(ack) self._callback(transaction.response) else: self._callback(transaction.response) elif isinstance(message, Message): self._messageLayer.receive_empty(message) logger.debug("Exiting receiver Thread due to request")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_rst(self, transaction): # pragma: no cover """ Sends an RST message for the response. :param transaction: transaction that holds the response """
rst = Message() rst.type = defines.Types['RST'] if not transaction.response.acknowledged: rst = self._messageLayer.send_empty(transaction, transaction.response, rst) self.send_datagram(rst)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_request(self, transaction): """ checks the cache for a response to the request :param transaction: :return: """
transaction.cached_element = self.cache.search_response(transaction.request) if transaction.cached_element is None: transaction.cacheHit = False else: transaction.response = transaction.cached_element.cached_response transaction.response.mid = transaction.request.mid transaction.cacheHit = True age = transaction.cached_element.creation_time + transaction.cached_element.max_age - time.time() if transaction.cached_element.freshness is True: if age <= 0: logger.debug("resource not fresh") """ if the resource is not fresh, its Etag must be added to the request so that the server might validate it instead of sending a new one """ transaction.cached_element.freshness = False """ ensuring that the request goes to the server """ transaction.cacheHit = False logger.debug("requesting etag %s", transaction.response.etag) transaction.request.etag = transaction.response.etag else: transaction.response.max_age = age else: transaction.cacheHit = False return transaction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_response(self, transaction): """ updates the cache with the response if there was a cache miss :param transaction: :return: """
if transaction.cacheHit is False: """ handling response based on the code """ logger.debug("handling response") self._handle_response(transaction) return transaction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_response(self, transaction): """ handles responses based on their type :param transaction: :return: """
code = transaction.response.code utils.check_code(code) """ VALID response: change the current cache value by switching the option set with the one provided also resets the timestamp if the request etag is different from the response, send the cached response """ if code == Codes.VALID.number: logger.debug("received VALID") self.cache.validate(transaction.request, transaction.response) if transaction.request.etag != transaction.response.etag: element = self.cache.search_response(transaction.request) transaction.response = element.cached_response return transaction """ CHANGED, CREATED or DELETED response: mark the requested resource as not fresh """ if code == Codes.CHANGED.number or code == Codes.CREATED.number or code == Codes.DELETED.number: target = self.cache.search_related(transaction.request) if target is not None: for element in target: self.cache.mark(element) return transaction """ any other response code can be cached normally """ self.cache.cache_add(transaction.request, transaction.response) return transaction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def version(self, v): """ Sets the CoAP version :param v: the version :raise AttributeError: if value is not 1 """
if not isinstance(v, int) or v != 1: raise AttributeError self._version = v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def type(self, value): """ Sets the type of the message. :type value: Types :param value: the type :raise AttributeError: if value is not a valid type """
if value not in list(defines.Types.values()): raise AttributeError self._type = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mid(self, value): """ Sets the MID of the message. :type value: Integer :param value: the MID :raise AttributeError: if value is not int or cannot be represented on 16 bits. """
if not isinstance(value, int) or value > 65536: raise AttributeError self._mid = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def token(self, value): """ Set the Token of the message. :type value: String :param value: the Token :raise AttributeError: if value is longer than 256 """
if value is None: self._token = value return if not isinstance(value, str): value = str(value) if len(value) > 256: raise AttributeError self._token = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def options(self, value): """ Set the options of the CoAP message. :type value: list :param value: list of options """
if value is None: value = [] assert isinstance(value, list) self._options = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def payload(self, value): """ Sets the payload of the message and eventually the Content-Type :param value: the payload """
if isinstance(value, tuple): content_type, payload = value self.content_type = content_type self._payload = payload else: self._payload = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destination(self, value): """ Set the destination of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port. """
if value is not None and (not isinstance(value, tuple) or len(value)) != 2: raise AttributeError self._destination = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def source(self, value): """ Set the source of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port. """
if not isinstance(value, tuple) or len(value) != 2: raise AttributeError self._source = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def code(self, value): """ Set the code of the message. :type value: Codes :param value: the code :raise AttributeError: if value is not a valid code """
if value not in list(defines.Codes.LIST.keys()) and value is not None: raise AttributeError self._code = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acknowledged(self, value): """ Marks this message as acknowledged. :type value: Boolean :param value: if acknowledged """
assert (isinstance(value, bool)) self._acknowledged = value if value: self._timeouted = False self._rejected = False self._cancelled = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rejected(self, value): """ Marks this message as rejected. :type value: Boolean :param value: if rejected """
assert (isinstance(value, bool)) self._rejected = value if value: self._timeouted = False self._acknowledged = False self._cancelled = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _already_in(self, option): """ Check if an option is already in the message. :type option: Option :param option: the option to be checked :return: True if already present, False otherwise """
for opt in self._options: if option.number == opt.number: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_option(self, option): """ Add an option to the message. :type option: Option :param option: the option :raise TypeError: if the option is not repeatable and such option is already present in the message """
assert isinstance(option, Option) repeatable = defines.OptionRegistry.LIST[option.number].repeatable if not repeatable: ret = self._already_in(option) if ret: raise TypeError("Option : %s is not repeatable", option.name) else: self._options.append(option) else: self._options.append(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_option(self, option): """ Delete an option from the message :type option: Option :param option: the option """
assert isinstance(option, Option) while option in list(self._options): self._options.remove(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_option_by_name(self, name): """ Delete an option from the message by name :type name: String :param name: option name """
for o in list(self._options): assert isinstance(o, Option) if o.name == name: self._options.remove(o)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_option_by_number(self, number): """ Delete an option from the message by number :type number: Integer :param number: option naumber """
for o in list(self._options): assert isinstance(o, Option) if o.number == number: self._options.remove(o)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def etag(self): """ Get the ETag option of the message. :rtype: list :return: the ETag values or [] if not specified by the request """
value = [] for option in self.options: if option.number == defines.OptionRegistry.ETAG.number: value.append(option.value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def etag(self, etag): """ Add an ETag option to the message. :param etag: the etag """
if not isinstance(etag, list): etag = [etag] for e in etag: option = Option() option.number = defines.OptionRegistry.ETAG.number if not isinstance(e, bytes): e = bytes(e, "utf-8") option.value = e self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content_type(self): """ Get the Content-Type option of a response. :return: the Content-Type value or 0 if not specified by the response """
value = 0 for option in self.options: if option.number == defines.OptionRegistry.CONTENT_TYPE.number: value = int(option.value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content_type(self, content_type): """ Set the Content-Type option of a response. :type content_type: int :param content_type: the Content-Type """
option = Option() option.number = defines.OptionRegistry.CONTENT_TYPE.number option.value = int(content_type) self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def observe(self): """ Check if the request is an observing request. :return: 0, if the request is an observing request """
for option in self.options: if option.number == defines.OptionRegistry.OBSERVE.number: # if option.value is None: # return 0 if option.value is None: return 0 return option.value return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def observe(self, ob): """ Add the Observe option. :param ob: observe count """
option = Option() option.number = defines.OptionRegistry.OBSERVE.number option.value = ob self.del_option_by_number(defines.OptionRegistry.OBSERVE.number) self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block1(self): """ Get the Block1 option. :return: the Block1 value """
value = None for option in self.options: if option.number == defines.OptionRegistry.BLOCK1.number: value = parse_blockwise(option.value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block1(self, value): """ Set the Block1 option. :param value: the Block1 value """
option = Option() option.number = defines.OptionRegistry.BLOCK1.number num, m, size = value if size > 512: szx = 6 elif 256 < size <= 512: szx = 5 elif 128 < size <= 256: szx = 4 elif 64 < size <= 128: szx = 3 elif 32 < size <= 64: szx = 2 elif 16 < size <= 32: szx = 1 else: szx = 0 value = (num << 4) value |= (m << 3) value |= szx option.value = value self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block2(self): """ Get the Block2 option. :return: the Block2 value """
value = None for option in self.options: if option.number == defines.OptionRegistry.BLOCK2.number: value = parse_blockwise(option.value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block2(self, value): """ Set the Block2 option. :param value: the Block2 value """
option = Option() option.number = defines.OptionRegistry.BLOCK2.number num, m, size = value if size > 512: szx = 6 elif 256 < size <= 512: szx = 5 elif 128 < size <= 256: szx = 4 elif 64 < size <= 128: szx = 3 elif 32 < size <= 64: szx = 2 elif 16 < size <= 32: szx = 1 else: szx = 0 value = (num << 4) value |= (m << 3) value |= szx option.value = value self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def line_print(self): """ Return the message as a one-line string. :return: the string representing the message """
inv_types = {v: k for k, v in defines.Types.items()} if self._code is None: self._code = defines.Codes.EMPTY.number msg = "From {source}, To {destination}, {type}-{mid}, {code}-{token}, ["\ .format(source=self._source, destination=self._destination, type=inv_types[self._type], mid=self._mid, code=defines.Codes.LIST[self._code].name, token=self._token) for opt in self._options: msg += "{name}: {value}, ".format(name=opt.name, value=opt.value) msg += "]" if self.payload is not None: if isinstance(self.payload, dict): tmp = list(self.payload.values())[0][0:20] else: tmp = self.payload[0:20] msg += " {payload}...{length} bytes".format(payload=tmp, length=len(self.payload)) else: msg += " No payload" return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pretty_print(self): """ Return the message as a formatted string. :return: the string representing the message """
msg = "Source: " + str(self._source) + "\n" msg += "Destination: " + str(self._destination) + "\n" inv_types = {v: k for k, v in defines.Types.items()} msg += "Type: " + str(inv_types[self._type]) + "\n" msg += "MID: " + str(self._mid) + "\n" if self._code is None: self._code = 0 msg += "Code: " + str(defines.Codes.LIST[self._code].name) + "\n" msg += "Token: " + str(self._token) + "\n" for opt in self._options: msg += str(opt) msg += "Payload: " + "\n" msg += str(self._payload) + "\n" return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interp_box(x, y, z, box, values): """ box is 8x3 array, though not really a box values is length-8 array, corresponding to values at the "box" coords TODO: should make power `p` an argument """
# Calculate the distance to each vertex val = 0 norm = 0 for i in range(8): # Inv distance, or Inv-dsq weighting distance = sqrt((x-box[i,0])**2 + (y-box[i,1])**2 + (z-box[i, 2])**2) # If you happen to land on exactly a corner, you're done. if distance == 0: val = values[i] norm = 1. break w = 1./distance # w = 1./((x-box[i,0])*(x-box[i,0]) + # (y-box[i,1])*(y-box[i,1]) + # (z-box[i, 2])*(z-box[i, 2])) val += w * values[i] norm += w return val/norm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_photometry(self, brightest=False, min_unc=0.02, convert=True): """Returns dictionary of photometry of closest match unless brightest is True, in which case the brightest match. """
if brightest: row = self.brightest else: row = self.closest if not hasattr(self, 'conversions'): convert = False if convert: bands = self.conversions else: bands = self.bands.keys() d = {} for b in bands: if convert: key = b mag, dmag = getattr(self, b)(brightest=brightest) else: key = self.bands[b] mag, dmag = row[b], row['e_{}'.format(b)] d[key] = mag, max(dmag, min_unc) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ichrone(models, bands=None, default=False, **kwargs): """Gets Isochrone Object by name, or type, with the right bands If `default` is `True`, then will set bands to be the union of bands and default_bands """
if isinstance(models, Isochrone): return models def actual(bands, ictype): if bands is None: return list(ictype.default_bands) elif default: return list(set(bands).union(set(ictype.default_bands))) else: return bands if type(models) is type(type): ichrone = models(actual(bands, models)) elif models=='dartmouth': from isochrones.dartmouth import Dartmouth_Isochrone ichrone = Dartmouth_Isochrone(bands=actual(bands, Dartmouth_Isochrone), **kwargs) elif models=='dartmouthfast': from isochrones.dartmouth import Dartmouth_FastIsochrone ichrone = Dartmouth_FastIsochrone(bands=actual(bands, Dartmouth_FastIsochrone), **kwargs) elif models=='mist': from isochrones.mist import MIST_Isochrone ichrone = MIST_Isochrone(bands=actual(bands, MIST_Isochrone), **kwargs) elif models=='padova': from isochrones.padova import Padova_Isochrone ichrone = Padova_Isochrone(bands=actual(bands, Padova_Isochrone), **kwargs) elif models=='basti': from isochrones.basti import Basti_Isochrone ichrone = Basti_Isochrone(bands=actual(bands, Basti_Isochrone), **kwargs) else: raise ValueError('Unknown stellar models: {}'.format(models)) return ichrone
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delta_nu(self, *args): """Returns asteroseismic delta_nu in uHz reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (2) """
return 134.88 * np.sqrt(self.mass(*args) / self.radius(*args)**3)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nu_max(self, *args): """Returns asteroseismic nu_max in uHz reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (3) """
return 3120.* (self.mass(*args) / (self.radius(*args)**2 * np.sqrt(self.Teff(*args)/5777.)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def agerange(self, m, feh=0.0): """ For a given mass and feh, returns the min and max allowed ages. """
ages = np.arange(self.minage, self.maxage, 0.01) rs = self.radius(m, ages, feh) w = np.where(np.isfinite(rs))[0] return ages[w[0]],ages[w[-1]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evtrack(self,m,feh=0.0,minage=None,maxage=None,dage=0.02, return_df=True): """ Returns evolution track for a single initial mass and feh. :param m: Initial mass of desired evolution track. :param feh: (optional) Metallicity of desired track. Default = 0.0 (solar) :param minage, maxage: (optional) Minimum and maximum log(age) of desired track. Will default to min and max age of model isochrones. :param dage: (optional) Spacing in log(age) at which to evaluate models. Default = 0.02 :param return_df: (optional) Whether to return a ``DataFrame`` or dicionary. Default is ``True``. :return: Either a :class:`pandas.DataFrame` or dictionary representing the evolution track---fixed mass, sampled at chosen range of ages. """
if minage is None: minage = self.minage if maxage is None: maxage = self.maxage ages = np.arange(minage,maxage,dage) Ms = self.mass(m,ages,feh) Rs = self.radius(m,ages,feh) logLs = self.logL(m,ages,feh) loggs = self.logg(m,ages,feh) Teffs = self.Teff(m,ages,feh) mags = {band:self.mag[band](m,ages,feh) for band in self.bands} props = {'age':ages,'mass':Ms,'radius':Rs,'logL':logLs, 'logg':loggs, 'Teff':Teffs, 'mag':mags} if not return_df: return props else: d = {} for key in props.keys(): if key=='mag': for m in props['mag'].keys(): d['{}_mag'.format(m)] = props['mag'][m] else: d[key] = props[key] try: df = pd.DataFrame(d) except ValueError: df = pd.DataFrame(d, index=[0]) return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isochrone(self,age,feh=0.0,minm=None,maxm=None,dm=0.02, return_df=True,distance=None,AV=0.0): """ Returns stellar models at constant age and feh, for a range of masses :param age: log10(age) of desired isochrone. :param feh: (optional) Metallicity of desired isochrone (default = 0.0) :param minm, maxm: (optional) Mass range of desired isochrone (will default to max and min available) :param dm: (optional) Spacing in mass of desired isochrone. Default = 0.02 Msun. :param return_df: (optional) Whether to return a :class:``pandas.DataFrame`` or dictionary. Default is ``True``. :param distance: Distance in pc. If passed, then mags will be converted to apparent mags based on distance (and ``AV``). :param AV: V-band extinction (magnitudes). :return: :class:`pandas.DataFrame` or dictionary containing results. """
if minm is None: minm = self.minmass if maxm is None: maxm = self.maxmass ms = np.arange(minm,maxm,dm) ages = np.ones(ms.shape)*age Ms = self.mass(ms,ages,feh) Rs = self.radius(ms,ages,feh) logLs = self.logL(ms,ages,feh) loggs = self.logg(ms,ages,feh) Teffs = self.Teff(ms,ages,feh) mags = {band:self.mag[band](ms,ages,feh) for band in self.bands} #for band in self.bands: # mags[band] = self.mag[band](ms,ages) if distance is not None: dm = 5*np.log10(distance) - 5 for band in mags: A = AV*EXTINCTION[band] mags[band] = mags[band] + dm + A props = {'M':Ms,'R':Rs,'logL':logLs,'logg':loggs, 'Teff':Teffs,'mag':mags} if not return_df: return props else: d = {} for key in props.keys(): if key=='mag': for m in props['mag'].keys(): d['{}_mag'.format(m)] = props['mag'][m] else: d[key] = props[key] try: df = pd.DataFrame(d) except ValueError: df = pd.DataFrame(d, index=[0]) return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_points(self,n,minmass=None,maxmass=None, minage=None,maxage=None, minfeh=None,maxfeh=None): """ Returns n random mass, age, feh points, none of which are out of range. :param n: Number of desired points. :param minmass, maxmass: (optional) Desired allowed range. Default is mass range of ``self``. :param minage, maxage: (optional) Desired allowed range. Default is log10(age) range of ``self``. :param minfehs, maxfeh: (optional) Desired allowed range. Default is feh range of ``self``. :return: :class:`np.ndarray` arrays of randomly selected mass, log10(age), and feh values within allowed ranges. Used, e.g., to initialize random walkers for :class:`StarModel` fits. .. todo:: Should change this to drawing from priors! Current implementation is a bit outdated. """
if minmass is None: minmass = self.minmass if maxmass is None: maxmass = self.maxmass if minage is None: minage = self.minage if maxage is None: maxage = self.maxage if minfeh is None: minfeh = self.minfeh if maxfeh is None: maxfeh = self.maxfeh ms = rand.uniform(minmass,maxmass,size=n) ages = rand.uniform(minage,maxage,size=n) fehs = rand.uniform(minage,maxage,size=n) Rs = self.radius(ms,ages,fehs) bad = np.isnan(Rs) nbad = bad.sum() while nbad > 0: ms[bad] = rand.uniform(minmass,maxmass,size=nbad) ages[bad] = rand.uniform(minage,maxage,size=nbad) fehs[bad] = rand.uniform(minfeh,maxfeh,size=nbad) Rs = self.radius(ms,ages,fehs) bad = np.isnan(Rs) nbad = bad.sum() return ms,ages,fehs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_band(cls, kw): """Returns photometric band from inifile keyword """
m = re.search('([a-zA-Z0-9]+)(_\d+)?', kw) if m: if m.group(1) in cls._not_a_band: return None else: return m.group(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_obs(self, **kwargs): """ Builds ObservationTree out of keyword arguments Ignores anything that is not a photometric bandpass. This should not be used if there are multiple stars observed. Creates self.obs """
logging.debug('Building ObservationTree...') tree = ObservationTree() for k,v in kwargs.items(): if k in self.ic.bands: if np.size(v) != 2: logging.warning('{}={} ignored.'.format(k,v)) # continue v = [v, np.nan] o = Observation('', k, 99) #bogus resolution=99 s = Source(v[0], v[1]) o.add_source(s) logging.debug('Adding {} ({})'.format(s,o)) tree.add_observation(o) self.obs = tree
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_properties(self, **kwargs): """ Adds non-photometry properties to ObservationTree """
for k,v in kwargs.items(): if k=='parallax': self.obs.add_parallax(v) elif k in ['Teff', 'logg', 'feh', 'density']: par = {k:v} self.obs.add_spectroscopy(**par) elif re.search('_', k): m = re.search('^(\w+)_(\w+)$', k) prop = m.group(1) tag = m.group(2) self.obs.add_spectroscopy(**{prop:v, 'label':'0_{}'.format(tag)})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mnest_basename(self): """Full path to basename """
if not hasattr(self, '_mnest_basename'): s = self.labelstring if s=='0_0': s = 'single' elif s=='0_0-0_1': s = 'binary' elif s=='0_0-0_1-0_2': s = 'triple' s = '{}-{}'.format(self.ic.name, s) self._mnest_basename = os.path.join('chains', s+'-') if os.path.isabs(self._mnest_basename): return self._mnest_basename else: return os.path.join(self.directory, self._mnest_basename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def samples(self): """Dataframe with samples drawn from isochrone according to posterior Columns include both the sampling parameters from the MCMC fit (mass, age, Fe/H, [distance, A_V]), and also evaluation of the :class:`Isochrone` at each of these sample points---this is how chains of physical/observable parameters get produced. """
if not hasattr(self,'sampler') and self._samples is None: raise AttributeError('Must run MCMC (or load from file) '+ 'before accessing samples') if self._samples is not None: df = self._samples else: self._make_samples() df = self._samples return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_samples(self, n): """ Returns a random sampling of given size from the existing samples. :param n: Number of samples :return: :class:`pandas.DataFrame` of length ``n`` with random samples. """
samples = self.samples inds = rand.randint(len(samples),size=int(n)) newsamples = samples.iloc[inds] newsamples.reset_index(inplace=True) return newsamples
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def corner_observed(self, **kwargs): """Makes corner plot for each observed node magnitude """
tot_mags = [] names = [] truths = [] rng = [] for n in self.obs.get_obs_nodes(): labels = [l.label for l in n.get_model_nodes()] band = n.band mags = [self.samples['{}_mag_{}'.format(band, l)] for l in labels] tot_mag = addmags(*mags) if n.relative: name = '{} $\Delta${}'.format(n.instrument, n.band) ref = n.reference if ref is None: continue ref_labels = [l.label for l in ref.get_model_nodes()] ref_mags = [self.samples['{}_mag_{}'.format(band, l)] for l in ref_labels] tot_ref_mag = addmags(*ref_mags) tot_mags.append(tot_mag - tot_ref_mag) truths.append(n.value[0] - ref.value[0]) else: name = '{} {}'.format(n.instrument, n.band) tot_mags.append(tot_mag) truths.append(n.value[0]) names.append(name) rng.append((min(truths[-1], np.percentile(tot_mags[-1],0.5)), max(truths[-1], np.percentile(tot_mags[-1],99.5)))) tot_mags = np.array(tot_mags).T return corner.corner(tot_mags, labels=names, truths=truths, range=rng, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_df(self): """Returns stellar model grid with desired bandpasses and with standard column names bands must be iterable, and are parsed according to :func:``get_band`` """
grids = {} df = pd.DataFrame() for bnd in self.bands: s,b = self.get_band(bnd, **self.kwargs) logging.debug('loading {} band from {}'.format(b,s)) if s not in grids: grids[s] = self.get_hdf(s) if self.common_columns[0] not in df: df[list(self.common_columns)] = grids[s][list(self.common_columns)] col = grids[s][b] n_nan = np.isnan(col).sum() if n_nan > 0: logging.debug('{} NANs in {} column'.format(n_nan, b)) df.loc[:, bnd] = col.values #dunno why it has to be this way; something # funny with indexing. return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_master_tarball(cls): """Unpack tarball of tarballs """
if not os.path.exists(cls.master_tarball_file): cls.download_grids() with tarfile.open(os.path.join(ISOCHRONES, cls.master_tarball_file)) as tar: logging.info('Extracting {}...'.format(cls.master_tarball_file)) tar.extractall(ISOCHRONES)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def df_all(self, phot): """Subclasses may want to sort this """
df = pd.concat([self.to_df(f) for f in self.get_filenames(phot)]) return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_band(cls, b, **kwargs): """Defines what a "shortcut" band name refers to. Returns phot_system, band """
phot = None # Default to SDSS for these if b in ['u','g','r','i','z']: phot = 'SDSS' band = 'SDSS_{}'.format(b) elif b in ['U','B','V','R','I']: phot = 'UBVRIplus' band = 'Bessell_{}'.format(b) elif b in ['J','H','Ks']: phot = 'UBVRIplus' band = '2MASS_{}'.format(b) elif b=='K': phot = 'UBVRIplus' band = '2MASS_Ks' elif b in ['kep','Kepler','Kp']: phot = 'UBVRIplus' band = 'Kepler_Kp' elif b=='TESS': phot = 'UBVRIplus' band = 'TESS' elif b in ['W1','W2','W3','W4']: phot = 'WISE' band = 'WISE_{}'.format(b) elif b in ('G', 'BP', 'RP'): phot = 'UBVRIplus' band = 'Gaia_{}'.format(b) if 'version' in kwargs: if kwargs['version']=='1.1': band += '_DR2Rev' else: m = re.match('([a-zA-Z]+)_([a-zA-Z_]+)',b) if m: if m.group(1) in cls.phot_systems: phot = m.group(1) if phot=='PanSTARRS': band = 'PS_{}'.format(m.group(2)) else: band = m.group(0) elif m.group(1) in ['UK','UKIRT']: phot = 'UKIDSS' band = 'UKIDSS_{}'.format(m.group(2)) if phot is None: for system, bands in cls.phot_bands.items(): if b in bands: phot = system band = b break if phot is None: raise ValueError('MIST grids cannot resolve band {}!'.format(b)) return phot, band
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_child(self, label): """ Removes node by label """
ind = None for i,c in enumerate(self.children): if c.label==label: ind = i if ind is None: logging.warning('No child labeled {}.'.format(label)) return self.children.pop(ind) self._clear_all_leaves()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_leaves(self, name): """Returns all leaves under all nodes matching name """
if self.is_leaf: return [self] if re.search(name, self.label) else [] else: leaves = [] if re.search(name, self.label): for c in self.children: leaves += c._get_leaves() #all leaves else: for c in self.children: leaves += c.select_leaves(name) #only matching ones return leaves
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_obs_leaves(self): """Returns the last obs nodes that are leaves """
obs_leaves = [] for n in self: if n.is_leaf: if isinstance(n, ModelNode): l = n.parent else: l = n if l not in obs_leaves: obs_leaves.append(l) return obs_leaves
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distance(self, other): """Coordinate distance from another ObsNode """
return distance((self.separation, self.pa), (other.separation, other.pa))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Nstars(self): """ dictionary of number of stars per system """
if self._Nstars is None: N = {} for n in self.get_model_nodes(): if n.index not in N: N[n.index] = 1 else: N[n.index] += 1 self._Nstars = N return self._Nstars
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_model(self, ic, N=1, index=0): """ Should only be able to do this to a leaf node. Either N and index both integers OR index is list of length=N """
if type(index) in [list,tuple]: if len(index) != N: raise ValueError('If a list, index must be of length N.') else: index = [index]*N for idx in index: existing = self.get_system(idx) tag = len(existing) self.add_child(ModelNode(ic, index=idx, tag=tag))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model_mag(self, pardict, use_cache=True): """ pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector """
if pardict == self._cache_key and use_cache: #print('{}: using cached'.format(self)) return self._cache_val #print('{}: calculating'.format(self)) self._cache_key = pardict # Generate appropriate parameter vector from dictionary p = [] for l in self.leaf_labels: p.extend(pardict[l]) assert len(p) == self.n_params tot = np.inf #print('Building {} mag for {}:'.format(self.band, self)) for i,m in enumerate(self.leaves): mag = m.evaluate(p[i*5:(i+1)*5], self.band) # logging.debug('{}: mag={}'.format(self,mag)) #print('{}: {}({}) = {}'.format(m,self.band,p[i*5:(i+1)*5],mag)) tot = addmags(tot, mag) self._cache_val = tot return tot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lnlike(self, pardict, use_cache=True): """ returns log-likelihood of this observation pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector """
mag, dmag = self.value if np.isnan(dmag): return 0 if self.relative: # If this *is* the reference, just return if self.reference is None: return 0 mod = (self.model_mag(pardict, use_cache=use_cache) - self.reference.model_mag(pardict, use_cache=use_cache)) mag -= self.reference.value[0] else: mod = self.model_mag(pardict, use_cache=use_cache) lnl = -0.5*(mag - mod)**2 / dmag**2 # logging.debug('{} {}: mag={}, mod={}, lnlike={}'.format(self.instrument, # self.band, # mag,mod,lnl)) return lnl
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_df(cls, df, **kwargs): """ DataFrame must have the right columns. these are: name, band, resolution, mag, e_mag, separation, pa """
tree = cls(**kwargs) for (n,b), g in df.groupby(['name','band']): #g.sort('separation', inplace=True) #ensures that the first is reference sources = [Source(**s[['mag','e_mag','separation','pa','relative']]) for _,s in g.iterrows()] obs = Observation(n, b, g.resolution.mean(), sources=sources, relative=g.relative.any()) tree.add_observation(obs) # For all relative mags, set reference to be brightest return tree
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_df(self): """ Returns DataFrame with photometry from observations organized. This DataFrame should be able to be read back in to reconstruct the observation. """
df = pd.DataFrame() name = [] band = [] resolution = [] mag = [] e_mag = [] separation = [] pa = [] relative = [] for o in self._observations: for s in o.sources: name.append(o.name) band.append(o.band) resolution.append(o.resolution) mag.append(s.mag) e_mag.append(s.e_mag) separation.append(s.separation) pa.append(s.pa) relative.append(s.relative) return pd.DataFrame({'name':name,'band':band,'resolution':resolution, 'mag':mag,'e_mag':e_mag,'separation':separation, 'pa':pa,'relative':relative})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_hdf(self, filename, path='', overwrite=False, append=False): """ Writes all info necessary to recreate object to HDF file Saves table of photometry in DataFrame Saves model specification, spectroscopy, parallax to attrs """
if os.path.exists(filename): store = pd.HDFStore(filename) if path in store: store.close() if overwrite: os.remove(filename) elif not append: raise IOError('{} in {} exists. Set either overwrite or append option.'.format(path,filename)) else: store.close() df = self.to_df() df.to_hdf(filename, path+'/df') with pd.HDFStore(filename) as store: # store = pd.HDFStore(filename) attrs = store.get_storer(path+'/df').attrs attrs.spectroscopy = self.spectroscopy attrs.parallax = self.parallax attrs.N = self._N attrs.index = self._index store.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_hdf(cls, filename, path='', ic=None): """ Loads stored ObservationTree from file. You can provide the isochrone to use; or it will default to MIST TODO: saving and loading must be fixed! save ic type, bands, etc. """
store = pd.HDFStore(filename) try: samples = store[path+'/df'] attrs = store.get_storer(path+'/df').attrs except: store.close() raise df = store[path+'/df'] new = cls.from_df(df) if ic is None: ic = get_ichrone('mist') new.define_models(ic, N=attrs.N, index=attrs.index) new.spectroscopy = attrs.spectroscopy new.parallax = attrs.parallax store.close() return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_observation(self, obs): """Adds an observation to observation list, keeping proper order """
if len(self._observations)==0: self._observations.append(obs) else: res = obs.resolution ind = 0 for o in self._observations: if res > o.resolution: break ind += 1 self._observations.insert(ind, obs) self._build_tree() self._clear_cache()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_limit(self, label='0_0', **props): """Define limits to spectroscopic property of particular stars. Usually will be used for 'logg', but 'Teff' and 'feh' will also work. In form (min, max): e.g., t.add_limit(logg=(3.0,None)) None will be converted to (-)np.inf """
if label not in self.leaf_labels: raise ValueError('No model node named {} (must be in {}). Maybe define models first?'.format(label, self.leaf_labels)) for k,v in props.items(): if k not in self.spec_props: raise ValueError('Illegal property {} (only {} allowed).'.format(k, self.spec_props)) if len(v) != 2: raise ValueError('Must provide (min, max) for {}. (`None` is allowed value)'.format(k)) if label not in self.limits: self.limits[label] = {} for k,v in props.items(): vmin, vmax = v if vmin is None: vmin = -np.inf if vmax is None: vmax = np.inf self.limits[label][k] = (vmin, vmax) self._clear_cache()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define_models(self, ic, leaves=None, N=1, index=0): """ N, index are either integers or lists of integers. N : number of model stars per observed star index : index of physical association leaves: either a list of leaves, or a pattern by which the leaves are selected (via `select_leaves`) If these are lists, then they are defined individually for each leaf. If `index` is a list, then each entry must be either an integer or a list of length `N` (where `N` is the corresponding entry in the `N` list.) This bugs up if you call it multiple times. If you want to re-do a call to this function, please re-define the tree. """
self.clear_models() if leaves is None: leaves = self._get_leaves() elif type(leaves)==type(''): leaves = self.select_leaves(leaves) # Sort leaves by distance, to ensure system 0 will be assigned # to the main reference star. if np.isscalar(N): N = (np.ones(len(leaves))*N) #if np.size(index) > 1: # index = [index] N = np.array(N).astype(int) if np.isscalar(index): index = (np.ones_like(N)*index) index = np.array(index).astype(int) # Add the appropriate number of model nodes to each # star in the highest-resoluion image for s,n,i in zip(leaves, N, index): # Remove any previous model nodes (should do some checks here?) s.remove_children() s.add_model(ic, n, i) # For each system, make sure tag _0 is the brightest. self._fix_labels() self._N = N self._index = index self._clear_all_leaves()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fix_labels(self): """For each system, make sure tag _0 is the brightest, and make sure system 0 contains the brightest star in the highest-resolution image """
for s in self.systems: mag0 = np.inf n0 = None for n in self.get_system(s): if isinstance(n.parent, DummyObsNode): continue mag, _ = n.parent.value if mag < mag0: mag0 = mag n0 = n # If brightest is not tag _0, then switch them. if n0 is not None and n0.tag != 0: n_other = self.get_leaf('{}_{}'.format(s,0)) n_other.tag = n0.tag n0.tag = 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_observations(self, name): """Returns nodes whose instrument-band matches 'name' """
return [n for n in self.get_obs_nodes() if n.obsname==name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trim(self): """ Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is """
# Only allow leaves to stay on list (highest-resolution) level return for l in self._levels[-2::-1]: for n in l: if n.is_leaf: n.parent.remove_child(n.label) self._clear_all_leaves()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def p2pardict(self, p): """ Given leaf labels, turns parameter vector into pardict """
d = {} N = self.Nstars i = 0 for s in self.systems: age, feh, dist, AV = p[i+N[s]:i+N[s]+4] for j in xrange(N[s]): l = '{}_{}'.format(s,j) mass = p[i+j] d[l] = [mass, age, feh, dist, AV] i += N[s] + 4 return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lnlike(self, p, use_cache=True): """ takes parameter vector, constructs pardict, returns sum of lnlikes of non-leaf nodes """
if use_cache and self._cache_key is not None and np.all(p==self._cache_key): return self._cache_val self._cache_key = p pardict = self.p2pardict(p) # lnlike from photometry lnl = 0 for n in self: if n is not self: lnl += n.lnlike(pardict, use_cache=use_cache) if not np.isfinite(lnl): self._cache_val = -np.inf return -np.inf # lnlike from spectroscopy for l in self.spectroscopy: for prop,(val,err) in self.spectroscopy[l].items(): mod = self.get_leaf(l).evaluate(pardict[l], prop) lnl += -0.5*(val - mod)**2/err**2 if not np.isfinite(lnl): self._cache_val = -np.inf return -np.inf # enforce limits for l in self.limits: for prop,(vmin,vmax) in self.limits[l].items(): mod = self.get_leaf(l).evaluate(pardict[l], prop) if mod < vmin or mod > vmax or not np.isfinite(mod): self._cache_val = -np.inf return -np.inf # lnlike from parallax for s,(val,err) in self.parallax.items(): dist = pardict['{}_0'.format(s)][3] mod = 1./dist * 1000. lnl += -0.5*(val-mod)**2/err**2 if not np.isfinite(lnl): self._cache_val = -np.inf return -np.inf self._cache_val = lnl return lnl
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_closest(self, n0): """returns the node in the tree that is closest to n0, but not in the same observation """
dmin = np.inf nclose = None ds = [] nodes = [] ds.append(np.inf) nodes.append(self) for n in self: if n is n0: continue try: if n._in_same_observation(n0): continue ds.append(n.distance(n0)) nodes.append(n) except AttributeError: pass inds = np.argsort(ds) ds = [ds[i] for i in inds] nodes = [nodes[i] for i in inds] for d,n in zip(ds, nodes): try: if d < n.resolution or n.resolution==-1: return n except AttributeError: pass # If nothing else works return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def q_prior(q, m=1, gamma=0.3, qmin=0.1): """Default prior on mass ratio q ~ q^gamma """
if q < qmin or q > 1: return 0 C = 1/(1/(gamma+1)*(1 - qmin**(gamma+1))) return C*q**gamma
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean_props(self): """ Makes sure all properties are legit for isochrone. Not done in __init__ in order to save speed on loading. """
remove = [] for p in self.properties.keys(): if not hasattr(self.ic, p) and \ p not in self.ic.bands and p not in ['parallax','feh','age','mass_B','mass_C'] and \ not re.search('delta_',p): remove.append(p) for p in remove: del self.properties[p] if len(remove) > 0: logging.warning('Properties removed from Model because ' + 'not present in {}: {}'.format(type(self.ic),remove)) remove = [] for p in self.properties.keys(): try: val = self.properties[p][0] if not np.isfinite(val): remove.append(p) except: pass for p in remove: del self.properties[p] if len(remove) > 0: logging.warning('Properties removed from Model because ' + 'value is nan or inf: {}'.format(remove)) self._props_cleaned = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_props(self,**kwargs): """ Adds observable properties to ``self.properties``. """
for kw,val in kwargs.iteritems(): self.properties[kw] = val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_props(self,*args): """ Removes desired properties from ``self.properties``. """
for arg in args: if arg in self.properties: del self.properties[arg]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit_for_distance(self): """ ``True`` if any of the properties are apparent magnitudes. """
for prop in self.properties.keys(): if prop in self.ic.bands: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lnlike(self, p): """Log-likelihood of model at given parameters :param p: mass, log10(age), feh, [distance, A_V (extinction)]. Final two should only be provided if ``self.fit_for_distance`` is ``True``; that is, apparent magnitudes are provided. :return: log-likelihood. Will be -np.inf if values out of range. """
if not self._props_cleaned: self._clean_props() if not self.use_emcee: fit_for_distance = True mass, age, feh, dist, AV = (p[0], p[1], p[2], p[3], p[4]) else: if len(p)==5: fit_for_distance = True mass,age,feh,dist,AV = p elif len(p)==3: fit_for_distance = False mass,age,feh = p if mass < self.ic.minmass or mass > self.ic.maxmass \ or age < self.ic.minage or age > self.ic.maxage \ or feh < self.ic.minfeh or feh > self.ic.maxfeh: return -np.inf if fit_for_distance: if dist < 0 or AV < 0 or dist > self.max_distance: return -np.inf if AV > self.maxAV: return -np.inf if self.min_logg is not None: logg = self.ic.logg(mass,age,feh) if logg < self.min_logg: return -np.inf logl = 0 for prop in self.properties.keys(): try: val,err = self.properties[prop] except TypeError: #property not appropriate for fitting (e.g. no error provided) continue if prop in self.ic.bands: if not fit_for_distance: raise ValueError('must fit for mass, age, feh, dist, A_V if apparent magnitudes provided.') mod = self.ic.mag[prop](mass,age,feh) + 5*np.log10(dist) - 5 A = AV*EXTINCTION[prop] mod += A elif re.search('delta_',prop): continue elif prop=='feh': mod = feh elif prop=='parallax': mod = 1./dist * 1000 else: mod = getattr(self.ic,prop)(mass,age,feh) logl += -(val-mod)**2/(2*err**2) + np.log(1/(err*np.sqrt(2*np.pi))) if np.isnan(logl): logl = -np.inf return logl
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lnprior(self, mass, age, feh, distance=None, AV=None, use_local_fehprior=True): """ log-prior for model parameters """
mass_prior = salpeter_prior(mass) if mass_prior==0: mass_lnprior = -np.inf else: mass_lnprior = np.log(mass_prior) if np.isnan(mass_lnprior): logging.warning('mass prior is nan at {}'.format(mass)) age_lnprior = np.log(age * (2/(self.ic.maxage**2-self.ic.minage**2))) if np.isnan(age_lnprior): logging.warning('age prior is nan at {}'.format(age)) if use_local_fehprior: fehdist = local_fehdist(feh) else: fehdist = 1/(self.ic.maxfeh - self.ic.minfeh) feh_lnprior = np.log(fehdist) if np.isnan(feh_lnprior): logging.warning('feh prior is nan at {}'.format(feh)) if distance is not None: if distance <= 0: distance_lnprior = -np.inf else: distance_lnprior = np.log(3/self.max_distance**3 * distance**2) else: distance_lnprior = 0 if np.isnan(distance_lnprior): logging.warning('distance prior is nan at {}'.format(distance)) if AV is not None: AV_lnprior = np.log(1/self.maxAV) else: AV_lnprior = 0 if np.isnan(AV_lnprior): logging.warning('AV prior is nan at {}'.format(AV)) lnprior = (mass_lnprior + age_lnprior + feh_lnprior + distance_lnprior + AV_lnprior) return lnprior
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triangle_plots(self, basename=None, format='png', **kwargs): """Returns two triangle plots, one with physical params, one observational :param basename: If basename is provided, then plots will be saved as "[basename]_physical.[format]" and "[basename]_observed.[format]" :param format: Format in which to save figures (e.g., 'png' or 'pdf') :param **kwargs: Additional keyword arguments passed to :func:`StarModel.triangle` and :func:`StarModel.prop_triangle` :return: * Physical parameters triangle plot (mass, radius, Teff, feh, age, distance) * Observed properties triangle plot. """
if self.fit_for_distance: fig1 = self.triangle(plot_datapoints=False, params=['mass','radius','Teff','logg','feh','age', 'distance','AV'], **kwargs) else: fig1 = self.triangle(plot_datapoints=False, params=['mass','radius','Teff','feh','age'], **kwargs) if basename is not None: plt.savefig('{}_physical.{}'.format(basename,format)) plt.close() fig2 = self.prop_triangle(**kwargs) if basename is not None: plt.savefig('{}_observed.{}'.format(basename,format)) plt.close() return fig1, fig2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prop_triangle(self, **kwargs): """ Makes corner plot of only observable properties. The idea here is to compare the predictions of the samples with the actual observed data---this can be a quick way to check if there are outlier properties that aren't predicted well by the model. :param **kwargs: Keyword arguments passed to :func:`StarModel.triangle`. :return: Figure object containing corner plot. """
truths = [] params = [] for p in self.properties: try: val, err = self.properties[p] except: continue if p in self.ic.bands: params.append('{}_mag'.format(p)) truths.append(val) elif p=='parallax': params.append('distance') truths.append(1/(val/1000.)) else: params.append(p) truths.append(val) return self.triangle(params, truths=truths, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prop_samples(self,prop,return_values=True,conf=0.683): """Returns samples of given property, based on MCMC sampling :param prop: Name of desired property. Must be column of ``self.samples``. :param return_values: (optional) If ``True`` (default), then also return (median, lo_err, hi_err) corresponding to desired credible interval. :param conf: (optional) Desired quantile for credible interval. Default = 0.683. :return: :class:`np.ndarray` of desired samples :return: Optionally also return summary statistics (median, lo_err, hi_err), if ``returns_values == True`` (this is default behavior) """
samples = self.samples[prop].values if return_values: sorted = np.sort(samples) med = np.median(samples) n = len(samples) lo_ind = int(n*(0.5 - conf/2)) hi_ind = int(n*(0.5 + conf/2)) lo = med - sorted[lo_ind] hi = sorted[hi_ind] - med return samples, (med,lo,hi) else: return samples