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 ...
<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 ...
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 r...
<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...
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) ...
<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 requ...
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 ...
<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_da...
<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_w...
<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...
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.retra...
<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:...
<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.re...
<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 ...
<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 represe...
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...
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 al...
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 ...
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: ...
<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(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 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 ...
<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 ...
<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...
<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: ...
<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: s...
# 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: ...
<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 ca...
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 ba...
<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 s...
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 t...
<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 m...
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) ...
<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...
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 = s...
<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 ...
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 ma...
<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 ...
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...
<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+...
<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) ...
<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, ag...
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() ...
<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...
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(*ma...
<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...
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: ...
<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']: ...
<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....
<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...
<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...
<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 bac...
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.refer...
<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 = Obs...
<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 observati...
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(...
<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 D...
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...
<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:...
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...
<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(i...
<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' ...
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...
<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 ...
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)...
<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 ...
<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 ...
<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...
<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....
<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: de...
<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 provi...
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...
<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.maxa...
<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 b...
if self.fit_for_distance: fig1 = self.triangle(plot_datapoints=False, params=['mass','radius','Teff','logg','feh','age', 'distance','AV'], **kwargs) else: fig1 = self.trian...
<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 actua...
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...
<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. Mu...
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] ...