output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def validate_integrity(self): """ Validate the integrity of the DataFrame. This checks that the indexes, column names and internal data are not corrupted. Will raise an error if there is a problem. :return: nothing """ self._validate_columns(self._columns) self._...
Write a Python 3 script to validate the integrity of the DataFrame.
As a Python code translator, you convert algorithms and pseudocode into Python.
Append another DataFrame to this DataFrame.
Make a summary of the following Python 3 code def append(self, data_frame): if len(data_frame) == 0: # empty DataFrame, do nothing return data_frame_index = data_frame.index combined_index = self._index + data_frame_index if len(set(combined_index)) != len(combined_index): ...
You are a Python code analyst, evaluating scripts for potential improvements.
This method adds element - wise two columns.
Can you generate the documentation for the following Python 3 function def add(self, left_column, right_column, indexes=None): left_list, right_list = self._get_lists(left_column, right_column, indexes) return [l + r for l, r in zip(left_list, right_list)]
As a Python code analyst, you investigate and solve complex coding mysteries
def isin(self, column, compare_list): """ Returns a boolean list where each elements is whether that element in the column is in the compare_list. :param column: single column name, does not work for multiple columns :param compare_list: list of items to compare to :return: list...
How would you implement a function in Python 3 that returns a boolean list where each element in the column is in the compare_list.
As a python code expert, you are capable of creating scripts from specifications.
def iterrows(self, index=True): """ Iterates over DataFrame rows as dictionary of the values. The index will be included. :param index: if True include the index in the results :return: dictionary """ for i in range(len(self._index)): row = {self._index_name:...
Implement a function in Python 3 to iterate over DataFrame rows as dictionary of the values.
As a Python code composer, you craft elegant and concise scripts.
def itertuples(self, index=True, name='Raccoon'): """ Iterates over DataFrame rows as tuple of the values. :param index: if True then include the index :param name: name of the namedtuple :return: namedtuple """ fields = [self._index_name] if index else list() ...
Can you implement a function in Python 3 that iterates over DataFrame rows as tuple of the values.
As a python code expert, you are capable of creating scripts from specifications.
Resets the index of the DataFrame to simple integer list and the index name to index.
How would you explain what the following Python 3 function does def reset_index(self, drop=False): if not drop: if isinstance(self.index_name, tuple): index_data = list(map(list, zip(*self._index))) for i in range(len(self.index_name)): self.set_co...
You are a Python code architect, reviewing and designing scalable and efficient code
Creates and returns a DataFrame from a JSON string.
Explain what the following Python 3 code does def from_json(cls, json_string): input_dict = json.loads(json_string) # convert index to tuple if required if input_dict['index'] and isinstance(input_dict['index'][0], list): input_dict['index'] = [tuple(x) for x in input_dict['index']] ...
As a Python code composer, you craft elegant and concise scripts.
Filter input task to pipelines and return a tuple containing the task and the list of latest retrieved results from the pipelines.
Can you generate the documentation for the following Python 3 function def doTask(self, task): # If we're not caching, then clear the table of last results. if not self._cache_results: self._last_results = dict() # Iterate the list of pipelines, draining each one of any results. ...
You are a Python code architect, reviewing and designing scalable and efficient code
This function is used to assert that two DataFrames are equal.
How would you explain what the following Python 3 function does def assert_frame_equal(left, right, data_function=None, data_args=None): if data_function: data_args = {} if not data_args else data_args data_function(left.data, right.data, **data_args) else: assert left.data == right.data...
You are a Python code architect, reviewing and designing scalable and efficient code
This function is used to assert that two Series objects are equal.
How would you explain what the following Python 3 function does def assert_series_equal(left, right, data_function=None, data_args=None): assert type(left) == type(right) if data_function: data_args = {} if not data_args else data_args data_function(left.data, right.data, **data_args) else: ...
As a Python code composer, you craft elegant and concise scripts.
def get(self, timeout=None): """Return result from the pipeline.""" result = None for stage in self._output_stages: result = stage.get(timeout) return result
Implement a function in Python 3 to get the result from the pipeline.
As a Python code translator, you convert algorithms and pseudocode into Python.
def load(self): """Load the lyrics from MetroLyrics.""" page = requests.get(self._url) # Forces utf-8 to prevent character mangling page.encoding = 'utf-8' tree = html.fromstring(page.text) lyric_div = tree.get_element_by_id('lyrics-body-text') verses = [c.text_c...
Can you implement a function in Python 3 that loads the lyrics from MetroLyrics.
You are a Python code analyst, evaluating scripts for potential improvements.
def load(self, verbose=False): """ Load the list of songs. Note that this only loads a list of songs that this artist was the main artist of. If they were only featured in the song, that song won't be listed here. There is a list on the artist page for that, I just hav...
Can you implement a function in Python 3 that loads the list of songs.
As a Python code translator, you convert algorithms and pseudocode into Python.
def distance(p0, p1, deg=True, r=r_earth_mean): """ Return the distance between two points on the surface of the Earth. Parameters ---------- p0 : point-like (or array of point-like) [longitude, latitude] objects p1 : point-like (or array of point-like) [longitude, latitude] objects deg : b...
How would you code a function in Python 3 to return the distance between two points on the surface of the Earth.
You are a Python code analyst, evaluating scripts for potential improvements.
def course(p0, p1, deg=True, bearing=False): """ Compute the initial bearing along the great circle from p0 to p1 NB: The angle returned by course() is not the traditional definition of bearing. It is definted such that 0 degrees to due East increasing counter-clockwise such that 90 degrees is due ...
Write a Python 3 script for computing the initial bearing along the great circle from p0 to p1.
As a Python code translator, you convert algorithms and pseudocode into Python.
Given an initial point and angle move distance d along the surface Returns a new object that is a copy of the base classical hierarchy.
Here you have a function in Python 3, explain what it does def propagate(p0, angle, d, deg=True, bearing=False, r=r_earth_mean): single, (p0, angle, d) = _to_arrays((p0, 2), (angle, 1), (d, 1)) if deg: p0 = np.radians(p0) angle = np.radians(angle) if not bearing: angle = np.pi / 2.0...
You are a Python code analyst, evaluating scripts for potential improvements.
def validate(self, signature, timestamp, nonce): """Validate request signature. :param signature: A string signature parameter sent by weixin. :param timestamp: A int timestamp parameter sent by weixin. :param nonce: A int nonce parameter sent by weixin. """ if not self....
Write a Python 3 script for validating the signature sent by weixin.
As a Python code analyst, you investigate and solve complex coding mysteries
def parse(self, content): """Parse xml body sent by weixin. :param content: A text of xml body. """ raw = {} try: root = etree.fromstring(content) except SyntaxError as e: raise ValueError(*e.args) for child in root: raw[chil...
Create a Python 3 function to parse the xml body sent by weixin.
You are a Python code generator, capable of creating scripts from specifications.
Create the reply text for the user.
Can you generate the documentation for the following Python 3 function def reply(self, username, type='text', sender=None, **kwargs): sender = sender or self.sender if not sender: raise RuntimeError('WEIXIN_SENDER or sender argument is missing') if type == 'text': conten...
As a Python code analyst, you investigate and solve complex coding mysteries
Register a command helper function.
Here you have a function in Python 3, explain what it does def register(self, key=None, func=None, **kwargs): if func: if key is None: limitation = frozenset(kwargs.items()) self._registry_without_key.append((func, limitation)) else: self._...
You are a Python code generator, capable of creating scripts from specifications.
Default view function for Flask app.
Can you generate a brief explanation for the following Python 3 code def view_func(self): if request is None: raise RuntimeError('view_func need Flask be installed') signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get(...
As a Python code analyst, you investigate and solve complex coding mysteries
def run_getgist(filename, user, **kwargs): """Passes user inputs to GetGist() and calls get()""" assume_yes = kwargs.get("yes_to_all") getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes) getgist.get()
Can you create a Python 3 function that passes user inputs to GetGist and calls get
As a Python code analyst, you investigate and solve complex coding mysteries
def run_putgist(filename, user, **kwargs): """Passes user inputs to GetGist() and calls put()""" assume_yes = kwargs.get("yes_to_all") private = kwargs.get("private") getgist = GetGist( user=user, filename=filename, assume_yes=assume_yes, create_private=private, a...
Can you write a function in Python 3 where it passes user inputs to GetGist and calls put
As a Python code analyst, you investigate and solve complex coding mysteries
Reads the remote file from Gist and saves it locally
Explain what the following Python 3 code does def get(self): if self.gist: content = self.github.read_gist_file(self.gist) self.local.save(content)
You are a Python code architect, reviewing and designing scalable and efficient code
Reads local file and updates the remote gist or creates a new one.
Can you tell what is the following Python 3 function doing def put(self): content = self.local.read() if self.gist: self.github.update(self.gist, content) else: self.github.create(content, public=self.public)
As a Python code translator, you convert algorithms and pseudocode into Python.
Decorator to restrict some GitHubTools methods to run only with OAuth
Here you have a function in Python 3, explain what it does def oauth_only(function): def check_for_oauth(self, *args, **kwargs): """ Returns False if GitHubTools instance is not authenticated, or return the decorated fucntion if it is. """ if not self.is_authenticated: ...
As a Python code composer, you craft elegant and concise scripts.
Validate token and add the proper header for further requests.
How would you explain what the following Python 3 function does def add_oauth_header(self): # abort if no token oauth_token = self._get_token() if not oauth_token: return # add oauth header & reach the api self.headers["Authorization"] = "token " + oauth_token ...
As a Python code analyst, you investigate and solve complex coding mysteries
Get all gists for the current user.
Given the following Python 3 function, write the documentation def get_gists(self): # fetch all gists if self.is_authenticated: url = self._api_url("gists") else: url = self._api_url("users", self.user, "gists") self.output("Fetching " + url) raw_resp = se...
As a Python code analyst, you investigate and solve complex coding mysteries
This method selects the proper gist for the given filename. If more than one gist is found it returns the proper gist ; if no gist is found it returns False
Can you tell what is the following Python 3 function doing def select_gist(self, allow_none=False): # pick up all macthing gists matches = list() for gist in self.get_gists(): for gist_file in gist.get("files"): if self.filename == gist_file.get("filename"): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def read_gist_file(self, gist): """ Returns the contents of file hosted inside a gist at GitHub. :param gist: (dict) gist parsed by GitHubTools._parse() :return: (bytes) content of a gist loaded from GitHub """ url = False files = gist.get("files") for gis...
Create a Python 3 function for reading a gist file from GitHub
You are a Python code generator, capable of creating scripts from specifications.
Updates the contents of a gist at GitHub.
Explain what the following Python 3 code does def update(self, gist, content): # abort if content is False if content is False: return False # request url = self._api_url("gists", gist.get("id")) data = {"files": {self.filename: {"content": content}}} self.ou...
As a Python code composer, you craft elegant and concise scripts.
Create a new gist.
Here you have a function in Python 3, explain what it does def create(self, content, **kwargs): # abort if content is False if content is False: return False # set new gist public = bool(kwargs.get("public", True)) data = { "description": self.filename, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _ask_which_gist(self, matches): """ Asks user which gist to use in case of more than one gist matching the instance filename. :param matches: (list) of dictioaries generated within select_gists() :return: (dict) of the selected gist """ # ask user which gist t...
How would you implement a function in Python 3 that asks user which gist to use in case of more than one gist matching the instance filename.
You are a Python code analyst, evaluating scripts for potential improvements.
def _parse_gist(gist): """Receive a gist (dict) and parse it to GetGist""" # parse files files = list() file_names = sorted(filename for filename in gist["files"].keys()) for name in file_names: files.append( dict(filename=name, raw_url=gist["files"][...
Write a Python 3 function that can receive a gist dict and parse it to GetGist
As a Python code analyst, you investigate and solve complex coding mysteries
Sets the indent for standardized output
Here you have a function in Python 3, explain what it does def indent(self, message): indent = self.indent_char * self.indent_size return indent + message
As a Python code composer, you craft elegant and concise scripts.
Encapsulte requests. get to use this class instance header
Can you generate a brief explanation for the following Python 3 code def get(self, url, params=None, **kwargs): return requests.get(url, params=params, headers=self.add_headers(**kwargs))
As a Python code composer, you craft elegant and concise scripts.
Encapsulte requests. patch to use this class instance header
Can you tell what is the following Python 3 function doing def patch(self, url, data=None, **kwargs): return requests.patch(url, data=data, headers=self.add_headers(**kwargs))
You are a Python code generator, capable of creating scripts from specifications.
Encapsulte requests. post to use this class instance header
Make a summary of the following Python 3 code def post(self, url, data=None, **kwargs): return requests.post(url, data=data, headers=self.add_headers(**kwargs))
As a Python code composer, you craft elegant and concise scripts.
Save any given content to the instance file.
Given the following Python 3 function, write the documentation def save(self, content): # backup existing file if needed if os.path.exists(self.file_path) and not self.assume_yes: message = "Overwrite existing {}? (y/n) " if not confirm(message.format(self.filename)): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Backups files with the same name of the instance filename
Can you generate a brief explanation for the following Python 3 code def backup(self): count = 0 name = "{}.bkp".format(self.filename) backup = os.path.join(self.cwd, name) while os.path.exists(backup): count += 1 name = "{}.bkp{}".format(self.filename, count) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def read(self, file_path=None): """ Read the contents of a file. :param filename: (str) path to a file in the local file system :return: (str) contents of the file, or (False) if not found/not file """ if not file_path: file_path = self.file_path # ab...
Implement a function in Python 3 to read the contents of a file in the local file system.
As a python code expert, you are capable of creating scripts from specifications.
Returns a function that returns a list of tokens that match the input string.
Here you have a function in Python 3, explain what it does def str_matcher(mode): def f_raw(inp_str, pos): return unique_literal_cache_pool[mode] if inp_str.startswith(mode, pos) else None def f_collection(inp_str, pos): for each in mode: if inp_str.startswith(each, pos): ...
As a python code expert, you are capable of creating scripts from specifications.
generate token names cache generate token names
Explain what the following Python 3 code does def regex_matcher(regex_pat): if isinstance(regex_pat, str): regex_pat = re.compile(regex_pat) def f(inp_str, pos): m = regex_pat.match(inp_str, pos) return m.group() if m else None return f
As a Python code analyst, you investigate and solve complex coding mysteries
Add the ast for the given list of statements.
Can you tell what is the following Python 3 function doing def ast_for_stmts(self, stmts: T) -> None: if not stmts: raise ValueError('no ast found!') head, *equals = stmts if head.name is NameEnum.TokenDef: self.ast_for_token_def(head) elif head.name is Na...
As a python code expert, you are capable of creating scripts from specifications.
Perform a method on a resource.
Make a summary of the following Python 3 code def _request(self, method, resource_uri, **kwargs): data = kwargs.get('data') response = method(self.API_BASE_URL + resource_uri, json=data, headers=self.headers) response.raise_for_status() return response.json()
As a Python code translator, you convert algorithms and pseudocode into Python.
def get(self, endpoint, **kwargs): """Get a resource. Args: endpoint: resource endpoint. """ return self._request(requests.get, endpoint, **kwargs)
Write a Python 3 script for getting a resource s nacms.
As a Python code translator, you convert algorithms and pseudocode into Python.
def post(self, endpoint, **kwargs): """Create a resource. Args: endpoint: resource endpoint. """ return self._request(requests.post, endpoint, **kwargs)
How would you code a function in Python 3 to create a resource. Args: endpoint: resource endpoint.
You are a Python code analyst, evaluating scripts for potential improvements.
Update a resource s nacms.
Make a summary of the following Python 3 code def put(self, endpoint, **kwargs): return self._request(requests.put, endpoint, **kwargs)
You are a Python code analyst, evaluating scripts for potential improvements.
def render(txt): """ Accepts Slack formatted text and returns HTML. """ # Removing links to other channels txt = re.sub(r'<#[^\|]*\|(.*)>', r'#\g<1>', txt) # Removing links to other users txt = re.sub(r'<(@.*)>', r'\g<1>', txt) # handle named hyperlinks txt = re.sub(r'<([^\|]*)\|(...
Implement a function in Python 3 to take Slack formatted text and returns HTML.
You are a Python code architect, reviewing and designing scalable and efficient code
Add an open list tag corresponding to the specification in the LIST_TYPES.
Make a summary of the following Python 3 code def _open_list(self, list_type): if list_type in LIST_TYPES.keys(): tag = LIST_TYPES[list_type] else: raise Exception('CustomSlackdownHTMLParser:_open_list: Not a valid list type.') html = '<{t} class="list-container-{c}">'.f...
As a Python code analyst, you investigate and solve complex coding mysteries
def _close_list(self): """ Add an close list tag corresponding to the currently open list found in current_parent_element. """ list_type = self.current_parent_element['attrs']['class'] tag = LIST_TYPES[list_type] html = '</{t}>'.format( t=tag ...
Implement a function in Python 3 to add an close list tag corresponding to the currently open list found in current_parent_element.
You are a Python code architect, reviewing and designing scalable and efficient code
def handle_starttag(self, tag, attrs): """ Called by HTMLParser.feed when a start tag is found. """ # Parse the tag attributes attrs_dict = dict(t for t in attrs) # If the tag is a predefined parent element if tag in PARENT_ELEMENTS: # If parser is pa...
Create a Python 3 function for handling the start tag of the element.
As a Python code analyst, you investigate and solve complex coding mysteries
def handle_endtag(self, tag): """ Called by HTMLParser.feed when an end tag is found. """ if tag in PARENT_ELEMENTS: self.current_parent_element['tag'] = '' self.current_parent_element['attrs'] = '' if tag == 'li': self.parsing_li = True ...
How would you code a function in Python 3 to call by HTMLParser. feed when an end tag is found.
As a Python code composer, you craft elegant and concise scripts.
Called by HTMLParser. feed when text is found.
Given the following Python 3 function, write the documentation def handle_data(self, data): if self.current_parent_element['tag'] == '': self.cleaned_html += '<p>' self.current_parent_element['tag'] = 'p' self.cleaned_html += data
You are a Python code generator, capable of creating scripts from specifications.
def _remove_pre_formatting(self): """ Removes formatting tags added to pre elements. """ preformatted_wrappers = [ 'pre', 'code' ] for wrapper in preformatted_wrappers: for formatter in FORMATTERS: tag = FORMATTERS[form...
Can you write a function in Python 3 where it removes formatting tags added to pre elements.
As a python code expert, you are capable of creating scripts from specifications.
Cleans up any problematic HTML.
How would you explain what the following Python 3 function does def clean(self): # Calls handle_starttag, handle_endtag, and handle_data self.feed() # Clean up any parent tags left open if self.current_parent_element['tag'] != '': self.cleaned_html += '</{}>'.format(self.cur...
As a Python code composer, you craft elegant and concise scripts.
Unstrict template block for rendering authors: <div class="author"> <img class="author-avatar" src="{author_avatar}"> <p class="author-name"> <a href="{author_link}">{author_name}</a> </p> <p class="user-handle">{author_handle}</p> </div>
Make a summary of the following Python 3 code def render_author(**kwargs): html = '<div class="user">' author_avatar = kwargs.get('author_avatar', None) if author_avatar: html += '<img class="user-avatar" src="{}">'.format(author_avatar) author_name = kwargs.get('author_name', None) if aut...
You are a Python code analyst, evaluating scripts for potential improvements.
Render the metadata page.
Here you have a function in Python 3, explain what it does def render_metadata(**kwargs): html = '<div class="metadata">' service_logo = kwargs.get('service_logo', None) if service_logo: html += '<img class="metadata-logo" src="{}">'.format(service_logo) service_name = kwargs.get('service_name...
You are a Python code analyst, evaluating scripts for potential improvements.
Render an image in a non - strict template block.
Explain what the following Python 3 code does def render_image(**kwargs): html = '' url = kwargs.get('url', None) if url: html = '<img' alt_text = kwargs.get('alt_text', None) if alt_text: html += ' alt="{}"'.format(alt_text) title = kwargs.get('title', None) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def render_twitter(text, **kwargs): """ Strict template block for rendering twitter embeds. """ author = render_author(**kwargs['author']) metadata = render_metadata(**kwargs['metadata']) image = render_image(**kwargs['image']) html = """ <div class="attachment attachment-twitter"> ...
Implement a Python 3 function for rendering a twitter embed.
As a python code expert, you are capable of creating scripts from specifications.
def get_model(LAB_DIR): """ Cannon model params """ coeffs = np.load("%s/coeffs.npz" %LAB_DIR)['arr_0'] scatters = np.load("%s/scatters.npz" %LAB_DIR)['arr_0'] chisqs = np.load("%s/chisqs.npz" %LAB_DIR)['arr_0'] pivots = np.load("%s/pivots.npz" %LAB_DIR)['arr_0'] return coeffs, scatters, chisqs,...
How would you code a function in Python 3 to get the model params from the given LAB directory.
As a Python code composer, you craft elegant and concise scripts.
Get labels for a list of ids
Can you generate a brief explanation for the following Python 3 code def get_labels(ids_find): a = pyfits.open("%s/lamost_catalog_full.fits" %LAB_DIR) data = a[1].data a.close() id_all = data['lamost_id'] id_all = np.array(id_all) id_all = np.array([val.strip() for val in id_all]) snr_all = ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_normed_spectra(): """ Spectra to compare with models """ wl = np.load("%s/wl.npz" %LAB_DIR)['arr_0'] filenames = np.array( [SPEC_DIR + "/Spectra" + "/" + val for val in lamost_id]) grid, fluxes, ivars, npix, SNRs = lamost.load_spectra( lamost_id, input_grid=wl) ds = d...
Create a Python 3 function for getting the normalized spectra for the lamost model
You are a Python code architect, reviewing and designing scalable and efficient code
Pull the files from the LAMOST archive
How would you explain what the following Python 3 function does def wget_files(): for f in lamost_id: short = (f.split('-')[2]).split('_')[0] filename = "%s/%s.gz" %(short,f) DIR = "/Users/annaho/Data/Li_Giants/Spectra_APOKASC" searchfor = "%s/%s.gz" %(DIR,f) if glob.glob(sea...
You are a Python code architect, reviewing and designing scalable and efficient code
Get the labels of the Cannon model spectra
Explain what the following Python 3 code does def get_labels(): cannon_teff = data['cannon_teff_2'] cannon_logg = data['cannon_logg_2'] cannon_m_h = data['cannon_m_h'] cannon_alpha_m = data['cannon_alpha_m'] cannon_a_k = data['cannon_a_k'] labels = np.vstack( (cannon_teff, cannon_log...
You are a Python code generator, capable of creating scripts from specifications.
Normalize according to The Cannon
Can you generate a brief explanation for the following Python 3 code def cannon_normalize(spec_raw): spec = np.array([spec_raw]) wl = np.arange(0, spec.shape[1]) w = continuum_normalization.gaussian_weight_matrix(wl, L=50) ivar = np.ones(spec.shape)*0.5 cont = continuum_normalization._find_cont_gaus...
You are a Python code generator, capable of creating scripts from specifications.
Resample spectrum onto desired grid
Can you generate a brief explanation for the following Python 3 code def resample(grid, wl, flux): flux_rs = (interpolate.interp1d(wl, flux))(grid) return flux_rs
As a Python code translator, you convert algorithms and pseudocode into Python.
def gen_cannon_grad_spec(choose, coeffs, pivots): """ Generate Cannon gradient spectra Parameters ---------- labels: default values for [teff, logg, feh, cfe, nfe, afe, ak] choose: val of cfe or nfe, whatever you're varying low: lowest val of cfe or nfe, whatever you're varying high: highes...
Write a Python 3 script for generating the gradient spectra for a Cannon object.
As a Python code composer, you craft elegant and concise scripts.
def get_model_spec_ting(atomic_number): """ X_u_template[0:2] are teff, logg, vturb in km/s X_u_template[:,3] -> onward, put atomic number atomic_number is 6 for C, 7 for N """ DATA_DIR = "/Users/annaho/Data/LAMOST/Mass_And_Age" temp = np.load("%s/X_u_template_KGh_res=1800.npz" %DATA_DIR) ...
How would you code a function in Python 3 to get model specting from the given atomic number
You are a Python code generator, capable of creating scripts from specifications.
def get_residuals(ds, m): """ Using the dataset and model object, calculate the residuals and return Parameters ---------- ds: dataset object m: model object Return ------ residuals: array of residuals, spec minus model spec """ model_spectra = get_model_spectra(ds, m) resid...
Create a Python 3 function for calculating the residuals of the dataset and model object using the dataset and model object ds and model object m.
You are a Python code analyst, evaluating scripts for potential improvements.
def load_model(): """ Load the model Parameters ---------- direc: directory with all of the model files Returns ------- m: model object """ direc = "/home/annaho/TheCannon/code/lamost/mass_age/cn" m = model.CannonModel(2) m.coeffs = np.load(direc + "/coeffs.npz")['arr_...
Can you implement a function in Python 3 that loads the model object for the
As a Python code translator, you convert algorithms and pseudocode into Python.
def load_dataset(date): """ Load the dataset for a single date Parameters ---------- date: the date (string) for which to load the data & dataset Returns ------- ds: the dataset object """ LAB_DIR = "/home/annaho/TheCannon/data/lamost" WL_DIR = "/home/annaho/TheCannon/code...
How would you implement a function in Python 3 that loads the dataset for a single date
As a Python code composer, you craft elegant and concise scripts.
def fit_gaussian(x, y, yerr, p0): """ Fit a Gaussian to the data """ try: popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True) except RuntimeError: return [0],[0] return popt, pcov
Write a Python 3 function that can fit a Gaussian to the data
As a python code expert, you are capable of creating scripts from specifications.
selects an object based on the given error and amplitudes
Can you generate a brief explanation for the following Python 3 code def select(yerrs, amps, amp_errs, widths): keep_1 = np.logical_and(amps < 0, widths > 1) keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps)) keep = np.logical_and(keep_1, keep_2) return keep
As a Python code translator, you convert algorithms and pseudocode into Python.
Load the data that we re using to search for Li - rich giants.
Can you generate the documentation for the following Python 3 function def run_all(): DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels" dates = os.listdir("/home/share/LAMOST/DR2/DR2_release") dates = np.array(dates) dates = np.delete(dates, np.where(dates=='.directory')[0][0]) d...
You are a Python code analyst, evaluating scripts for potential improvements.
Generate the gradient of a Cannon graph based on the base_labels and coeffs.
Explain what the following Python 3 code does def gen_cannon_grad_spec(base_labels, choose, low, high, coeffs, pivots): # Generate Cannon gradient spectra low_lab = copy.copy(base_labels) low_lab[choose] = low lvec = (train_model._get_lvec(np.array([low_lab]), pivots))[0] model_low = np.dot(coeffs, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get approximate scatters from SNR.
Explain what the following Python 3 code does def get_err(snr): quad_terms = np.array( [3.11e-3, 1.10e-5, 6.95e-6, 5.05e-6, 4.65e-6, 4.10e-6]) lin_terms = np.array( [-0.869, -2.07e-3, -1.40e-3, -1.03e-3, -1.13e-3, -7.29e-4]) consts = np.array([104, 0.200, 0.117, 0.114, 0.156, 0.0624...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_colors(catalog): """ Pull colors from catalog Parameters ---------- catalog: filename """ print("Get Colors") a = pyfits.open(catalog) data = a[1].data a.close() all_ids = data['LAMOST_ID_1'] all_ids = np.array([val.strip() for val in all_ids]) # G magnitude...
Create a Python 3 function to get colors from a catalog
You are a Python code generator, capable of creating scripts from specifications.
Generates the best fit spectra for all the test objects
How would you explain what the following Python 3 function does def draw_spectra(md, ds): coeffs_all, covs, scatters, red_chisqs, pivots, label_vector = model.model nstars = len(dataset.test_SNR) cannon_flux = np.zeros(dataset.test_flux.shape) cannon_ivar = np.zeros(dataset.test_ivar.shape) for i in...
As a Python code analyst, you investigate and solve complex coding mysteries
Overlays the original spectra with the best fit spectra.
Can you tell what is the following Python 3 function doing def overlay_spectra(model, dataset): best_flux, best_ivar = draw_spectra(model, dataset) coeffs_all, covs, scatters, all_chisqs, pivots, label_vector = model.model # Overplot original spectra with best-fit spectra print("Overplotting spectra fo...
You are a Python code architect, reviewing and designing scalable and efficient code
Stack spectrum fit residuals
Make a summary of the following Python 3 code def residuals(cannon_set, dataset): print("Stacking spectrum fit residuals") res = dataset.test_fluxes - cannon_set.test_fluxes bad = dataset.test_ivars == SMALL**2 err = np.zeros(len(dataset.test_ivars)) err = np.sqrt(1. / dataset.test_ivars + 1. / cann...
As a Python code analyst, you investigate and solve complex coding mysteries
Find and return continuum pixels given the flux and sigma cuts.
How would you explain what the following Python 3 function does def _find_contpix_given_cuts(f_cut, sig_cut, wl, fluxes, ivars): f_bar = np.median(fluxes, axis=0) sigma_f = np.var(fluxes, axis=0) bad = np.logical_and(f_bar==0, sigma_f==0) cont1 = np.abs(f_bar-1) <= f_cut cont2 = sigma_f <= sig_cut ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _find_contpix(wl, fluxes, ivars, target_frac): """ Find continuum pix in spec, meeting a set target fraction Parameters ---------- wl: numpy ndarray rest-frame wavelength vector fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, par...
Create a Python 3 function to find continuum pix in the spec meeting a set target fraction.
You are a Python code architect, reviewing and designing scalable and efficient code
Find continuum pix in a spectrum split into chunks
Make a summary of the following Python 3 code def _find_contpix_regions(wl, fluxes, ivars, frac, ranges): contmask = np.zeros(len(wl), dtype=bool) for chunk in ranges: start = chunk[0] stop = chunk[1] contmask[start:stop] = _find_contpix( wl[start:stop], fluxes[:,start:st...
As a python code expert, you are capable of creating scripts from specifications.
def group_data(): """ Load the reference data, and assign each object a random integer from 0 to 7. Save the IDs. """ tr_obj = np.load("%s/ref_id.npz" %direc_ref)['arr_0'] groups = np.random.randint(0, 8, size=len(tr_obj)) np.savez("ref_groups.npz", groups)
Create a Python 3 function to load the reference data and assign each object a random integer from 0 to 7. Save the IDs.
You are a Python code analyst, evaluating scripts for potential improvements.
Train the Cannon model on a dataset object.
Explain what the following Python 3 code does def train(ds, ii): print("Loading model") m = model.CannonModel(2) print("Training...") m.fit(ds) np.savez("./ex%s_coeffs.npz" %ii, m.coeffs) np.savez("./ex%s_scatters.npz" %ii, m.scatters) np.savez("./ex%s_chisqs.npz" %ii, m.chisqs) np.savez...
As a Python code analyst, you investigate and solve complex coding mysteries
Train a model on the remaining 1 / 8 of the sample.
Here you have a function in Python 3, explain what it does def xvalidate(): print("Loading data") groups = np.load("ref_groups.npz")['arr_0'] ref_label = np.load("%s/ref_label.npz" %direc_ref)['arr_0'] ref_id = np.load("%s/ref_id.npz" %direc_ref)['arr_0'] ref_flux = np.load("%s/ref_flux.npz" %direc...
You are a Python code architect, reviewing and designing scalable and efficient code
def weighted_std(values, weights): """ Calculate standard deviation weighted by errors """ average = np.average(values, weights=weights) variance = np.average((values-average)**2, weights=weights) return np.sqrt(variance)
Implement a Python 3 function for calculating the weighted standard deviation of a sequence of values.
As a Python code analyst, you investigate and solve complex coding mysteries
def estimate_noise(fluxes, contmask): """ Estimate the scatter in a region of the spectrum taken to be continuum """ nstars = fluxes.shape[0] scatter = np.zeros(nstars) for i,spec in enumerate(fluxes): cont = spec[contmask] scatter[i] = stats.funcs.mad_std(cont) return scatter
Create a Python 3 function to estimate the scatter in a region of the spectrum taken to be continuum
You are a Python code architect, reviewing and designing scalable and efficient code
Load the training spectra from the first file in the directory and return the wavelength array
Make a summary of the following Python 3 code def load_ref_spectra(): data_dir = "/Users/annaho/Data/AAOmega/ref_spectra" # Load the files & count the number of training objects ff = glob.glob("%s/*.txt" %data_dir) nstars = len(ff) print("We have %s training objects" %nstars) # Read the fir...
You are a Python code architect, reviewing and designing scalable and efficient code
def load_data(): data_dir = "/Users/annaho/Data/AAOmega" out_dir = "%s/%s" %(data_dir, "Run_13_July") """ Use all the above functions to set data up for The Cannon """ ff, wl, tr_flux, tr_ivar = load_ref_spectra() """ pick one that doesn't have extra dead pixels """ skylines = tr_ivar[4,:] # s...
Can you write a function in Python 3 where it loads the data for the AAOmega object.
You are a Python code architect, reviewing and designing scalable and efficient code
def make_full_ivar(): """ take the scatters and skylines and make final ivars """ # skylines come as an ivar # don't use them for now, because I don't really trust them... # skylines = np.load("%s/skylines.npz" %DATA_DIR)['arr_0'] ref_flux = np.load("%s/ref_flux_all.npz" %DATA_DIR)['arr_0'] re...
Create a Python 3 function for taking the scatters and skylines and make final ivars
As a Python code composer, you craft elegant and concise scripts.
Returns the sinusoid contfunc evaluated at input x for the continuum.
Given the following Python 3 function, write the documentation def _sinusoid(x, p, L, y): N = int(len(p)/2) n = np.linspace(0, N, N+1) k = n*np.pi/L func = 0 for n in range(0, N): func += p[2*n]*np.sin(k[n]*x)+p[2*n+1]*np.cos(k[n]*x) return func
As a Python code composer, you craft elegant and concise scripts.
Calculate a weighted median of a set of values
Can you generate a brief explanation for the following Python 3 code def _weighted_median(values, weights, quantile): sindx = np.argsort(values) cvalues = 1. * np.cumsum(weights[sindx]) if cvalues[-1] == 0: # means all the values are 0 return values[0] cvalues = cvalues / cvalues[-1] # div by la...
As a Python code analyst, you investigate and solve complex coding mysteries
Finds the weighted mean block of spectra with Gaussian smoothed fluxes.
How would you explain what the following Python 3 function does def _find_cont_gaussian_smooth(wl, fluxes, ivars, w): print("Finding the continuum") bot = np.dot(ivars, w.T) top = np.dot(fluxes*ivars, w.T) bad = bot == 0 cont = np.zeros(top.shape) cont[~bad] = top[~bad] / bot[~bad] return co...
As a Python code analyst, you investigate and solve complex coding mysteries
Continuum normalize by dividing by a Gaussian - weighted smoothed spectrum
Can you tell what is the following Python 3 function doing def _cont_norm_gaussian_smooth(dataset, L): print("Gaussian smoothing the entire dataset...") w = gaussian_weight_matrix(dataset.wl, L) print("Gaussian smoothing the training set") cont = _find_cont_gaussian_smooth( dataset.wl, data...
As a Python code analyst, you investigate and solve complex coding mysteries
def _find_cont_fitfunc(fluxes, ivars, contmask, deg, ffunc, n_proc=1): """ Fit a continuum to a continuum pixels in a segment of spectra Functional form can be either sinusoid or chebyshev, with specified degree Parameters ---------- fluxes: numpy ndarray of shape (nstars, npixels) trainin...
Can you create a Python 3 function that fits a continuum to a single segment of spectra.
You are a Python code architect, reviewing and designing scalable and efficient code
def _find_cont_fitfunc_regions(fluxes, ivars, contmask, deg, ranges, ffunc, n_proc=1): """ Run fit_cont, dealing with spectrum in regions or chunks This is useful if a spectrum has gaps. Parameters ---------- fluxes: ndarray of shape (nstars, npixels) trainin...
How would you code a function in Python 3 to find the continuum in the given set of fluxes and the given mask.
As a Python code composer, you craft elegant and concise scripts.
Perform continuum normalization using a running quantile
Explain what the following Python 3 code does def _find_cont_running_quantile(wl, fluxes, ivars, q, delta_lambda, verbose=False): """ Perform continuum normalization using a running quantile Parameters ---------- wl: numpy ndarray wavelength vector fluxes: n...
As a python code expert, you are capable of creating scripts from specifications.