Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|>
if __name__ == "__main__":
path = "/Users/musthero/Documents/Yura/Applications/tmva_local/BDT_score_distributions_electrons.root"
hsig_path = "histo_tmva_sig"
hbkg_path = "histo_tmva_bkg"
rootfile = ROOT.TFile.Open(path)
if rootfile.IsZombie():
print "Root file is corrupt"
hSig = rootfile.Get(hsig_path)
hBkg = rootfile.Get(hbkg_path)
<|code_end|>
, determine the next line of code. You have imports:
import ROOT
from ROOT import TGraphErrors
from array import array
from mva_tools.build_roc_simple import build_roc
and context (class names, function names, or code) available:
# Path: mva_tools/build_roc_simple.py
# def build_roc(h_sig, h_bkg, verbose=0):
#
# nbins_sig = h_sig.GetXaxis().GetNbins()
# nbins_bkg = h_bkg.GetXaxis().GetNbins()
# nbins = nbins_sig if nbins_sig == nbins_bkg else -1
# #print nbins
# if nbins < 0.0:
# sys.exit("Error: nbins_sig != nbins_bkg")
#
# min_val = h_sig.GetXaxis().GetXmin()
# max_val = h_sig.GetXaxis().GetXmax()
#
# step = float(max_val - min_val)/(nbins-1)
# sig_eff = array('f', [])
# bkg_rej = array('f', [])
#
# total_sig = h_sig.Integral()
# total_bkg = h_bkg.Integral()
# print total_sig
# print total_bkg
#
# sig_rejected = 0.0
# bkg_rejected = 0.0
# for i in xrange_bins(nbins):
# sig_rejected += h_sig.GetBinContent(i)
# #print sig_rejected
# bkg_rejected += h_bkg.GetBinContent(i)
# #print bkg_rejected
#
# seff = float(total_sig-sig_rejected)/total_sig
# brej = float(bkg_rejected)/total_bkg
# #print seff, brej
# sig_eff.append(seff)
# bkg_rej.append(brej)
#
# if verbose == 1:
# bdt_score = min_val + i * step
# print "bdt score =", bdt_score, "sig_eff =", seff
#
# #bin_sig = h_sig.GetBinContent()
# print "Overflow =", h_sig.GetBinContent(nbins_sig+1)
# print "Underflow =", h_sig.GetBinContent(0)
#
# g = ROOT.TGraph(nbins, sig_eff, bkg_rej)
# g.GetXaxis().SetRangeUser(0.0,1.0)
# g.GetYaxis().SetRangeUser(0.0,1.0)
# #g.Draw("AC")
# #g.SetLineColor(ROOT.kRed)
# g.SetTitle("ROC curve")
#
#
# return g
#
# #print nbins_bkg
. Output only the next line. | g = build_roc(hSig, hBkg, 1) |
Here is a snippet: <|code_start|> histo_tmva_bkg.Fill(bdtOutput)
elif m_el_isprompt == 1:
histo_tmva_sig.Fill(bdtOutput)
else:
print "Warning: m_mu_isprompt is not 0 or 1!!!"
file.Close()
X_test = np.array(_X_test)
y_test = np.array(_y_test)
# sklearn tpr and tpr
sk_y_predicted = bdt.predict_proba(X_test)[:, 1]
fpr, tpr, _ = roc_curve(y_test, sk_y_predicted)
sig_eff = array.array('f', [rate for rate in tpr])
bkg_rej = array.array('f',[ (1-rate) for rate in fpr])
# roc_curve_sk() - skTMVA version of roc_curve
fpr_comp, tpr_comp, _ = roc_curve_sk(y_test, sk_y_predicted)
sig_eff_comp = array.array('f', [rate for rate in tpr_comp])
bkg_rej_comp = array.array('f',[ (1-rate) for rate in fpr_comp])
# Stack for keeping plots
plots = []
# Getting ROC-curve for skTMVA
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import ROOT
import array
import numpy as np
import cPickle
from ROOT import TH1F
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import classification_report, roc_auc_score, roc_curve
from sklearn import tree
from mva_tools.build_roc_simple import build_roc
from mva_tools.build_roc_simple import roc_curve_sk
and context from other files:
# Path: mva_tools/build_roc_simple.py
# def build_roc(h_sig, h_bkg, verbose=0):
#
# nbins_sig = h_sig.GetXaxis().GetNbins()
# nbins_bkg = h_bkg.GetXaxis().GetNbins()
# nbins = nbins_sig if nbins_sig == nbins_bkg else -1
# #print nbins
# if nbins < 0.0:
# sys.exit("Error: nbins_sig != nbins_bkg")
#
# min_val = h_sig.GetXaxis().GetXmin()
# max_val = h_sig.GetXaxis().GetXmax()
#
# step = float(max_val - min_val)/(nbins-1)
# sig_eff = array('f', [])
# bkg_rej = array('f', [])
#
# total_sig = h_sig.Integral()
# total_bkg = h_bkg.Integral()
# print total_sig
# print total_bkg
#
# sig_rejected = 0.0
# bkg_rejected = 0.0
# for i in xrange_bins(nbins):
# sig_rejected += h_sig.GetBinContent(i)
# #print sig_rejected
# bkg_rejected += h_bkg.GetBinContent(i)
# #print bkg_rejected
#
# seff = float(total_sig-sig_rejected)/total_sig
# brej = float(bkg_rejected)/total_bkg
# #print seff, brej
# sig_eff.append(seff)
# bkg_rej.append(brej)
#
# if verbose == 1:
# bdt_score = min_val + i * step
# print "bdt score =", bdt_score, "sig_eff =", seff
#
# #bin_sig = h_sig.GetBinContent()
# print "Overflow =", h_sig.GetBinContent(nbins_sig+1)
# print "Underflow =", h_sig.GetBinContent(0)
#
# g = ROOT.TGraph(nbins, sig_eff, bkg_rej)
# g.GetXaxis().SetRangeUser(0.0,1.0)
# g.GetYaxis().SetRangeUser(0.0,1.0)
# #g.Draw("AC")
# #g.SetLineColor(ROOT.kRed)
# g.SetTitle("ROC curve")
#
#
# return g
#
# #print nbins_bkg
#
# Path: mva_tools/build_roc_simple.py
# def roc_curve_sk(y_test, sk_y_predicted, step = 0.001):
#
# pos_label = 1 # prompt lepton
# neg_label = 0 # non-prompt lepton
#
# y_test = column_or_1d(y_test)
#
# assert y_test.size == sk_y_predicted.size, "Error: len(y_test) != len(sk_y_predicted)"
# assert np.unique(y_test).size == 2, "Error: number of classes is %i. Expected 2 classes only." % np.unique(y_test).size
#
# # calculate number of prompt and non-prompt leptons
# num_prompts = np.sum(y_test == pos_label)
# num_nonprompts = y_test.size - num_prompts
#
# # array of probability cut values
# # minimum probability is 0, maximum is one,
# # and step is defind above
# cuts = np.arange(0, 1, step)
#
# tpr = []
# fpr = []
#
# for cut in cuts:
# prompts_passed = 0
# nonprompts_passed = 0
#
# indxs = np.where(sk_y_predicted >= cut)
# y_test_passed = np.take(y_test, indxs)
# prompts_passed = np.sum(y_test_passed == pos_label)
# nonprompts_passed = np.sum(y_test_passed == neg_label)
#
# tpr.append(float(prompts_passed)/num_prompts)
# fpr.append(float(nonprompts_passed)/num_nonprompts)
#
# return np.array(fpr), np.array(tpr), 0
, which may include functions, classes, or code. Output only the next line. | g1 = build_roc(histo_tmva_sig, histo_tmva_bkg) |
Here is a snippet: <|code_start|> # m_el_etcone20Dpt[0], m_el_ptcone20Dpt[0]]).item(0)
_X_test.append([m_el_pt[0], m_el_eta[0], m_el_sigd0PV[0], m_el_z0SinTheta[0], m_el_etcone20Dpt[0], m_el_ptcone20Dpt[0]])
_y_test.append([m_el_isprompt])
# calculate the value of the classifier with TMVA/TskMVA
bdtOutput = reader.EvaluateMVA("BDT")
if m_el_isprompt == 0:
histo_tmva_bkg.Fill(bdtOutput)
elif m_el_isprompt == 1:
histo_tmva_sig.Fill(bdtOutput)
else:
print "Warning: m_mu_isprompt is not 0 or 1!!!"
file.Close()
X_test = np.array(_X_test)
y_test = np.array(_y_test)
# sklearn tpr and tpr
sk_y_predicted = bdt.predict_proba(X_test)[:, 1]
fpr, tpr, _ = roc_curve(y_test, sk_y_predicted)
sig_eff = array.array('f', [rate for rate in tpr])
bkg_rej = array.array('f',[ (1-rate) for rate in fpr])
# roc_curve_sk() - skTMVA version of roc_curve
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import ROOT
import array
import numpy as np
import cPickle
from ROOT import TH1F
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import classification_report, roc_auc_score, roc_curve
from sklearn import tree
from mva_tools.build_roc_simple import build_roc
from mva_tools.build_roc_simple import roc_curve_sk
and context from other files:
# Path: mva_tools/build_roc_simple.py
# def build_roc(h_sig, h_bkg, verbose=0):
#
# nbins_sig = h_sig.GetXaxis().GetNbins()
# nbins_bkg = h_bkg.GetXaxis().GetNbins()
# nbins = nbins_sig if nbins_sig == nbins_bkg else -1
# #print nbins
# if nbins < 0.0:
# sys.exit("Error: nbins_sig != nbins_bkg")
#
# min_val = h_sig.GetXaxis().GetXmin()
# max_val = h_sig.GetXaxis().GetXmax()
#
# step = float(max_val - min_val)/(nbins-1)
# sig_eff = array('f', [])
# bkg_rej = array('f', [])
#
# total_sig = h_sig.Integral()
# total_bkg = h_bkg.Integral()
# print total_sig
# print total_bkg
#
# sig_rejected = 0.0
# bkg_rejected = 0.0
# for i in xrange_bins(nbins):
# sig_rejected += h_sig.GetBinContent(i)
# #print sig_rejected
# bkg_rejected += h_bkg.GetBinContent(i)
# #print bkg_rejected
#
# seff = float(total_sig-sig_rejected)/total_sig
# brej = float(bkg_rejected)/total_bkg
# #print seff, brej
# sig_eff.append(seff)
# bkg_rej.append(brej)
#
# if verbose == 1:
# bdt_score = min_val + i * step
# print "bdt score =", bdt_score, "sig_eff =", seff
#
# #bin_sig = h_sig.GetBinContent()
# print "Overflow =", h_sig.GetBinContent(nbins_sig+1)
# print "Underflow =", h_sig.GetBinContent(0)
#
# g = ROOT.TGraph(nbins, sig_eff, bkg_rej)
# g.GetXaxis().SetRangeUser(0.0,1.0)
# g.GetYaxis().SetRangeUser(0.0,1.0)
# #g.Draw("AC")
# #g.SetLineColor(ROOT.kRed)
# g.SetTitle("ROC curve")
#
#
# return g
#
# #print nbins_bkg
#
# Path: mva_tools/build_roc_simple.py
# def roc_curve_sk(y_test, sk_y_predicted, step = 0.001):
#
# pos_label = 1 # prompt lepton
# neg_label = 0 # non-prompt lepton
#
# y_test = column_or_1d(y_test)
#
# assert y_test.size == sk_y_predicted.size, "Error: len(y_test) != len(sk_y_predicted)"
# assert np.unique(y_test).size == 2, "Error: number of classes is %i. Expected 2 classes only." % np.unique(y_test).size
#
# # calculate number of prompt and non-prompt leptons
# num_prompts = np.sum(y_test == pos_label)
# num_nonprompts = y_test.size - num_prompts
#
# # array of probability cut values
# # minimum probability is 0, maximum is one,
# # and step is defind above
# cuts = np.arange(0, 1, step)
#
# tpr = []
# fpr = []
#
# for cut in cuts:
# prompts_passed = 0
# nonprompts_passed = 0
#
# indxs = np.where(sk_y_predicted >= cut)
# y_test_passed = np.take(y_test, indxs)
# prompts_passed = np.sum(y_test_passed == pos_label)
# nonprompts_passed = np.sum(y_test_passed == neg_label)
#
# tpr.append(float(prompts_passed)/num_prompts)
# fpr.append(float(nonprompts_passed)/num_nonprompts)
#
# return np.array(fpr), np.array(tpr), 0
, which may include functions, classes, or code. Output only the next line. | fpr_comp, tpr_comp, _ = roc_curve_sk(y_test, sk_y_predicted) |
Based on the snippet: <|code_start|>
if __name__ == "__main__":
path = "/Users/musthero/Documents/Yura/Applications/tmva_local/BDT_score_distributions_muons.root"
hsig_skTMVA_path = "histo_tmva_sig"
hbkg_skTMVA_path = "histo_tmva_bkg"
hsig_sklearn_path = "histo_sk_sig"
hbkg_sklearn_path = "histo_sk_bkg"
rootfile = ROOT.TFile.Open(path)
if rootfile.IsZombie():
print "Root file is corrupt"
hSig_skTMVA = rootfile.Get(hsig_skTMVA_path)
hBkg_skTMVA = rootfile.Get(hbkg_skTMVA_path)
hSig_sklearn = rootfile.Get(hsig_sklearn_path)
hBkg_sklearn = rootfile.Get(hbkg_sklearn_path)
# Stack for keeping plots
plots = []
# Getting ROC-curve for skTMVA
<|code_end|>
, predict the immediate next line with the help of imports:
import ROOT
from ROOT import TGraphErrors
from array import array
from mva_tools.build_roc_simple import build_roc
and context (classes, functions, sometimes code) from other files:
# Path: mva_tools/build_roc_simple.py
# def build_roc(h_sig, h_bkg, verbose=0):
#
# nbins_sig = h_sig.GetXaxis().GetNbins()
# nbins_bkg = h_bkg.GetXaxis().GetNbins()
# nbins = nbins_sig if nbins_sig == nbins_bkg else -1
# #print nbins
# if nbins < 0.0:
# sys.exit("Error: nbins_sig != nbins_bkg")
#
# min_val = h_sig.GetXaxis().GetXmin()
# max_val = h_sig.GetXaxis().GetXmax()
#
# step = float(max_val - min_val)/(nbins-1)
# sig_eff = array('f', [])
# bkg_rej = array('f', [])
#
# total_sig = h_sig.Integral()
# total_bkg = h_bkg.Integral()
# print total_sig
# print total_bkg
#
# sig_rejected = 0.0
# bkg_rejected = 0.0
# for i in xrange_bins(nbins):
# sig_rejected += h_sig.GetBinContent(i)
# #print sig_rejected
# bkg_rejected += h_bkg.GetBinContent(i)
# #print bkg_rejected
#
# seff = float(total_sig-sig_rejected)/total_sig
# brej = float(bkg_rejected)/total_bkg
# #print seff, brej
# sig_eff.append(seff)
# bkg_rej.append(brej)
#
# if verbose == 1:
# bdt_score = min_val + i * step
# print "bdt score =", bdt_score, "sig_eff =", seff
#
# #bin_sig = h_sig.GetBinContent()
# print "Overflow =", h_sig.GetBinContent(nbins_sig+1)
# print "Underflow =", h_sig.GetBinContent(0)
#
# g = ROOT.TGraph(nbins, sig_eff, bkg_rej)
# g.GetXaxis().SetRangeUser(0.0,1.0)
# g.GetYaxis().SetRangeUser(0.0,1.0)
# #g.Draw("AC")
# #g.SetLineColor(ROOT.kRed)
# g.SetTitle("ROC curve")
#
#
# return g
#
# #print nbins_bkg
. Output only the next line. | g1 = build_roc(hSig_skTMVA, hBkg_skTMVA) |
Predict the next line after this snippet: <|code_start|> np.ones(n_vars) * -1, np.diag(np.ones(n_vars)), n_events)
X = np.concatenate([signal, background])
y = np.ones(X.shape[0])
w = RNG.randint(1, 10, n_events * 2)
y[signal.shape[0]:] *= -1
permute = RNG.permutation(y.shape[0])
X = X[permute]
y = y[permute]
# Use all dataset for training
X_train, y_train, w_train = X, y, w
# Declare BDT - we are going to use AdaBoost Decision Tree
bdt = GradientBoostingClassifier(
n_estimators=200, learning_rate=0.5,
min_samples_leaf=int(0.05*len(X_train)),
max_depth=3, random_state=0)
# Train BDT
bdt.fit(X_train, y_train)
# Save BDT to pickle file
with open('bdt_sklearn_to_tmva_example.pkl', 'wb') as fid:
cPickle.dump(bdt, fid)
# Save BDT to TMVA xml file
# Note:
# - declare input variable names and their type
# - variable order is important for TMVA
<|code_end|>
using the current file's imports:
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import GradientBoostingClassifier
from skTMVA import convert_bdt_sklearn_tmva
from numpy.random import RandomState
import cPickle
import numpy as np
and any relevant context from other files:
# Path: skTMVA/skTMVA.py
# def convert_bdt_sklearn_tmva(sklearn_bdt_clf, input_var_list, tmva_outfile_xml):
#
# # AdaBoost
# if isinstance(sklearn_bdt_clf, AdaBoostClassifier):
# convert_bdt__AdaBoost(sklearn_bdt_clf, input_var_list, tmva_outfile_xml)
#
# # Gradient Boosting (binary classification only)
# if isinstance(sklearn_bdt_clf, GradientBoostingClassifier):
# convert_bdt__Grad(sklearn_bdt_clf, input_var_list, tmva_outfile_xml)
. Output only the next line. | convert_bdt_sklearn_tmva(bdt, [('var1', 'F'), ('var2', 'F')], 'bdt_sklearn_to_tmva_example.xml') |
Predict the next line after this snippet: <|code_start|>y = np.ones(X.shape[0])
w = RNG.randint(1, 10, n_events * 2)
y[signal.shape[0]:] *= -1
permute = RNG.permutation(y.shape[0])
X = X[permute]
y = y[permute]
# Use all dataset for training
X_train, y_train, w_train = X, y, w
# Declare BDT - we are going to use AdaBoost Decision Tree
dt = DecisionTreeClassifier(max_depth=3,
min_samples_leaf=int(0.05*len(X_train)))
bdt = AdaBoostClassifier(dt,
algorithm='SAMME',
n_estimators=800,
learning_rate=0.5)
# Train BDT
bdt.fit(X_train, y_train)
# Save BDT to pickle file
with open('bdt_sklearn_to_tmva_example.pkl', 'wb') as fid:
cPickle.dump(bdt, fid)
# Save BDT to TMVA xml file
# Note:
# - declare input variable names and their type
# - variable order is important for TMVA
<|code_end|>
using the current file's imports:
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from skTMVA import convert_bdt_sklearn_tmva
from numpy.random import RandomState
import cPickle
import numpy as np
and any relevant context from other files:
# Path: skTMVA/skTMVA.py
# def convert_bdt_sklearn_tmva(sklearn_bdt_clf, input_var_list, tmva_outfile_xml):
#
# # AdaBoost
# if isinstance(sklearn_bdt_clf, AdaBoostClassifier):
# convert_bdt__AdaBoost(sklearn_bdt_clf, input_var_list, tmva_outfile_xml)
#
# # Gradient Boosting (binary classification only)
# if isinstance(sklearn_bdt_clf, GradientBoostingClassifier):
# convert_bdt__Grad(sklearn_bdt_clf, input_var_list, tmva_outfile_xml)
. Output only the next line. | convert_bdt_sklearn_tmva(bdt, [('var1', 'F'), ('var2', 'F')], 'bdt_sklearn_to_tmva_example.xml') |
Predict the next line for this snippet: <|code_start|>
def filterable(f):
"""Filter a query"""
@wraps(f)
def wrapped(*args, **kwargs):
d = f(*args, **kwargs)
q = d['query']
state = request.args.get('state', None, type=str)
if state:
<|code_end|>
with the help of current file imports:
from functools import wraps
from flask import render_template, request, url_for
from app.models import PatchState
and context from other files:
# Path: app/models.py
# class PatchState(DeclEnum):
# unreviewed = "U", "Unreviewed"
# comments = "C", "Comments"
# accepted = "A", "Accepted"
# rejected = "R", "Rejected"
, which may contain function names, class names, or code. Output only the next line. | q = q.filter_by(state=PatchState.from_string(state)) |
Predict the next line after this snippet: <|code_start|>
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinxcontrib.napoleon',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['ntemplates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pyhamtools'
copyright = u'2019, Tobias Wellnitz, DH1TW'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
<|code_end|>
using the current file's imports:
import sys
import os
from pyhamtools.version import __version__, __release__
and any relevant context from other files:
# Path: pyhamtools/version.py
# VERSION = (0, 7, 9)
. Output only the next line. | version = __version__ |
Given the code snippet: <|code_start|># extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinxcontrib.napoleon',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['ntemplates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pyhamtools'
copyright = u'2019, Tobias Wellnitz, DH1TW'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
<|code_end|>
, generate the next line using the imports in this file:
import sys
import os
from pyhamtools.version import __version__, __release__
and context (functions, classes, or occasionally code) from other files:
# Path: pyhamtools/version.py
# VERSION = (0, 7, 9)
. Output only the next line. | release = __release__ |
Next line prediction: <|code_start|>
response_Exception_VP8STI_with_start_and_stop_date = {
'adif': 240,
'country': u'SOUTH SANDWICH ISLANDS',
'continent': u'SA',
'latitude': -59.48,
'longitude': -27.29,
'cqz': 13,
}
response_Exception_VK9XO_with_start_date = {
'adif': 35,
'country': 'CHRISTMAS ISLAND',
'continent': 'OC',
'latitude': -10.50,
'longitude': 105.70,
'cqz': 29
}
response_zone_exception_ci8aw = {
'country': 'CANADA',
'adif': 1,
'cqz': 1,
'latitude': 45.0,
'longitude': -80.0,
'continent': 'NA'
}
response_lat_long_dh1tw = {
<|code_end|>
. Use current file imports:
(from datetime import datetime
from pyhamtools.consts import LookupConventions as const
import pytest
import pytz)
and context including class names, function names, or small code snippets from other files:
# Path: pyhamtools/consts.py
# class LookupConventions:
# """ This class defines the constants used within the pyhamtools package """
#
# # Mostly specific to Clublog XML File
# CALLSIGN = u"callsign"
# COUNTRY = u"country"
# PREFIX = u"prefix"
# ADIF = u"adif"
# CQZ = u"cqz"
# ITUZ = u"ituz"
# CONTINENT = u"continent"
# LATITUDE = u"latitude"
# LONGITUDE = u"longitude"
# START = u"start"
# END = u"end"
# WHITELIST = u"whitelist"
# WHITELIST_START = u"whitelist_start"
# WHITELIST_END = u"whitelist_end"
# DELETED = u"deleted"
# MARITIME_MOBILE = u"mm"
# AIRCRAFT_MOBILE = u"am"
# LOCATOR = u"locator"
# BEACON = u"beacon"
#
# #CQ / DIGITAL Skimmer specific
#
# SKIMMER = u"skimmer"
# FS = u"fs" #fieldstrength
# WPM = u"wpm" #words / bytes per second
# CQ = u"cq"
# NCDXF = u"ncdxf"
#
#
# # Modes
# CW = u"CW"
# USB = u"USB"
# LSB = u"LSB"
# DIGITAL = u"DIGITAL"
# FM = u"FM"
# # FT8 = u'FT8'
#
# #DX Spot
# SPOTTER = u"spotter"
# DX = u"dx"
# FREQUENCY = u"frequency"
# COMMENT = u"comment"
# TIME = u"time"
# BAND = u"band"
# MODE = u"mode"
#
# #DX Spider specific
# ORIGIN_NODE = u"node"
# HOPS = u"hops"
# RAW_SPOT = u"raw"
# IP = u"ip"
# ROUTE = u"route"
# TEXT = u"text"
# SYSOP_FLAG = u"sysop_flag"
# WX_FLAG = u"wx_flag"
#
# #WWV & WCY
# STATION = u"station"
# R = u"r"
# K = u"k"
# EXPK = u"expk"
# SFI = u"sfi"
# A = u"a"
# AURORA = u"aurora"
# SA = u"sa"
# GMF = u"gmf"
# FORECAST = u"forecast"
#
# #QRZ.com
# XREF = u"xref"
# ALIASES = u"aliases"
# FNAME = u"fname"
# NAME = u"name"
# ADDR1 = u"addr1"
# ADDR2 = u"addr2"
# STATE = u"state"
# ZIPCODE = u"zipcode"
# CCODE = u"ccode"
# COUNTY = u"county"
# FIPS = u"fips"
# LAND = u"land"
# EFDATE = u"efdate"
# EXPDATE = u"expdate"
# P_CALL = u"p_call"
# LICENSE_CLASS = u"license_class"
# CODES = u"codes"
# QSLMGR = u"qslmgr"
# EMAIL = u"email"
# URL = u"url"
# U_VIEWS = u"u_views"
# BIO = u"bio"
# BIODATE = u"biodate"
# IMAGE = u"image"
# IMAGE_INFO = u"imageinfo"
# SERIAL = u"serial"
# MODDATE = u"moddate"
# MSA = "msa"
# AREACODE = "areacode"
# TIMEZONE = "timezone"
# GMTOFFSET = "gmtoffset"
# DST = "dst"
# EQSL = "eqsl"
# MQSL = "mqsl"
# LOTW = "lotw"
# BORN = "born"
# USER_MGR = "user"
# IOTA = "iota"
# GEOLOC = "geoloc"
. Output only the next line. | const.LATITUDE: 51.0, |
Continue the code snippet: <|code_start|>
if sys.version_info.major == 3:
unicode = str
test_dir = os.path.dirname(os.path.abspath(__file__))
fix_dir = os.path.join(test_dir, 'fixtures')
class Test_lotw_methods:
def test_check_content_with_mocked_http_server(self, httpserver):
httpserver.serve_content(open(os.path.join(fix_dir, 'lotw-user-activity.csv')).read())
namespace = {}
execfile(os.path.join(fix_dir,"lotw_fixture.py"), namespace)
<|code_end|>
. Use current file imports:
import os
import sys
import datetime
import pytest
from past.builtins import execfile
from future.utils import iteritems
from pyhamtools.qsl import get_lotw_users
and context (classes, functions, or code) from other files:
# Path: pyhamtools/qsl.py
# def get_lotw_users(**kwargs):
# """Download the latest offical list of `ARRL Logbook of the World (LOTW)`__ users.
#
# Args:
# url (str, optional): Download URL
#
# Returns:
# dict: Dictionary containing the callsign (unicode) date of the last LOTW upload (datetime)
#
# Raises:
# IOError: When network is unavailable, file can't be downloaded or processed
#
# ValueError: Raised when data from file can't be read
#
# Example:
# The following example downloads the LOTW user list and check when DH1TW has made his last LOTW upload:
#
# >>> from pyhamtools.qsl import get_lotw_users
# >>> mydict = get_lotw_users()
# >>> mydict['DH1TW']
# datetime.datetime(2014, 9, 7, 0, 0)
#
# .. _ARRL: http://www.arrl.org/logbook-of-the-world
# __ ARRL_
#
# """
#
# url = ""
#
# lotw = {}
#
# try:
# url = kwargs['url']
# except KeyError:
# # url = "http://wd5eae.org/LoTW_Data.txt"
# url = "https://lotw.arrl.org/lotw-user-activity.csv"
#
# try:
# result = requests.get(url)
# except (ConnectionError, HTTPError, Timeout) as e:
# raise IOError(e)
#
# error_count = 0
#
# if result.status_code == requests.codes.ok:
# for el in result.text.split():
# data = el.split(",")
# try:
# lotw[data[0]] = datetime.strptime(data[1], '%Y-%m-%d')
# except ValueError as e:
# error_count += 1
# if error_count > 10:
# raise ValueError("more than 10 wrongly formatted datasets " + str(e))
#
# else:
# raise IOError("HTTP Error: " + str(result.status_code))
#
# return lotw
. Output only the next line. | assert get_lotw_users(url=httpserver.url) == namespace['lotw_fixture'] |
Given the code snippet: <|code_start|>
UTC = pytz.UTC
class Test_calculate_sunrise_sunset_normal_case():
def test_calculate_sunrise_sunset(self):
time_margin = timedelta(minutes=1)
locator = "JN48QM"
test_time = datetime(year=2014, month=1, day=1, tzinfo=UTC)
result_JN48QM_1_1_2014_evening_dawn = datetime(2014, 1, 1, 15, 38, tzinfo=UTC)
result_JN48QM_1_1_2014_morning_dawn = datetime(2014, 1, 1, 6, 36, tzinfo=UTC)
result_JN48QM_1_1_2014_sunrise = datetime(2014, 1, 1, 7, 14, tzinfo=UTC)
result_JN48QM_1_1_2014_sunset = datetime(2014, 1, 1, 16, 15, 23, 31016, tzinfo=UTC)
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime, timedelta
from pyhamtools.locator import calculate_sunrise_sunset
import pytest
import pytz
and context (functions, classes, or occasionally code) from other files:
# Path: pyhamtools/locator.py
# def calculate_sunrise_sunset(locator, calc_date=None):
# """calculates the next sunset and sunrise for a Maidenhead locator at a give date & time
#
# Args:
# locator1 (string): Maidenhead Locator, either 4 or 6 characters
# calc_date (datetime, optional): Starting datetime for the calculations (UTC)
#
# Returns:
# dict: Containing datetimes for morning_dawn, sunrise, evening_dawn, sunset
#
# Raises:
# ValueError: When called with wrong or invalid input arg
# AttributeError: When args are not a string
#
# Example:
# The following calculates the next sunrise & sunset for JN48QM on the 1./Jan/2014
#
# >>> from pyhamtools.locator import calculate_sunrise_sunset
# >>> from datetime import datetime
# >>> import pytz
# >>> UTC = pytz.UTC
# >>> myDate = datetime(year=2014, month=1, day=1, tzinfo=UTC)
# >>> calculate_sunrise_sunset("JN48QM", myDate)
# {
# 'morning_dawn': datetime.datetime(2014, 1, 1, 6, 36, 51, 710524, tzinfo=<UTC>),
# 'sunset': datetime.datetime(2014, 1, 1, 16, 15, 23, 31016, tzinfo=<UTC>),
# 'evening_dawn': datetime.datetime(2014, 1, 1, 15, 38, 8, 355315, tzinfo=<UTC>),
# 'sunrise': datetime.datetime(2014, 1, 1, 7, 14, 6, 162063, tzinfo=<UTC>)
# }
#
# """
# morning_dawn = None
# sunrise = None
# evening_dawn = None
# sunset = None
#
# latitude, longitude = locator_to_latlong(locator)
#
# if calc_date is None:
# calc_date = datetime.utcnow()
# if type(calc_date) != datetime:
# raise ValueError
#
# sun = ephem.Sun()
# home = ephem.Observer()
#
# home.lat = str(latitude)
# home.long = str(longitude)
# home.date = calc_date
#
# sun.compute(home)
#
# try:
# nextrise = home.next_rising(sun)
# nextset = home.next_setting(sun)
#
# home.horizon = '-6'
# beg_twilight = home.next_rising(sun, use_center=True)
# end_twilight = home.next_setting(sun, use_center=True)
#
# morning_dawn = beg_twilight.datetime()
# sunrise = nextrise.datetime()
#
# evening_dawn = nextset.datetime()
# sunset = end_twilight.datetime()
#
# #if sun never sets or rises (e.g. at polar circles)
# except ephem.AlwaysUpError as e:
# morning_dawn = None
# sunrise = None
# evening_dawn = None
# sunset = None
# except ephem.NeverUpError as e:
# morning_dawn = None
# sunrise = None
# evening_dawn = None
# sunset = None
#
# result = {}
# result['morning_dawn'] = morning_dawn
# result['sunrise'] = sunrise
# result['evening_dawn'] = evening_dawn
# result['sunset'] = sunset
#
# if morning_dawn:
# result['morning_dawn'] = morning_dawn.replace(tzinfo=UTC)
# if sunrise:
# result['sunrise'] = sunrise.replace(tzinfo=UTC)
# if evening_dawn:
# result['evening_dawn'] = evening_dawn.replace(tzinfo=UTC)
# if sunset:
# result['sunset'] = sunset.replace(tzinfo=UTC)
# return result
. Output only the next line. | assert calculate_sunrise_sunset(locator, test_time)['morning_dawn'] - result_JN48QM_1_1_2014_morning_dawn < time_margin |
Based on the snippet: <|code_start|>
def freq_to_band(freq):
"""converts a Frequency [kHz] into the band and mode according to the IARU bandplan
Note:
**DEPRECATION NOTICE**
This function has been moved to pyhamtools.frequency with PyHamTools 0.4.1
Please don't use this module/function anymore. It will be removed soon.
"""
band = None
mode = None
if ((freq >= 135) and (freq <= 138)):
band = 2190
<|code_end|>
, predict the immediate next line with the help of imports:
from pyhamtools.consts import LookupConventions as const
and context (classes, functions, sometimes code) from other files:
# Path: pyhamtools/consts.py
# class LookupConventions:
# """ This class defines the constants used within the pyhamtools package """
#
# # Mostly specific to Clublog XML File
# CALLSIGN = u"callsign"
# COUNTRY = u"country"
# PREFIX = u"prefix"
# ADIF = u"adif"
# CQZ = u"cqz"
# ITUZ = u"ituz"
# CONTINENT = u"continent"
# LATITUDE = u"latitude"
# LONGITUDE = u"longitude"
# START = u"start"
# END = u"end"
# WHITELIST = u"whitelist"
# WHITELIST_START = u"whitelist_start"
# WHITELIST_END = u"whitelist_end"
# DELETED = u"deleted"
# MARITIME_MOBILE = u"mm"
# AIRCRAFT_MOBILE = u"am"
# LOCATOR = u"locator"
# BEACON = u"beacon"
#
# #CQ / DIGITAL Skimmer specific
#
# SKIMMER = u"skimmer"
# FS = u"fs" #fieldstrength
# WPM = u"wpm" #words / bytes per second
# CQ = u"cq"
# NCDXF = u"ncdxf"
#
#
# # Modes
# CW = u"CW"
# USB = u"USB"
# LSB = u"LSB"
# DIGITAL = u"DIGITAL"
# FM = u"FM"
# # FT8 = u'FT8'
#
# #DX Spot
# SPOTTER = u"spotter"
# DX = u"dx"
# FREQUENCY = u"frequency"
# COMMENT = u"comment"
# TIME = u"time"
# BAND = u"band"
# MODE = u"mode"
#
# #DX Spider specific
# ORIGIN_NODE = u"node"
# HOPS = u"hops"
# RAW_SPOT = u"raw"
# IP = u"ip"
# ROUTE = u"route"
# TEXT = u"text"
# SYSOP_FLAG = u"sysop_flag"
# WX_FLAG = u"wx_flag"
#
# #WWV & WCY
# STATION = u"station"
# R = u"r"
# K = u"k"
# EXPK = u"expk"
# SFI = u"sfi"
# A = u"a"
# AURORA = u"aurora"
# SA = u"sa"
# GMF = u"gmf"
# FORECAST = u"forecast"
#
# #QRZ.com
# XREF = u"xref"
# ALIASES = u"aliases"
# FNAME = u"fname"
# NAME = u"name"
# ADDR1 = u"addr1"
# ADDR2 = u"addr2"
# STATE = u"state"
# ZIPCODE = u"zipcode"
# CCODE = u"ccode"
# COUNTY = u"county"
# FIPS = u"fips"
# LAND = u"land"
# EFDATE = u"efdate"
# EXPDATE = u"expdate"
# P_CALL = u"p_call"
# LICENSE_CLASS = u"license_class"
# CODES = u"codes"
# QSLMGR = u"qslmgr"
# EMAIL = u"email"
# URL = u"url"
# U_VIEWS = u"u_views"
# BIO = u"bio"
# BIODATE = u"biodate"
# IMAGE = u"image"
# IMAGE_INFO = u"imageinfo"
# SERIAL = u"serial"
# MODDATE = u"moddate"
# MSA = "msa"
# AREACODE = "areacode"
# TIMEZONE = "timezone"
# GMTOFFSET = "gmtoffset"
# DST = "dst"
# EQSL = "eqsl"
# MQSL = "mqsl"
# LOTW = "lotw"
# BORN = "born"
# USER_MGR = "user"
# IOTA = "iota"
# GEOLOC = "geoloc"
. Output only the next line. | mode = const.CW |
Here is a snippet: <|code_start|>
if sys.version_info.major == 3:
unicode = str
test_dir = os.path.dirname(os.path.abspath(__file__))
fix_dir = os.path.join(test_dir, 'fixtures')
class Test_eqsl_methods:
def test_check_content_with_mocked_http_server(self, httpserver):
httpserver.serve_content(open(os.path.join(fix_dir, 'eqsl_data.html'), 'rb').read(), headers={'content-type': 'text/plain; charset=ISO-8859-1'})
namespace = {}
execfile(os.path.join(fix_dir,"eqsl_data.py"), namespace)
<|code_end|>
. Write the next line using the current file imports:
from past.builtins import execfile
from pyhamtools.qsl import get_eqsl_users
import os
import sys
import datetime
import pytest
and context from other files:
# Path: pyhamtools/qsl.py
# def get_eqsl_users(**kwargs):
# """Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_.
#
# Args:
# url (str, optional): Download URL
#
# Returns:
# list: List containing the callsigns of EQSL users (unicode)
#
# Raises:
# IOError: When network is unavailable, file can't be downloaded or processed
#
# Example:
# The following example downloads the EQSL user list and checks if DH1TW is a user:
#
# >>> from pyhamtools.qsl import get_eqsl_users
# >>> mylist = get_eqsl_users()
# >>> try:
# >>> mylist.index('DH1TW')
# >>> except ValueError as e:
# >>> print e
# 'DH1TW' is not in list
#
# .. _here: http://www.eqsl.cc/QSLCard/DownloadedFiles/AGMemberlist.txt
#
# """
#
# url = ""
#
# eqsl = []
#
# try:
# url = kwargs['url']
# except KeyError:
# url = "http://www.eqsl.cc/QSLCard/DownloadedFiles/AGMemberlist.txt"
#
# try:
# result = requests.get(url)
# except (ConnectionError, HTTPError, Timeout) as e:
# raise IOError(e)
#
# if result.status_code == requests.codes.ok:
# eqsl = re.sub("^List.+UTC", "", result.text)
# eqsl = eqsl.upper().split()
# else:
# raise IOError("HTTP Error: " + str(result.status_code))
#
# return eqsl
, which may include functions, classes, or code. Output only the next line. | assert get_eqsl_users(url=httpserver.url) == namespace['eqsl_fixture'] |
Continue the code snippet: <|code_start|>
if sys.version_info.major == 3:
unicode = str
test_dir = os.path.dirname(os.path.abspath(__file__))
fix_dir = os.path.join(test_dir, 'fixtures')
class Test_clublog_methods:
def test_check_content_with_mocked_http_server(self, httpserver):
httpserver.serve_content(
open(os.path.join(fix_dir, 'clublog-users.json.zip'), 'rb').read())
<|code_end|>
. Use current file imports:
import os
import sys
import datetime
import pytest
from future.utils import iteritems
from pyhamtools.qsl import get_clublog_users
and context (classes, functions, or code) from other files:
# Path: pyhamtools/qsl.py
# def get_clublog_users(**kwargs):
# """Download the latest offical list of `Clublog`__ users.
#
# Args:
# url (str, optional): Download URL
#
# Returns:
# dict: Dictionary containing (if data available) the fields:
# firstqso, lastqso, last-lotw, lastupload (datetime),
# locator (string) and oqrs (boolean)
#
# Raises:
# IOError: When network is unavailable, file can't be downloaded or processed
#
# Example:
# The following example downloads the Clublog user list and returns a dictionary with the data of HC2/AL1O:
#
# >>> from pyhamtools.qsl import get_clublog_users
# >>> clublog = get_lotw_users()
# >>> clublog['HC2/AL1O']
# {'firstqso': datetime.datetime(2012, 1, 1, 19, 59, 27),
# 'last-lotw': datetime.datetime(2013, 5, 9, 1, 56, 23),
# 'lastqso': datetime.datetime(2013, 5, 5, 6, 39, 3),
# 'lastupload': datetime.datetime(2013, 5, 8, 15, 0, 6),
# 'oqrs': True}
#
# .. _CLUBLOG: https://secure.clublog.org
# __ CLUBLOG_
#
# """
#
# url = ""
#
# clublog = {}
#
# try:
# url = kwargs['url']
# except KeyError:
# url = "https://secure.clublog.org/clublog-users.json.zip"
#
# try:
# result = requests.get(url)
# except (ConnectionError, HTTPError, Timeout) as e:
# raise IOError(e)
#
#
# if result.status_code != requests.codes.ok:
# raise IOError("HTTP Error: " + str(result.status_code))
#
# zip_file = zipfile.ZipFile(BytesIO(result.content))
# files = zip_file.namelist()
# cl_json_unzipped = zip_file.read(files[0]).decode('utf8').replace("'", '"')
#
# cl_data = json.loads(cl_json_unzipped)
#
# error_count = 0
#
# for call, call_data in iteritems(cl_data):
# try:
# data = {}
# if "firstqso" in call_data:
# if call_data["firstqso"] != None:
# data["firstqso"] = datetime.strptime(call_data["firstqso"], '%Y-%m-%d %H:%M:%S')
# if "lastqso" in call_data:
# if call_data["lastqso"] != None:
# data["lastqso"] = datetime.strptime(call_data["lastqso"], '%Y-%m-%d %H:%M:%S')
# if "last-lotw" in call_data:
# if call_data["last-lotw"] != None:
# data["last-lotw"] = datetime.strptime(call_data["last-lotw"], '%Y-%m-%d %H:%M:%S')
# if "lastupload" in call_data:
# if call_data["lastupload"] != None:
# data["lastupload"] = datetime.strptime(call_data["lastupload"], '%Y-%m-%d %H:%M:%S')
# if "locator" in call_data:
# if call_data["locator"] != None:
# data["locator"] = call_data["locator"]
# if "oqrs" in call_data:
# if call_data["oqrs"] != None:
# data["oqrs"] = call_data["oqrs"]
# clublog[call] = data
# except TypeError: #some date fields contain null instead of a valid datetime string - we ignore them
# print("Ignoring invalid type in data:", call, call_data)
# pass
# except ValueError: #some date fiels are invalid. we ignore them for the moment
# print("Ignoring invalid data:", call, call_data)
# pass
#
# return clublog
. Output only the next line. | data = get_clublog_users(url=httpserver.url) |
Predict the next line after this snippet: <|code_start|> dict: Dictionary containing the band (int) and mode (str)
Raises:
KeyError: Wrong frequency or out of band
Example:
The following example converts the frequency *14005.3 kHz* into band and mode.
>>> from pyhamtools.utils import freq_to_band
>>> print freq_to_band(14005.3)
{
'band': 20,
'mode': CW
}
Note:
Modes are:
- CW
- USB
- LSB
- DIGITAL
"""
band = None
mode = None
if ((freq >= 135) and (freq <= 138)):
band = 2190
<|code_end|>
using the current file's imports:
from pyhamtools.consts import LookupConventions as const
and any relevant context from other files:
# Path: pyhamtools/consts.py
# class LookupConventions:
# """ This class defines the constants used within the pyhamtools package """
#
# # Mostly specific to Clublog XML File
# CALLSIGN = u"callsign"
# COUNTRY = u"country"
# PREFIX = u"prefix"
# ADIF = u"adif"
# CQZ = u"cqz"
# ITUZ = u"ituz"
# CONTINENT = u"continent"
# LATITUDE = u"latitude"
# LONGITUDE = u"longitude"
# START = u"start"
# END = u"end"
# WHITELIST = u"whitelist"
# WHITELIST_START = u"whitelist_start"
# WHITELIST_END = u"whitelist_end"
# DELETED = u"deleted"
# MARITIME_MOBILE = u"mm"
# AIRCRAFT_MOBILE = u"am"
# LOCATOR = u"locator"
# BEACON = u"beacon"
#
# #CQ / DIGITAL Skimmer specific
#
# SKIMMER = u"skimmer"
# FS = u"fs" #fieldstrength
# WPM = u"wpm" #words / bytes per second
# CQ = u"cq"
# NCDXF = u"ncdxf"
#
#
# # Modes
# CW = u"CW"
# USB = u"USB"
# LSB = u"LSB"
# DIGITAL = u"DIGITAL"
# FM = u"FM"
# # FT8 = u'FT8'
#
# #DX Spot
# SPOTTER = u"spotter"
# DX = u"dx"
# FREQUENCY = u"frequency"
# COMMENT = u"comment"
# TIME = u"time"
# BAND = u"band"
# MODE = u"mode"
#
# #DX Spider specific
# ORIGIN_NODE = u"node"
# HOPS = u"hops"
# RAW_SPOT = u"raw"
# IP = u"ip"
# ROUTE = u"route"
# TEXT = u"text"
# SYSOP_FLAG = u"sysop_flag"
# WX_FLAG = u"wx_flag"
#
# #WWV & WCY
# STATION = u"station"
# R = u"r"
# K = u"k"
# EXPK = u"expk"
# SFI = u"sfi"
# A = u"a"
# AURORA = u"aurora"
# SA = u"sa"
# GMF = u"gmf"
# FORECAST = u"forecast"
#
# #QRZ.com
# XREF = u"xref"
# ALIASES = u"aliases"
# FNAME = u"fname"
# NAME = u"name"
# ADDR1 = u"addr1"
# ADDR2 = u"addr2"
# STATE = u"state"
# ZIPCODE = u"zipcode"
# CCODE = u"ccode"
# COUNTY = u"county"
# FIPS = u"fips"
# LAND = u"land"
# EFDATE = u"efdate"
# EXPDATE = u"expdate"
# P_CALL = u"p_call"
# LICENSE_CLASS = u"license_class"
# CODES = u"codes"
# QSLMGR = u"qslmgr"
# EMAIL = u"email"
# URL = u"url"
# U_VIEWS = u"u_views"
# BIO = u"bio"
# BIODATE = u"biodate"
# IMAGE = u"image"
# IMAGE_INFO = u"imageinfo"
# SERIAL = u"serial"
# MODDATE = u"moddate"
# MSA = "msa"
# AREACODE = "areacode"
# TIMEZONE = "timezone"
# GMTOFFSET = "gmtoffset"
# DST = "dst"
# EQSL = "eqsl"
# MQSL = "mqsl"
# LOTW = "lotw"
# BORN = "born"
# USER_MGR = "user"
# IOTA = "iota"
# GEOLOC = "geoloc"
. Output only the next line. | mode = const.CW |
Here is a snippet: <|code_start|> self._logger.debug("appendix: " + appendix)
if appendix == 'MM': # special case Martime Mobile
#self._mm = True
return {
'adif': 999,
'continent': '',
'country': 'MARITIME MOBILE',
'cqz': 0,
'latitude': 0.0,
'longitude': 0.0
}
elif appendix == 'AM': # special case Aeronautic Mobile
return {
'adif': 998,
'continent': '',
'country': 'AIRCAFT MOBILE',
'cqz': 0,
'latitude': 0.0,
'longitude': 0.0
}
elif appendix == 'QRP': # special case QRP
callsign = re.sub('/QRP', '', callsign)
return self._iterate_prefix(callsign, timestamp)
elif appendix == 'QRPP': # special case QRPP
callsign = re.sub('/QRPP', '', callsign)
return self._iterate_prefix(callsign, timestamp)
elif appendix == 'BCN': # filter all beacons
callsign = re.sub('/BCN', '', callsign)
data = self._iterate_prefix(callsign, timestamp).copy()
<|code_end|>
. Write the next line using the current file imports:
import re
import logging
import sys
import pytz
from datetime import datetime
from pyhamtools.consts import LookupConventions as const
from pyhamtools.callsign_exceptions import callsign_exceptions
and context from other files:
# Path: pyhamtools/consts.py
# class LookupConventions:
# """ This class defines the constants used within the pyhamtools package """
#
# # Mostly specific to Clublog XML File
# CALLSIGN = u"callsign"
# COUNTRY = u"country"
# PREFIX = u"prefix"
# ADIF = u"adif"
# CQZ = u"cqz"
# ITUZ = u"ituz"
# CONTINENT = u"continent"
# LATITUDE = u"latitude"
# LONGITUDE = u"longitude"
# START = u"start"
# END = u"end"
# WHITELIST = u"whitelist"
# WHITELIST_START = u"whitelist_start"
# WHITELIST_END = u"whitelist_end"
# DELETED = u"deleted"
# MARITIME_MOBILE = u"mm"
# AIRCRAFT_MOBILE = u"am"
# LOCATOR = u"locator"
# BEACON = u"beacon"
#
# #CQ / DIGITAL Skimmer specific
#
# SKIMMER = u"skimmer"
# FS = u"fs" #fieldstrength
# WPM = u"wpm" #words / bytes per second
# CQ = u"cq"
# NCDXF = u"ncdxf"
#
#
# # Modes
# CW = u"CW"
# USB = u"USB"
# LSB = u"LSB"
# DIGITAL = u"DIGITAL"
# FM = u"FM"
# # FT8 = u'FT8'
#
# #DX Spot
# SPOTTER = u"spotter"
# DX = u"dx"
# FREQUENCY = u"frequency"
# COMMENT = u"comment"
# TIME = u"time"
# BAND = u"band"
# MODE = u"mode"
#
# #DX Spider specific
# ORIGIN_NODE = u"node"
# HOPS = u"hops"
# RAW_SPOT = u"raw"
# IP = u"ip"
# ROUTE = u"route"
# TEXT = u"text"
# SYSOP_FLAG = u"sysop_flag"
# WX_FLAG = u"wx_flag"
#
# #WWV & WCY
# STATION = u"station"
# R = u"r"
# K = u"k"
# EXPK = u"expk"
# SFI = u"sfi"
# A = u"a"
# AURORA = u"aurora"
# SA = u"sa"
# GMF = u"gmf"
# FORECAST = u"forecast"
#
# #QRZ.com
# XREF = u"xref"
# ALIASES = u"aliases"
# FNAME = u"fname"
# NAME = u"name"
# ADDR1 = u"addr1"
# ADDR2 = u"addr2"
# STATE = u"state"
# ZIPCODE = u"zipcode"
# CCODE = u"ccode"
# COUNTY = u"county"
# FIPS = u"fips"
# LAND = u"land"
# EFDATE = u"efdate"
# EXPDATE = u"expdate"
# P_CALL = u"p_call"
# LICENSE_CLASS = u"license_class"
# CODES = u"codes"
# QSLMGR = u"qslmgr"
# EMAIL = u"email"
# URL = u"url"
# U_VIEWS = u"u_views"
# BIO = u"bio"
# BIODATE = u"biodate"
# IMAGE = u"image"
# IMAGE_INFO = u"imageinfo"
# SERIAL = u"serial"
# MODDATE = u"moddate"
# MSA = "msa"
# AREACODE = "areacode"
# TIMEZONE = "timezone"
# GMTOFFSET = "gmtoffset"
# DST = "dst"
# EQSL = "eqsl"
# MQSL = "mqsl"
# LOTW = "lotw"
# BORN = "born"
# USER_MGR = "user"
# IOTA = "iota"
# GEOLOC = "geoloc"
#
# Path: pyhamtools/callsign_exceptions.py
, which may include functions, classes, or code. Output only the next line. | data[const.BEACON] = True |
Next line prediction: <|code_start|> data = self._iterate_prefix(callsign, timestamp).copy()
data[const.BEACON] = True
return data
elif re.search('\d$', appendix):
area_nr = re.search('\d$', appendix).group(0)
callsign = re.sub('/\d$', '', callsign) #remove /number
if len(re.findall(r'\d+', callsign)) == 1: #call has just on digit e.g. DH1TW
callsign = re.sub('[\d]+', area_nr, callsign)
else: # call has several digits e.g. 7N4AAL
pass # no (two) digit prefix contries known where appendix would change entitiy
return self._iterate_prefix(callsign, timestamp)
else:
return self._iterate_prefix(callsign, timestamp)
# regular callsigns, without prefix or appendix
elif re.match('^[\d]{0,1}[A-Z]{1,2}\d([A-Z]{1,4}|\d{3,3}|\d{1,3}[A-Z])[A-Z]{0,5}$', callsign):
return self._iterate_prefix(callsign, timestamp)
# callsigns with prefixes (xxx/callsign)
elif re.search('^[A-Z0-9]{1,4}/', entire_callsign):
pfx = re.search('^[A-Z0-9]{1,4}/', entire_callsign)
pfx = re.sub('/', '', pfx.group(0))
#make sure that the remaining part is actually a callsign (avoid: OZ/JO81)
rest = re.search('/[A-Z0-9]+', entire_callsign)
rest = re.sub('/', '', rest.group(0))
if re.match('^[\d]{0,1}[A-Z]{1,2}\d([A-Z]{1,4}|\d{3,3}|\d{1,3}[A-Z])[A-Z]{0,5}$', rest):
return self._iterate_prefix(pfx)
<|code_end|>
. Use current file imports:
(import re
import logging
import sys
import pytz
from datetime import datetime
from pyhamtools.consts import LookupConventions as const
from pyhamtools.callsign_exceptions import callsign_exceptions)
and context including class names, function names, or small code snippets from other files:
# Path: pyhamtools/consts.py
# class LookupConventions:
# """ This class defines the constants used within the pyhamtools package """
#
# # Mostly specific to Clublog XML File
# CALLSIGN = u"callsign"
# COUNTRY = u"country"
# PREFIX = u"prefix"
# ADIF = u"adif"
# CQZ = u"cqz"
# ITUZ = u"ituz"
# CONTINENT = u"continent"
# LATITUDE = u"latitude"
# LONGITUDE = u"longitude"
# START = u"start"
# END = u"end"
# WHITELIST = u"whitelist"
# WHITELIST_START = u"whitelist_start"
# WHITELIST_END = u"whitelist_end"
# DELETED = u"deleted"
# MARITIME_MOBILE = u"mm"
# AIRCRAFT_MOBILE = u"am"
# LOCATOR = u"locator"
# BEACON = u"beacon"
#
# #CQ / DIGITAL Skimmer specific
#
# SKIMMER = u"skimmer"
# FS = u"fs" #fieldstrength
# WPM = u"wpm" #words / bytes per second
# CQ = u"cq"
# NCDXF = u"ncdxf"
#
#
# # Modes
# CW = u"CW"
# USB = u"USB"
# LSB = u"LSB"
# DIGITAL = u"DIGITAL"
# FM = u"FM"
# # FT8 = u'FT8'
#
# #DX Spot
# SPOTTER = u"spotter"
# DX = u"dx"
# FREQUENCY = u"frequency"
# COMMENT = u"comment"
# TIME = u"time"
# BAND = u"band"
# MODE = u"mode"
#
# #DX Spider specific
# ORIGIN_NODE = u"node"
# HOPS = u"hops"
# RAW_SPOT = u"raw"
# IP = u"ip"
# ROUTE = u"route"
# TEXT = u"text"
# SYSOP_FLAG = u"sysop_flag"
# WX_FLAG = u"wx_flag"
#
# #WWV & WCY
# STATION = u"station"
# R = u"r"
# K = u"k"
# EXPK = u"expk"
# SFI = u"sfi"
# A = u"a"
# AURORA = u"aurora"
# SA = u"sa"
# GMF = u"gmf"
# FORECAST = u"forecast"
#
# #QRZ.com
# XREF = u"xref"
# ALIASES = u"aliases"
# FNAME = u"fname"
# NAME = u"name"
# ADDR1 = u"addr1"
# ADDR2 = u"addr2"
# STATE = u"state"
# ZIPCODE = u"zipcode"
# CCODE = u"ccode"
# COUNTY = u"county"
# FIPS = u"fips"
# LAND = u"land"
# EFDATE = u"efdate"
# EXPDATE = u"expdate"
# P_CALL = u"p_call"
# LICENSE_CLASS = u"license_class"
# CODES = u"codes"
# QSLMGR = u"qslmgr"
# EMAIL = u"email"
# URL = u"url"
# U_VIEWS = u"u_views"
# BIO = u"bio"
# BIODATE = u"biodate"
# IMAGE = u"image"
# IMAGE_INFO = u"imageinfo"
# SERIAL = u"serial"
# MODDATE = u"moddate"
# MSA = "msa"
# AREACODE = "areacode"
# TIMEZONE = "timezone"
# GMTOFFSET = "gmtoffset"
# DST = "dst"
# EQSL = "eqsl"
# MQSL = "mqsl"
# LOTW = "lotw"
# BORN = "born"
# USER_MGR = "user"
# IOTA = "iota"
# GEOLOC = "geoloc"
#
# Path: pyhamtools/callsign_exceptions.py
. Output only the next line. | if entire_callsign in callsign_exceptions: |
Given snippet: <|code_start|>__author__ = 'dh1tw'
UTC = pytz.UTC
def decode_char_spot(raw_string):
"""Chop Line from DX-Cluster into pieces and return a dict with the spot data"""
data = {}
# Spotter callsign
if re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import datetime
from time import strptime, mktime
from pyhamtools.consts import LookupConventions as const
import re
import pytz
and context:
# Path: pyhamtools/consts.py
# class LookupConventions:
# """ This class defines the constants used within the pyhamtools package """
#
# # Mostly specific to Clublog XML File
# CALLSIGN = u"callsign"
# COUNTRY = u"country"
# PREFIX = u"prefix"
# ADIF = u"adif"
# CQZ = u"cqz"
# ITUZ = u"ituz"
# CONTINENT = u"continent"
# LATITUDE = u"latitude"
# LONGITUDE = u"longitude"
# START = u"start"
# END = u"end"
# WHITELIST = u"whitelist"
# WHITELIST_START = u"whitelist_start"
# WHITELIST_END = u"whitelist_end"
# DELETED = u"deleted"
# MARITIME_MOBILE = u"mm"
# AIRCRAFT_MOBILE = u"am"
# LOCATOR = u"locator"
# BEACON = u"beacon"
#
# #CQ / DIGITAL Skimmer specific
#
# SKIMMER = u"skimmer"
# FS = u"fs" #fieldstrength
# WPM = u"wpm" #words / bytes per second
# CQ = u"cq"
# NCDXF = u"ncdxf"
#
#
# # Modes
# CW = u"CW"
# USB = u"USB"
# LSB = u"LSB"
# DIGITAL = u"DIGITAL"
# FM = u"FM"
# # FT8 = u'FT8'
#
# #DX Spot
# SPOTTER = u"spotter"
# DX = u"dx"
# FREQUENCY = u"frequency"
# COMMENT = u"comment"
# TIME = u"time"
# BAND = u"band"
# MODE = u"mode"
#
# #DX Spider specific
# ORIGIN_NODE = u"node"
# HOPS = u"hops"
# RAW_SPOT = u"raw"
# IP = u"ip"
# ROUTE = u"route"
# TEXT = u"text"
# SYSOP_FLAG = u"sysop_flag"
# WX_FLAG = u"wx_flag"
#
# #WWV & WCY
# STATION = u"station"
# R = u"r"
# K = u"k"
# EXPK = u"expk"
# SFI = u"sfi"
# A = u"a"
# AURORA = u"aurora"
# SA = u"sa"
# GMF = u"gmf"
# FORECAST = u"forecast"
#
# #QRZ.com
# XREF = u"xref"
# ALIASES = u"aliases"
# FNAME = u"fname"
# NAME = u"name"
# ADDR1 = u"addr1"
# ADDR2 = u"addr2"
# STATE = u"state"
# ZIPCODE = u"zipcode"
# CCODE = u"ccode"
# COUNTY = u"county"
# FIPS = u"fips"
# LAND = u"land"
# EFDATE = u"efdate"
# EXPDATE = u"expdate"
# P_CALL = u"p_call"
# LICENSE_CLASS = u"license_class"
# CODES = u"codes"
# QSLMGR = u"qslmgr"
# EMAIL = u"email"
# URL = u"url"
# U_VIEWS = u"u_views"
# BIO = u"bio"
# BIODATE = u"biodate"
# IMAGE = u"image"
# IMAGE_INFO = u"imageinfo"
# SERIAL = u"serial"
# MODDATE = u"moddate"
# MSA = "msa"
# AREACODE = "areacode"
# TIMEZONE = "timezone"
# GMTOFFSET = "gmtoffset"
# DST = "dst"
# EQSL = "eqsl"
# MQSL = "mqsl"
# LOTW = "lotw"
# BORN = "born"
# USER_MGR = "user"
# IOTA = "iota"
# GEOLOC = "geoloc"
which might include code, classes, or functions. Output only the next line. | data[const.SPOTTER] = re.sub(':', '', re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]).group(0)) |
Next line prediction: <|code_start|> # step counter for how many pages we have hit
step = 0
if 'step' in response.meta:
step = response.meta['step']
# Create Item to send to kafka
# capture raw response
item = RawResponseItem()
# populated from response.meta
item['appid'] = response.meta['appid']
item['crawlid'] = response.meta['crawlid']
item['attrs'] = response.meta['attrs']
# populated from raw HTTP response
item["url"] = response.request.url
item["response_url"] = response.url
item["status_code"] = response.status
item["status_msg"] = "OK"
item["response_headers"] = self.reconstruct_headers(response)
item["request_headers"] = response.request.headers
item["body"] = response.body
item["links"] = []
# we want to know how far our spider gets
if item['attrs'] is None:
item['attrs'] = {}
item['attrs']['step'] = step
self._logger.debug("Finished creating item")
# determine what link we want to crawl
<|code_end|>
. Use current file imports:
(import scrapy
import random
from scrapy.http import Request
from .lxmlhtml import CustomLxmlLinkExtractor as LinkExtractor
from scrapy.conf import settings
from crawling.items import RawResponseItem
from .redis_spider import RedisSpider)
and context including class names, function names, or small code snippets from other files:
# Path: crawler/crawling/spiders/lxmlhtml.py
# class CustomLxmlLinkExtractor(LxmlLinkExtractor):
# def __init__(self, allow=(), deny=(), allow_domains=(), deny_domains=(),
# restrict_xpaths=(),
# tags=('a', 'area'), attrs=('href',), canonicalize=True,
# unique=True, process_value=None, deny_extensions=None,
# restrict_css=()):
# super(CustomLxmlLinkExtractor, self).__init__(allow=allow, deny=deny,
# allow_domains=allow_domains, deny_domains=deny_domains,
# restrict_xpaths=restrict_xpaths, restrict_css=restrict_css,
# canonicalize=canonicalize, deny_extensions=deny_extensions)
# tag_func = lambda x: x in tags
# attr_func = lambda x: x in attrs
#
# # custom parser override
# cp = CustomParser(tag=tag_func, attr=attr_func,
# unique=unique, process=process_value)
# self.link_extractor = cp
#
# Path: crawler/crawling/spiders/redis_spider.py
# class RedisSpider(Spider):
# '''
# Base Spider for doing distributed crawls coordinated through Redis
# '''
#
# def _set_crawler(self, crawler):
# super(RedisSpider, self)._set_crawler(crawler)
# self.crawler.signals.connect(self.spider_idle,
# signal=signals.spider_idle)
#
# def spider_idle(self):
# raise DontCloseSpider
#
# def parse(self, response):
# '''
# Parse a page of html, and yield items into the item pipeline
#
# @param response: The response object of the scrape
# '''
# raise NotImplementedError("Please implement parse() for your spider")
#
# def set_logger(self, logger):
# '''
# Set the logger for the spider, different than the default Scrapy one
#
# @param logger: the logger from the scheduler
# '''
# self._logger = logger
#
# def reconstruct_headers(self, response):
# """
# Purpose of this method is to reconstruct the headers dictionary that
# is normally passed in with a "response" object from scrapy.
#
# Args:
# response: A scrapy response object
#
# Returns: A dictionary that mirrors the "response.headers" dictionary
# that is normally within a response object
#
# Raises: None
# Reason: Originally, there was a bug where the json.dumps() did not
# properly serialize the headers. This method is a way to circumvent
# the known issue
# """
#
# header_dict = {}
# # begin reconstructing headers from scratch...
# for key in list(response.headers.keys()):
# key_item_list = []
# key_list = response.headers.getlist(key)
# for item in key_list:
# key_item_list.append(item)
# header_dict[key] = key_item_list
# return header_dict
. Output only the next line. | link_extractor = LinkExtractor( |
Using the snippet: <|code_start|>
rpy2.rinterface_lib.callbacks.logger.setLevel(logging.ERROR) # Ignore R warning messages
# Main LISI
def lisi(
adata,
batch_key,
label_key,
k0=90,
type_=None,
scale=True,
verbose=False
):
"""
Compute lisi score (after integration)
params:
matrix: matrix from adata to calculate on
covariate_key: variable to compute iLISI on
cluster_key: variable to compute cLISI on
return:
pd.DataFrame with median cLISI and median iLISI scores (following the harmony paper)
"""
<|code_end|>
, determine the next line of code. You have imports:
import itertools
import logging
import multiprocessing as mp
import os
import pathlib
import subprocess
import tempfile
import anndata2ri
import numpy as np
import pandas as pd
import rpy2.rinterface_lib.callbacks
import rpy2.robjects as ro
import scanpy as sc
import scipy.sparse
from scipy.io import mmwrite
from ..utils import check_adata, check_batch
and context (class names, function names, or code) available:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
. Output only the next line. | check_adata(adata) |
Next line prediction: <|code_start|>
rpy2.rinterface_lib.callbacks.logger.setLevel(logging.ERROR) # Ignore R warning messages
# Main LISI
def lisi(
adata,
batch_key,
label_key,
k0=90,
type_=None,
scale=True,
verbose=False
):
"""
Compute lisi score (after integration)
params:
matrix: matrix from adata to calculate on
covariate_key: variable to compute iLISI on
cluster_key: variable to compute cLISI on
return:
pd.DataFrame with median cLISI and median iLISI scores (following the harmony paper)
"""
check_adata(adata)
<|code_end|>
. Use current file imports:
(import itertools
import logging
import multiprocessing as mp
import os
import pathlib
import subprocess
import tempfile
import anndata2ri
import numpy as np
import pandas as pd
import rpy2.rinterface_lib.callbacks
import rpy2.robjects as ro
import scanpy as sc
import scipy.sparse
from scipy.io import mmwrite
from ..utils import check_adata, check_batch)
and context including class names, function names, or small code snippets from other files:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
. Output only the next line. | check_batch(batch_key, adata.obs) |
Based on the snippet: <|code_start|>
def opt_louvain(adata, label_key, cluster_key, function=None, resolutions=None,
use_rep=None,
inplace=True, plot=False, force=True, verbose=True, **kwargs):
"""
params:
label_key: name of column in adata.obs containing biological labels to be
optimised against
cluster_key: name of column to be added to adata.obs during clustering.
Will be overwritten if exists and `force=True`
function: function that computes the cost to be optimised over. Must take as
arguments (adata, group1, group2, **kwargs) and returns a number for maximising
resolutions: list if resolutions to be optimised over. If `resolutions=None`,
default resolutions of 20 values ranging between 0.1 and 2 will be used
use_rep: key of embedding to use only if adata.uns['neighbors'] is not defined,
otherwise will be ignored
returns:
res_max: resolution of maximum score
score_max: maximum score
score_all: `pd.DataFrame` containing all scores at resolutions. Can be used to plot the score profile.
clustering: only if `inplace=False`, return cluster assignment as `pd.Series`
plot: if `plot=True` plot the score profile over resolution
"""
if verbose:
print('Clustering...')
if function is None:
<|code_end|>
, predict the immediate next line with the help of imports:
import matplotlib.pyplot as plt
import pandas as pd
import scanpy as sc
import seaborn as sns
from .nmi import nmi
and context (classes, functions, sometimes code) from other files:
# Path: scib/metrics/nmi.py
# def nmi(adata, group1, group2, method="arithmetic", nmi_dir=None):
# """
# Wrapper for normalized mutual information NMI between two different cluster assignments
#
# :param adata: Anndata object
# :param group1: column name of `adata.obs`
# :param group2: column name of `adata.obs`
# :param method: NMI implementation
# 'max': scikit method with `average_method='max'`
# 'min': scikit method with `average_method='min'`
# 'geometric': scikit method with `average_method='geometric'`
# 'arithmetic': scikit method with `average_method='arithmetic'`
# 'Lancichinetti': implementation by A. Lancichinetti 2009 et al. https://sites.google.com/site/andrealancichinetti/mutual
# 'ONMI': implementation by Aaron F. McDaid et al. https://github.com/aaronmcdaid/Overlapping-NMI
# :param nmi_dir: directory of compiled C code if 'Lancichinetti' or 'ONMI' are specified as `method`.
# These packages need to be compiled as specified in the corresponding READMEs.
# :return:
# Normalized mutual information NMI value
# """
#
# check_adata(adata)
# check_batch(group1, adata.obs)
# check_batch(group2, adata.obs)
#
# group1 = adata.obs[group1].tolist()
# group2 = adata.obs[group2].tolist()
#
# if len(group1) != len(group2):
# raise ValueError(
# f'different lengths in group1 ({len(group1)}) and group2 ({len(group2)})'
# )
#
# # choose method
# if method in ['max', 'min', 'geometric', 'arithmetic']:
# nmi_value = normalized_mutual_info_score(group1, group2, average_method=method)
# elif method == "Lancichinetti":
# nmi_value = nmi_Lanc(group1, group2, nmi_dir=nmi_dir)
# elif method == "ONMI":
# nmi_value = onmi(group1, group2, nmi_dir=nmi_dir)
# else:
# raise ValueError(f"Method {method} not valid")
#
# return nmi_value
. Output only the next line. | function = nmi |
Given the following code snippet before the placeholder: <|code_start|> :param isolated_label: value of specific isolated label e.g. cell type/identity annotation
:param embed: embedding to be passed to opt_louvain, if adata.uns['neighbors'] is missing
:param cluster: if True, compute clustering-based F1 score, otherwise compute
silhouette score on grouping of isolated label vs all other remaining labels
:param iso_label_key: name of key to use for cluster assignment for F1 score or
isolated-vs-rest assignment for silhouette score
:param verbose:
:return:
Isolated label score
"""
adata_tmp = adata.copy()
def max_f1(adata, label_key, cluster_key, label, argmax=False):
"""cluster optimizing over largest F1 score of isolated label"""
obs = adata.obs
max_cluster = None
max_f1 = 0
for cluster in obs[cluster_key].unique():
y_pred = obs[cluster_key] == cluster
y_true = obs[label_key] == label
f1 = f1_score(y_pred, y_true)
if f1 > max_f1:
max_f1 = f1
max_cluster = cluster
if argmax:
return max_cluster
return max_f1
if cluster:
# F1-score on clustering
<|code_end|>
, predict the next line using imports from the current file:
import pandas as pd
from sklearn.metrics import f1_score
from .clustering import opt_louvain
from .silhouette import silhouette
and context including class names, function names, and sometimes code from other files:
# Path: scib/metrics/clustering.py
# def opt_louvain(adata, label_key, cluster_key, function=None, resolutions=None,
# use_rep=None,
# inplace=True, plot=False, force=True, verbose=True, **kwargs):
# """
# params:
# label_key: name of column in adata.obs containing biological labels to be
# optimised against
# cluster_key: name of column to be added to adata.obs during clustering.
# Will be overwritten if exists and `force=True`
# function: function that computes the cost to be optimised over. Must take as
# arguments (adata, group1, group2, **kwargs) and returns a number for maximising
# resolutions: list if resolutions to be optimised over. If `resolutions=None`,
# default resolutions of 20 values ranging between 0.1 and 2 will be used
# use_rep: key of embedding to use only if adata.uns['neighbors'] is not defined,
# otherwise will be ignored
# returns:
# res_max: resolution of maximum score
# score_max: maximum score
# score_all: `pd.DataFrame` containing all scores at resolutions. Can be used to plot the score profile.
# clustering: only if `inplace=False`, return cluster assignment as `pd.Series`
# plot: if `plot=True` plot the score profile over resolution
# """
#
# if verbose:
# print('Clustering...')
#
# if function is None:
# function = nmi
#
# if cluster_key in adata.obs.columns:
# if force:
# print(f"Warning: cluster key {cluster_key} already exists "
# "in adata.obs and will be overwritten")
# else:
# raise ValueError(f"cluster key {cluster_key} already exists in " +
# "adata, please remove the key or choose a different name." +
# "If you want to force overwriting the key, specify `force=True`")
#
# if resolutions is None:
# n = 20
# resolutions = [2 * x / n for x in range(1, n + 1)]
#
# score_max = 0
# res_max = resolutions[0]
# clustering = None
# score_all = []
#
# try:
# adata.uns['neighbors']
# except KeyError:
# if verbose:
# print('computing neighbours for opt_cluster')
# sc.pp.neighbors(adata, use_rep=use_rep)
#
# for res in resolutions:
# sc.tl.louvain(adata, resolution=res, key_added=cluster_key)
# score = function(adata, label_key, cluster_key, **kwargs)
# if verbose:
# print(f'resolution: {res}, {function.__name__}: {score}')
# score_all.append(score)
# if score_max < score:
# score_max = score
# res_max = res
# clustering = adata.obs[cluster_key]
# del adata.obs[cluster_key]
#
# if verbose:
# print(f'optimised clustering against {label_key}')
# print(f'optimal cluster resolution: {res_max}')
# print(f'optimal score: {score_max}')
#
# score_all = pd.DataFrame(zip(resolutions, score_all), columns=('resolution', 'score'))
# if plot:
# # score vs. resolution profile
# sns.lineplot(data=score_all, x='resolution', y='score').set_title('Optimal cluster resolution profile')
# plt.show()
#
# if inplace:
# adata.obs[cluster_key] = clustering
# return res_max, score_max, score_all
# else:
# return res_max, score_max, score_all, clustering
#
# Path: scib/metrics/silhouette.py
# def silhouette(
# adata,
# group_key,
# embed,
# metric='euclidean',
# scale=True
# ):
# """
# Wrapper for sklearn silhouette function values range from [-1, 1] with
# 1 being an ideal fit
# 0 indicating overlapping clusters and
# -1 indicating misclassified cells
# By default, the score is scaled between 0 and 1. This is controlled `scale=True`
#
# :param group_key: key in adata.obs of cell labels
# :param embed: embedding key in adata.obsm, default: 'X_pca'
# :param scale: default True, scale between 0 (worst) and 1 (best)
# """
# if embed not in adata.obsm.keys():
# print(adata.obsm.keys())
# raise KeyError(f'{embed} not in obsm')
# asw = silhouette_score(
# X=adata.obsm[embed],
# labels=adata.obs[group_key],
# metric=metric
# )
# if scale:
# asw = (asw + 1) / 2
# return asw
. Output only the next line. | opt_louvain( |
Given snippet: <|code_start|> obs = adata.obs
max_cluster = None
max_f1 = 0
for cluster in obs[cluster_key].unique():
y_pred = obs[cluster_key] == cluster
y_true = obs[label_key] == label
f1 = f1_score(y_pred, y_true)
if f1 > max_f1:
max_f1 = f1
max_cluster = cluster
if argmax:
return max_cluster
return max_f1
if cluster:
# F1-score on clustering
opt_louvain(
adata_tmp,
label_key,
cluster_key=iso_label_key,
label=isolated_label,
use_rep=embed,
function=max_f1,
verbose=False,
inplace=True
)
score = max_f1(adata_tmp, label_key, iso_label_key, isolated_label, argmax=False)
else:
# AWS score between label
adata_tmp.obs[iso_label_key] = adata_tmp.obs[label_key] == isolated_label
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pandas as pd
from sklearn.metrics import f1_score
from .clustering import opt_louvain
from .silhouette import silhouette
and context:
# Path: scib/metrics/clustering.py
# def opt_louvain(adata, label_key, cluster_key, function=None, resolutions=None,
# use_rep=None,
# inplace=True, plot=False, force=True, verbose=True, **kwargs):
# """
# params:
# label_key: name of column in adata.obs containing biological labels to be
# optimised against
# cluster_key: name of column to be added to adata.obs during clustering.
# Will be overwritten if exists and `force=True`
# function: function that computes the cost to be optimised over. Must take as
# arguments (adata, group1, group2, **kwargs) and returns a number for maximising
# resolutions: list if resolutions to be optimised over. If `resolutions=None`,
# default resolutions of 20 values ranging between 0.1 and 2 will be used
# use_rep: key of embedding to use only if adata.uns['neighbors'] is not defined,
# otherwise will be ignored
# returns:
# res_max: resolution of maximum score
# score_max: maximum score
# score_all: `pd.DataFrame` containing all scores at resolutions. Can be used to plot the score profile.
# clustering: only if `inplace=False`, return cluster assignment as `pd.Series`
# plot: if `plot=True` plot the score profile over resolution
# """
#
# if verbose:
# print('Clustering...')
#
# if function is None:
# function = nmi
#
# if cluster_key in adata.obs.columns:
# if force:
# print(f"Warning: cluster key {cluster_key} already exists "
# "in adata.obs and will be overwritten")
# else:
# raise ValueError(f"cluster key {cluster_key} already exists in " +
# "adata, please remove the key or choose a different name." +
# "If you want to force overwriting the key, specify `force=True`")
#
# if resolutions is None:
# n = 20
# resolutions = [2 * x / n for x in range(1, n + 1)]
#
# score_max = 0
# res_max = resolutions[0]
# clustering = None
# score_all = []
#
# try:
# adata.uns['neighbors']
# except KeyError:
# if verbose:
# print('computing neighbours for opt_cluster')
# sc.pp.neighbors(adata, use_rep=use_rep)
#
# for res in resolutions:
# sc.tl.louvain(adata, resolution=res, key_added=cluster_key)
# score = function(adata, label_key, cluster_key, **kwargs)
# if verbose:
# print(f'resolution: {res}, {function.__name__}: {score}')
# score_all.append(score)
# if score_max < score:
# score_max = score
# res_max = res
# clustering = adata.obs[cluster_key]
# del adata.obs[cluster_key]
#
# if verbose:
# print(f'optimised clustering against {label_key}')
# print(f'optimal cluster resolution: {res_max}')
# print(f'optimal score: {score_max}')
#
# score_all = pd.DataFrame(zip(resolutions, score_all), columns=('resolution', 'score'))
# if plot:
# # score vs. resolution profile
# sns.lineplot(data=score_all, x='resolution', y='score').set_title('Optimal cluster resolution profile')
# plt.show()
#
# if inplace:
# adata.obs[cluster_key] = clustering
# return res_max, score_max, score_all
# else:
# return res_max, score_max, score_all, clustering
#
# Path: scib/metrics/silhouette.py
# def silhouette(
# adata,
# group_key,
# embed,
# metric='euclidean',
# scale=True
# ):
# """
# Wrapper for sklearn silhouette function values range from [-1, 1] with
# 1 being an ideal fit
# 0 indicating overlapping clusters and
# -1 indicating misclassified cells
# By default, the score is scaled between 0 and 1. This is controlled `scale=True`
#
# :param group_key: key in adata.obs of cell labels
# :param embed: embedding key in adata.obsm, default: 'X_pca'
# :param scale: default True, scale between 0 (worst) and 1 (best)
# """
# if embed not in adata.obsm.keys():
# print(adata.obsm.keys())
# raise KeyError(f'{embed} not in obsm')
# asw = silhouette_score(
# X=adata.obsm[embed],
# labels=adata.obs[group_key],
# metric=metric
# )
# if scale:
# asw = (asw + 1) / 2
# return asw
which might include code, classes, or functions. Output only the next line. | score = silhouette(adata_tmp, iso_label_key, embed) |
Using the snippet: <|code_start|>
def nmi(adata, group1, group2, method="arithmetic", nmi_dir=None):
"""
Wrapper for normalized mutual information NMI between two different cluster assignments
:param adata: Anndata object
:param group1: column name of `adata.obs`
:param group2: column name of `adata.obs`
:param method: NMI implementation
'max': scikit method with `average_method='max'`
'min': scikit method with `average_method='min'`
'geometric': scikit method with `average_method='geometric'`
'arithmetic': scikit method with `average_method='arithmetic'`
'Lancichinetti': implementation by A. Lancichinetti 2009 et al. https://sites.google.com/site/andrealancichinetti/mutual
'ONMI': implementation by Aaron F. McDaid et al. https://github.com/aaronmcdaid/Overlapping-NMI
:param nmi_dir: directory of compiled C code if 'Lancichinetti' or 'ONMI' are specified as `method`.
These packages need to be compiled as specified in the corresponding READMEs.
:return:
Normalized mutual information NMI value
"""
<|code_end|>
, determine the next line of code. You have imports:
import os
import subprocess
import tempfile
from sklearn.metrics.cluster import normalized_mutual_info_score
from ..utils import check_adata, check_batch
and context (class names, function names, or code) available:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
. Output only the next line. | check_adata(adata) |
Given the following code snippet before the placeholder: <|code_start|>
def nmi(adata, group1, group2, method="arithmetic", nmi_dir=None):
"""
Wrapper for normalized mutual information NMI between two different cluster assignments
:param adata: Anndata object
:param group1: column name of `adata.obs`
:param group2: column name of `adata.obs`
:param method: NMI implementation
'max': scikit method with `average_method='max'`
'min': scikit method with `average_method='min'`
'geometric': scikit method with `average_method='geometric'`
'arithmetic': scikit method with `average_method='arithmetic'`
'Lancichinetti': implementation by A. Lancichinetti 2009 et al. https://sites.google.com/site/andrealancichinetti/mutual
'ONMI': implementation by Aaron F. McDaid et al. https://github.com/aaronmcdaid/Overlapping-NMI
:param nmi_dir: directory of compiled C code if 'Lancichinetti' or 'ONMI' are specified as `method`.
These packages need to be compiled as specified in the corresponding READMEs.
:return:
Normalized mutual information NMI value
"""
check_adata(adata)
<|code_end|>
, predict the next line using imports from the current file:
import os
import subprocess
import tempfile
from sklearn.metrics.cluster import normalized_mutual_info_score
from ..utils import check_adata, check_batch
and context including class names, function names, and sometimes code from other files:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
. Output only the next line. | check_batch(group1, adata.obs) |
Based on the snippet: <|code_start|> :param adata_post: integrated adata
:param label_key: column in `adata_pre.obs` of the groups used to precompute the trajectory
:param pseudotime_key: column in `adata_pre.obs` in which the pseudotime is saved in.
Column can contain empty entries, the dataset will be subset to the cells with scores.
:param batch_key: set to batch key if if you want to compute the trajectory metric by batch
"""
# subset to cells for which pseudotime has been computed
cell_subset = adata_pre.obs.index[adata_pre.obs[pseudotime_key].notnull()]
adata_pre_ti = adata_pre[cell_subset]
adata_post_ti = adata_post[cell_subset]
try:
iroot, adata_post_ti2 = get_root(adata_pre_ti, adata_post_ti, label_key, pseudotime_key)
except RootCellError:
print('No root cell found, setting trajectory conservation metric to 0.')
return 0 # failure to find root cell means no TI conservation
adata_post_ti2.uns['iroot'] = iroot
sc.tl.dpt(adata_post_ti2) # stored in 'dpt_pseudotime'
adata_post_ti2.obs.loc[adata_post_ti2.obs['dpt_pseudotime'] > 1, 'dpt_pseudotime'] = 0
adata_post_ti.obs['dpt_pseudotime'] = 0
adata_post_ti.obs['dpt_pseudotime'] = adata_post_ti2.obs['dpt_pseudotime']
adata_post_ti.obs['dpt_pseudotime'].fillna(0, inplace=True)
if batch_key == None:
pseudotime_before = adata_pre_ti.obs[pseudotime_key]
pseudotime_after = adata_post_ti.obs['dpt_pseudotime']
correlation = pseudotime_before.corr(pseudotime_after, 'spearman')
return (correlation + 1) / 2 # scaled
else:
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import pandas as pd
import scanpy as sc
from scipy.sparse.csgraph import connected_components
from ..utils import check_batch
from .utils import RootCellError
and context (classes, functions, sometimes code) from other files:
# Path: scib/utils.py
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
#
# Path: scib/metrics/utils.py
# class RootCellError(Exception):
# def __init__(self, message):
# self.message = message
. Output only the next line. | check_batch(batch_key, adata_pre.obs) |
Using the snippet: <|code_start|> Column can contain empty entries, the dataset will be subset to the cells with scores.
:param dpt_dim: number of diffmap dimensions used to determine root
"""
n_components, adata_post.obs['neighborhood'] = connected_components(
csgraph=adata_post.obsp['connectivities'],
directed=False,
return_labels=True
)
start_clust = adata_pre.obs.groupby([ct_key]).mean()[pseudotime_key].idxmin()
min_dpt = adata_pre.obs[adata_pre.obs[ct_key] == start_clust].index
which_max_neigh = adata_post.obs['neighborhood'] == adata_post.obs['neighborhood'].value_counts().idxmax()
min_dpt = [value for value in min_dpt if value in adata_post.obs[which_max_neigh].index]
adata_post_ti = adata_post[which_max_neigh]
min_dpt = [adata_post_ti.obs_names.get_loc(i) for i in min_dpt]
# compute Diffmap for adata_post
sc.tl.diffmap(adata_post_ti)
# determine most extreme cell in adata_post Diffmap
min_dpt_cell = np.zeros(len(min_dpt))
for dim in np.arange(dpt_dim):
diffmap_mean = adata_post_ti.obsm["X_diffmap"][:, dim].mean()
diffmap_min_dpt = adata_post_ti.obsm["X_diffmap"][min_dpt, dim]
# count opt cell
if len(diffmap_min_dpt) == 0:
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import pandas as pd
import scanpy as sc
from scipy.sparse.csgraph import connected_components
from ..utils import check_batch
from .utils import RootCellError
and context (class names, function names, or code) available:
# Path: scib/utils.py
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
#
# Path: scib/metrics/utils.py
# class RootCellError(Exception):
# def __init__(self, message):
# self.message = message
. Output only the next line. | raise RootCellError('No root cell in largest component') |
Based on the snippet: <|code_start|> else:
return pcr_after - pcr_before
def pcr(
adata,
covariate,
embed=None,
n_comps=50,
recompute_pca=True,
verbose=False
):
"""
Principal component regression for anndata object
Checks whether to
+ compute PCA on embedding or expression data (set `embed` to name of embedding matrix e.g. `embed='X_emb'`)
+ use existing PCA (only if PCA entry exists)
+ recompute PCA on expression matrix (default)
:param adata: Anndata object
:param covariate: Key for adata.obs column to regress against
:param embed: Embedding to use for principal components.
If None, use the full expression matrix (`adata.X`), otherwise use the embedding
provided in `adata_post.obsm[embed]`.
:param n_comps: Number of PCs, if PCA is recomputed
:return:
R2Var of regression
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import pandas as pd
import scanpy as sc
from scipy import sparse
from sklearn.linear_model import LinearRegression
from ..utils import check_adata, check_batch
and context (classes, functions, sometimes code) from other files:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
. Output only the next line. | check_adata(adata) |
Predict the next line for this snippet: <|code_start|> return pcr_after - pcr_before
def pcr(
adata,
covariate,
embed=None,
n_comps=50,
recompute_pca=True,
verbose=False
):
"""
Principal component regression for anndata object
Checks whether to
+ compute PCA on embedding or expression data (set `embed` to name of embedding matrix e.g. `embed='X_emb'`)
+ use existing PCA (only if PCA entry exists)
+ recompute PCA on expression matrix (default)
:param adata: Anndata object
:param covariate: Key for adata.obs column to regress against
:param embed: Embedding to use for principal components.
If None, use the full expression matrix (`adata.X`), otherwise use the embedding
provided in `adata_post.obsm[embed]`.
:param n_comps: Number of PCs, if PCA is recomputed
:return:
R2Var of regression
"""
check_adata(adata)
<|code_end|>
with the help of current file imports:
import numpy as np
import pandas as pd
import scanpy as sc
from scipy import sparse
from sklearn.linear_model import LinearRegression
from ..utils import check_adata, check_batch
and context from other files:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
, which may contain function names, class names, or code. Output only the next line. | check_batch(covariate, adata.obs) |
Next line prediction: <|code_start|> :param verbose:
:return:
A score between 1 and 0. The larger the score, the stronger the cell cycle
variance is conserved.
"""
# subset adata objects
raw_sub = adata_pre[adata_pre.obs[batch_key] == batch]
int_sub = adata_post[adata_post.obs[batch_key] == batch].copy()
int_sub = int_sub.obsm[embed] if embed is not None else int_sub.X
# sanity check: subsets have same number of rows?
if raw_sub.shape[0] != int_sub.shape[0]:
raise ValueError(
f'batch "{batch}" of batch_key "{batch_key}" has unequal number of '
f'entries before and after integration.\n'
f'before: {raw_sub.shape[0]} after: {int_sub.shape[0]}'
)
# compute cc scores if necessary
if recompute_cc:
if verbose:
print("Score cell cycle...")
score_cell_cycle(raw_sub, organism=organism)
# regression variable
covariate = raw_sub.obs[['S_score', 'G2M_score']]
# PCR on adata before integration
if recompute_pcr:
<|code_end|>
. Use current file imports:
(import numpy as np
import pandas as pd
from ..preprocessing import score_cell_cycle
from ..utils import check_adata
from .pcr import pc_regression)
and context including class names, function names, or small code snippets from other files:
# Path: scib/preprocessing.py
# def score_cell_cycle(adata, organism='mouse'):
# """
# Tirosh et al. cell cycle marker genes downloaded from
# https://raw.githubusercontent.com/theislab/scanpy_usage/master/180209_cell_cycle/data/regev_lab_cell_cycle_genes.txt
# return: (s_genes, g2m_genes)
# s_genes: S-phase genes
# g2m_genes: G2- and M-phase genes
# """
# import pathlib
# root = pathlib.Path(__file__).parent
#
# cc_files = {'mouse': [root / 'resources/s_genes_tirosh.txt',
# root / 'resources/g2m_genes_tirosh.txt'],
# 'human': [root / 'resources/s_genes_tirosh_hm.txt',
# root / 'resources/g2m_genes_tirosh_hm.txt']}
#
# with open(cc_files[organism][0], "r") as f:
# s_genes = [x.strip() for x in f.readlines() if x.strip() in adata.var.index]
# with open(cc_files[organism][1], "r") as f:
# g2m_genes = [x.strip() for x in f.readlines() if x.strip() in adata.var.index]
#
# if (len(s_genes) == 0) or (len(g2m_genes) == 0):
# rand_choice = np.random.randint(1, adata.n_vars, 10)
# rand_genes = adata.var_names[rand_choice].tolist()
# raise ValueError(f"cell cycle genes not in adata\n organism: {organism}\n varnames: {rand_genes}")
#
# sc.tl.score_genes_cell_cycle(adata, s_genes, g2m_genes)
#
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# Path: scib/metrics/pcr.py
# def pc_regression(
# data,
# covariate,
# pca_var=None,
# n_comps=50,
# svd_solver='arpack',
# verbose=False
# ):
# """
# :params data: Expression or PC matrix. Assumed to be PC, if pca_sd is given.
# :param covariate: series or list of batch assignments
# :param n_comps: number of PCA components for computing PCA, only when pca_sd is not given.
# If no pca_sd is not defined and n_comps=None, compute PCA and don't reduce data
# :param pca_var: Iterable of variances for `n_comps` components.
# If `pca_sd` is not `None`, it is assumed that the matrix contains PC,
# otherwise PCA is computed on `data`.
# :param svd_solver:
# :param verbose:
# :return:
# R2Var of regression
# """
#
# if isinstance(data, (np.ndarray, sparse.csr_matrix, sparse.csc_matrix)):
# matrix = data
# else:
# raise TypeError(f'invalid type: {data.__class__} is not a numpy array or sparse matrix')
#
# # perform PCA if no variance contributions are given
# if pca_var is None:
#
# if n_comps is None or n_comps > min(matrix.shape):
# n_comps = min(matrix.shape)
#
# if n_comps == min(matrix.shape):
# svd_solver = 'full'
#
# if verbose:
# print("compute PCA")
# pca = sc.tl.pca(matrix, n_comps=n_comps, use_highly_variable=False,
# return_info=True, svd_solver=svd_solver, copy=True)
# X_pca = pca[0].copy()
# pca_var = pca[3].copy()
# del pca
# else:
# X_pca = matrix
# n_comps = matrix.shape[1]
#
# ## PC Regression
# if verbose:
# print("fit regression on PCs")
#
# # handle categorical values
# if pd.api.types.is_numeric_dtype(covariate):
# covariate = np.array(covariate).reshape(-1, 1)
# else:
# if verbose:
# print("one-hot encode categorical values")
# covariate = pd.get_dummies(covariate)
#
# # fit linear model for n_comps PCs
# r2 = []
# for i in range(n_comps):
# pc = X_pca[:, [i]]
# lm = LinearRegression()
# lm.fit(covariate, pc)
# r2_score = np.maximum(0, lm.score(covariate, pc))
# r2.append(r2_score)
#
# Var = pca_var / sum(pca_var) * 100
# R2Var = sum(r2 * Var) / 100
#
# return R2Var
. Output only the next line. | before = pc_regression( |
Next line prediction: <|code_start|>
def ari(adata, group1, group2, implementation=None):
""" Adjusted Rand Index
The function is symmetric, so group1 and group2 can be switched
For single cell integration evaluation the scenario is:
predicted cluster assignments vs. ground-truth (e.g. cell type) assignments
:param adata: anndata object
:param group1: string of column in adata.obs containing labels
:param group2: string of column in adata.obs containing labels
:params implementation: of set to 'sklearn', uses sklearns implementation,
otherwise native implementation is taken
"""
<|code_end|>
. Use current file imports:
(import numpy as np
import pandas as pd
import scipy.special
from sklearn.metrics.cluster import adjusted_rand_score
from ..utils import check_adata, check_batch)
and context including class names, function names, or small code snippets from other files:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
. Output only the next line. | check_adata(adata) |
Continue the code snippet: <|code_start|>
def ari(adata, group1, group2, implementation=None):
""" Adjusted Rand Index
The function is symmetric, so group1 and group2 can be switched
For single cell integration evaluation the scenario is:
predicted cluster assignments vs. ground-truth (e.g. cell type) assignments
:param adata: anndata object
:param group1: string of column in adata.obs containing labels
:param group2: string of column in adata.obs containing labels
:params implementation: of set to 'sklearn', uses sklearns implementation,
otherwise native implementation is taken
"""
check_adata(adata)
<|code_end|>
. Use current file imports:
import numpy as np
import pandas as pd
import scipy.special
from sklearn.metrics.cluster import adjusted_rand_score
from ..utils import check_adata, check_batch
and context (classes, functions, or code) from other files:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
. Output only the next line. | check_batch(group1, adata.obs) |
Predict the next line after this snippet: <|code_start|> score = np.nan
anndata2ri.deactivate()
return score
def kBET(
adata,
batch_key,
label_key,
scaled=True,
embed='X_pca',
type_=None,
return_df=False,
verbose=False
):
"""
:param adata: anndata object to compute kBET on
:param batch_key: name of batch column in adata.obs
:param label_key: name of cell identity labels column in adata.obs
:param scaled: whether to scale between 0 and 1
with 0 meaning low batch mixing and 1 meaning optimal batch mixing
if scaled=False, 0 means optimal batch mixing and 1 means low batch mixing
return:
kBET score (average of kBET per label) based on observed rejection rate
return_df=True: pd.DataFrame with kBET observed rejection rates per cluster for batch
"""
<|code_end|>
using the current file's imports:
import logging
import anndata2ri
import numpy as np
import pandas as pd
import rpy2.rinterface_lib.callbacks
import rpy2.robjects as ro
import scanpy as sc
import scipy.sparse
from ..utils import check_adata, check_batch
from .utils import NeighborsError, diffusion_conn, diffusion_nn
and any relevant context from other files:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
#
# Path: scib/metrics/utils.py
# class NeighborsError(Exception):
# def __init__(self, message):
# self.message = message
#
# def diffusion_conn(adata, min_k=50, copy=True, max_iterations=26):
# """
# Diffusion for connectivites matrix extension
# This function performs graph diffusion on the connectivities matrix until a
# minimum number `min_k` of entries per row are non-zero.
#
# Note:
# Due to self-loops min_k-1 non-zero connectivies entries is actually the stopping
# criterion. This is equivalent to `sc.pp.neighbors`.
#
# Returns:
# The diffusion-enhanced connectivities matrix of a copy of the AnnData object
# with the diffusion-enhanced connectivities matrix is in
# `adata.uns["neighbors"]["conectivities"]`
# """
# if 'neighbors' not in adata.uns:
# raise ValueError(
# '`neighbors` not in adata object. '
# 'Please compute a neighbourhood graph!'
# )
#
# if 'connectivities' not in adata.obsp:
# raise ValueError(
# '`connectivities` not in `adata.obsp`. '
# 'Please pass an object with connectivities computed!'
# )
#
# T = adata.obsp['connectivities']
#
# # Normalize T with max row sum
# # Note: This keeps the matrix symmetric and ensures |M| doesn't keep growing
# T = sparse.diags(1 / np.array([T.sum(1).max()] * T.shape[0])) * T
#
# M = T
#
# # Check for disconnected component
# n_comp, labs = sparse.csgraph.connected_components(adata.obsp['connectivities'],
# connection='strong')
#
# if n_comp > 1:
# tab = pd.value_counts(labs)
# small_comps = tab.index[tab < min_k]
# large_comp_mask = np.array(~pd.Series(labs).isin(small_comps))
# else:
# large_comp_mask = np.array([True] * M.shape[0])
#
# T_agg = T
# i = 2
# while ((M[large_comp_mask, :][:, large_comp_mask] > 0).sum(1).min() < min_k) and (i < max_iterations):
# print(f'Adding diffusion to step {i}')
# T_agg *= T
# M += T_agg
# i += 1
#
# if (M[large_comp_mask, :][:, large_comp_mask] > 0).sum(1).min() < min_k:
# raise ValueError(
# 'could not create diffusion connectivities matrix'
# f'with at least {min_k} non-zero entries in'
# f'{max_iterations} iterations.\n Please increase the'
# 'value of max_iterations or reduce k_min.\n'
# )
#
# M.setdiag(0)
#
# if copy:
# adata_tmp = adata.copy()
# adata_tmp.uns['neighbors'].update({'diffusion_connectivities': M})
# return adata_tmp
#
# else:
# return M
#
# def diffusion_nn(adata, k, max_iterations=26):
# """
# Diffusion neighbourhood score
# This function generates a nearest neighbour list from a connectivities matrix
# as supplied by BBKNN or Conos. This allows us to select a consistent number
# of nearest neighbours across all methods.
#
# Return:
# `k_indices` a numpy.ndarray of the indices of the k-nearest neighbors.
# """
# if 'neighbors' not in adata.uns:
# raise ValueError('`neighbors` not in adata object. '
# 'Please compute a neighbourhood graph!')
#
# if 'connectivities' not in adata.obsp:
# raise ValueError('`connectivities` not in `adata.obsp`. '
# 'Please pass an object with connectivities computed!')
#
# T = adata.obsp['connectivities']
#
# # Row-normalize T
# T = sparse.diags(1 / T.sum(1).A.ravel()) * T
#
# T_agg = T ** 3
# M = T + T ** 2 + T_agg
# i = 4
#
# while ((M > 0).sum(1).min() < (k + 1)) and (i < max_iterations):
# # note: k+1 is used as diag is non-zero (self-loops)
# print(f'Adding diffusion to step {i}')
# T_agg *= T
# M += T_agg
# i += 1
#
# if (M > 0).sum(1).min() < (k + 1):
# raise NeighborsError(f'could not find {k} nearest neighbors in {max_iterations}'
# 'diffusion steps.\n Please increase max_iterations or reduce'
# ' k.\n')
#
# M.setdiag(0)
# k_indices = np.argpartition(M.A, -k, axis=1)[:, -k:]
#
# return k_indices
. Output only the next line. | check_adata(adata) |
Given the following code snippet before the placeholder: <|code_start|>
anndata2ri.deactivate()
return score
def kBET(
adata,
batch_key,
label_key,
scaled=True,
embed='X_pca',
type_=None,
return_df=False,
verbose=False
):
"""
:param adata: anndata object to compute kBET on
:param batch_key: name of batch column in adata.obs
:param label_key: name of cell identity labels column in adata.obs
:param scaled: whether to scale between 0 and 1
with 0 meaning low batch mixing and 1 meaning optimal batch mixing
if scaled=False, 0 means optimal batch mixing and 1 means low batch mixing
return:
kBET score (average of kBET per label) based on observed rejection rate
return_df=True: pd.DataFrame with kBET observed rejection rates per cluster for batch
"""
check_adata(adata)
<|code_end|>
, predict the next line using imports from the current file:
import logging
import anndata2ri
import numpy as np
import pandas as pd
import rpy2.rinterface_lib.callbacks
import rpy2.robjects as ro
import scanpy as sc
import scipy.sparse
from ..utils import check_adata, check_batch
from .utils import NeighborsError, diffusion_conn, diffusion_nn
and context including class names, function names, and sometimes code from other files:
# Path: scib/utils.py
# def check_adata(adata):
# if type(adata) is not anndata.AnnData:
# raise TypeError('Input is not a valid AnnData object')
#
# def check_batch(batch, obs, verbose=False):
# if batch not in obs:
# raise ValueError(f'column {batch} is not in obs')
# elif verbose:
# print(f'Object contains {obs[batch].nunique()} batches.')
#
# Path: scib/metrics/utils.py
# class NeighborsError(Exception):
# def __init__(self, message):
# self.message = message
#
# def diffusion_conn(adata, min_k=50, copy=True, max_iterations=26):
# """
# Diffusion for connectivites matrix extension
# This function performs graph diffusion on the connectivities matrix until a
# minimum number `min_k` of entries per row are non-zero.
#
# Note:
# Due to self-loops min_k-1 non-zero connectivies entries is actually the stopping
# criterion. This is equivalent to `sc.pp.neighbors`.
#
# Returns:
# The diffusion-enhanced connectivities matrix of a copy of the AnnData object
# with the diffusion-enhanced connectivities matrix is in
# `adata.uns["neighbors"]["conectivities"]`
# """
# if 'neighbors' not in adata.uns:
# raise ValueError(
# '`neighbors` not in adata object. '
# 'Please compute a neighbourhood graph!'
# )
#
# if 'connectivities' not in adata.obsp:
# raise ValueError(
# '`connectivities` not in `adata.obsp`. '
# 'Please pass an object with connectivities computed!'
# )
#
# T = adata.obsp['connectivities']
#
# # Normalize T with max row sum
# # Note: This keeps the matrix symmetric and ensures |M| doesn't keep growing
# T = sparse.diags(1 / np.array([T.sum(1).max()] * T.shape[0])) * T
#
# M = T
#
# # Check for disconnected component
# n_comp, labs = sparse.csgraph.connected_components(adata.obsp['connectivities'],
# connection='strong')
#
# if n_comp > 1:
# tab = pd.value_counts(labs)
# small_comps = tab.index[tab < min_k]
# large_comp_mask = np.array(~pd.Series(labs).isin(small_comps))
# else:
# large_comp_mask = np.array([True] * M.shape[0])
#
# T_agg = T
# i = 2
# while ((M[large_comp_mask, :][:, large_comp_mask] > 0).sum(1).min() < min_k) and (i < max_iterations):
# print(f'Adding diffusion to step {i}')
# T_agg *= T
# M += T_agg
# i += 1
#
# if (M[large_comp_mask, :][:, large_comp_mask] > 0).sum(1).min() < min_k:
# raise ValueError(
# 'could not create diffusion connectivities matrix'
# f'with at least {min_k} non-zero entries in'
# f'{max_iterations} iterations.\n Please increase the'
# 'value of max_iterations or reduce k_min.\n'
# )
#
# M.setdiag(0)
#
# if copy:
# adata_tmp = adata.copy()
# adata_tmp.uns['neighbors'].update({'diffusion_connectivities': M})
# return adata_tmp
#
# else:
# return M
#
# def diffusion_nn(adata, k, max_iterations=26):
# """
# Diffusion neighbourhood score
# This function generates a nearest neighbour list from a connectivities matrix
# as supplied by BBKNN or Conos. This allows us to select a consistent number
# of nearest neighbours across all methods.
#
# Return:
# `k_indices` a numpy.ndarray of the indices of the k-nearest neighbors.
# """
# if 'neighbors' not in adata.uns:
# raise ValueError('`neighbors` not in adata object. '
# 'Please compute a neighbourhood graph!')
#
# if 'connectivities' not in adata.obsp:
# raise ValueError('`connectivities` not in `adata.obsp`. '
# 'Please pass an object with connectivities computed!')
#
# T = adata.obsp['connectivities']
#
# # Row-normalize T
# T = sparse.diags(1 / T.sum(1).A.ravel()) * T
#
# T_agg = T ** 3
# M = T + T ** 2 + T_agg
# i = 4
#
# while ((M > 0).sum(1).min() < (k + 1)) and (i < max_iterations):
# # note: k+1 is used as diag is non-zero (self-loops)
# print(f'Adding diffusion to step {i}')
# T_agg *= T
# M += T_agg
# i += 1
#
# if (M > 0).sum(1).min() < (k + 1):
# raise NeighborsError(f'could not find {k} nearest neighbors in {max_iterations}'
# 'diffusion steps.\n Please increase max_iterations or reduce'
# ' k.\n')
#
# M.setdiag(0)
# k_indices = np.argpartition(M.A, -k, axis=1)[:, -k:]
#
# return k_indices
. Output only the next line. | check_batch(batch_key, adata.obs) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
class SaFaker(object):
"""
This is a class for creating dummy database models for testing purposes.
"""
# Class Members
# Instantiation
# Static Methods
@staticmethod
def create_posts_for_user(to_populate=None, count=100):
"""
Create a number of StreetArtPost objects and associate them with the given
user.
:param to_populate: The user to populate.
:param count: The number of posts to add to the user.
:return: The newly-created posts.
"""
new_posts = []
faker = Faker()
for i in range(count):
<|code_end|>
. Use current file imports:
(from faker import Faker
from uuid import uuid4
from .data import StreetArtTestData
from ..models import StreetArtUser, StreetArtPost)
and context including class names, function names, or small code snippets from other files:
# Path: sectesting/streetart/tests/data.py
# class StreetArtTestData(object):
# """
# This class contains test data for use in unit testing the Street Art project.
# """
#
# USERS = {
# "user_1": {
# "email": "test1@streetart.com",
# "first_name": "Barry",
# "last_name": "Bonds",
# "date_joined": datetime.now(),
# "is_active": True,
# "is_staff": False,
# "is_superuser": False,
# "password": "Password123",
# },
# "user_2": {
# "email": "test2@streetart.com",
# "first_name": "Billy",
# "last_name": "Bonds",
# "date_joined": datetime.now(),
# "is_active": True,
# "is_staff": False,
# "is_superuser": False,
# "password": "Password123",
# },
# "admin_1": {
# "email": "test3@streetart.com",
# "first_name": "Bondy",
# "last_name": "Bonds",
# "date_joined": datetime.now(),
# "is_active": True,
# "is_staff": False,
# "is_superuser": True,
# "password": "Password123",
# }
# }
#
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
#
# Path: sectesting/streetart/models/user.py
# class StreetArtUser(AbstractBaseUser, PermissionsMixin, BaseStreetArtModel):
# """
# This is a custom user class for users of the Street Art project.
# """
#
# # Columns
#
# email = models.EmailField(_('email address'), unique=True)
# first_name = models.CharField(_('first name'), max_length=30, blank=True)
# last_name = models.CharField(_('last name'), max_length=30, blank=True)
# date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
# is_active = models.BooleanField(_('active'), default=True)
# is_staff = models.BooleanField(default=False)
#
# USERNAME_FIELD = "email"
# REQUIRED_FIELDS = []
#
# objects = StreetArtUserManager()
#
# # Class Meta
#
# class Meta:
# verbose_name = _('user')
# verbose_name_plural = _('users')
#
# # Methods
#
# def get_full_name(self):
# """
# Get a string representing the user's full name.
# :return: A string representing the user's full name.
# """
# to_return = "%s %s" % (self.first_name, self.last_name)
# return to_return.strip()
#
# def get_short_name(self):
# """
# Get a string representing the user's short name.
# :return: A string representing the user's short name.
# """
# return self.first_name
#
# def send_email(self, subject, message, from_email=None, **kwargs):
# """
# Send an email to this user.
# :param subject: The subject for the email.
# :param message: The message to include in the email.
# :param from_email: The email address where the email should originate from.
# :param kwargs: Keyword arguments for send_mail.
# :return: None
# """
# send_mail(subject, message, from_email, [self.email], **kwargs)
. Output only the next line. | new_posts.append(StreetArtPost.objects.create( |
Given the code snippet: <|code_start|> user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
"""
Create and save a regular user based on the given email and password.
:param email: The email to assign the user.
:param password: The password to assign the user.
:param extra_fields: Extra fields to attribute to the user.
:return: The created user object.
"""
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a super user based on the given email and password.
:param email: The email to assign the user.
:param password: The password to assign the user.
:param extra_fields: Extra fields to attribute to the user.
:return: The created user object.
"""
extra_fields.setdefault("is_superuser", True)
extra_fields.setdefault("is_staff", True)
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self._create_user(email, password, **extra_fields)
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import PermissionsMixin
from django.core.mail import send_mail
from django.contrib.auth.base_user import BaseUserManager
from .base import BaseStreetArtModel
and context (functions, classes, or occasionally code) from other files:
# Path: sectesting/streetart/models/base.py
# class BaseStreetArtModel(models.Model):
# """
# This is a base model for all models used by the Street Art project.
# """
#
# uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# created = models.DateTimeField(auto_now_add=True)
#
# class Meta:
# ordering = ("created",)
# abstract = True
#
# def __repr__(self):
# return "<%s - %s>" % (self.__class__.__name__, self.uuid)
. Output only the next line. | class StreetArtUser(AbstractBaseUser, PermissionsMixin, BaseStreetArtModel): |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
@requested_by("streetart.tests.requestors.pages.PostListViewRequestor")
class PostListView(BaseListView):
"""
This is the main landing view that presents the user with all of the street art posts
contained within the Street Art project database.
"""
template_name = "pages/streetart_post_list.html"
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from uuid import uuid4
from django.conf import settings
from django.urls import reverse_lazy
from django.db import connection
from ...models import StreetArtPost
from ...forms import NewStreetArtPostForm, EditStreetArtPostForm
from .base import BaseListView, BaseDetailView, BaseFormView, BaseUpdateView, BaseDeleteView, BaseTemplateView
from lib import ImageProcessingHelper, InvalidImageFileException, S3Helper
from streetart.tests import requested_by
and context from other files:
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
#
# Path: sectesting/streetart/forms/post.py
# class EditStreetArtPostForm(forms.ModelForm):
# """
# This is a form for editing a street art post.
# """
#
# class Meta:
# model = StreetArtPost
# fields = [
# "title",
# "description",
# "latitude",
# "longitude",
# ]
#
# class NewStreetArtPostForm(forms.ModelForm):
# """
# This is a form for creating new street art posts.
# """
#
# image = forms.ImageField()
#
# class Meta:
# model = StreetArtPost
# fields = ["title", "description"]
#
# Path: sectesting/streetart/views/pages/base.py
# class BaseListView(ListView):
# """
# This is a base class for all ListView pages used within the Street Art project.
# """
#
# class BaseDetailView(DetailView):
# """
# This is a base class for all DetailView pages used within the Street Art project.
# """
#
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseUpdateView(UpdateView):
# """
# This is a base class for all UpdateView pages used within the Street Art project.
# """
#
# class BaseDeleteView(DeleteView):
# """
# This is a base class for all DeleteView pages used within the Street Art project.
# """
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
, which may include functions, classes, or code. Output only the next line. | model = StreetArtPost |
Given the following code snippet before the placeholder: <|code_start|> return "/post-successful/%s/" % (self.created_object.uuid,)
@requested_by("streetart.tests.requestors.pages.SuccessfulPostDetailViewRequestor")
class SuccessfulPostDetailView(BaseDetailView):
"""
This is the page for providing the user with details regarding the post that they uploaded.
"""
template_name = "pages/streetart_post_successful.html"
model = StreetArtPost
@requested_by("streetart.tests.requestors.pages.PostDetailViewRequestor")
class PostDetailView(BaseDetailView):
"""
This is the page for providing the user with details regarding a single post.
"""
template_name = "pages/streetart_post.html"
model = StreetArtPost
@requested_by("streetart.tests.requestors.pages.EditPostViewRequestor")
class EditPostView(LoginRequiredMixin, BaseUpdateView):
"""
This is the page for editing the contents of a street art post object.
"""
template_name = "pages/edit_streetart_post.html"
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from uuid import uuid4
from django.conf import settings
from django.urls import reverse_lazy
from django.db import connection
from ...models import StreetArtPost
from ...forms import NewStreetArtPostForm, EditStreetArtPostForm
from .base import BaseListView, BaseDetailView, BaseFormView, BaseUpdateView, BaseDeleteView, BaseTemplateView
from lib import ImageProcessingHelper, InvalidImageFileException, S3Helper
from streetart.tests import requested_by
and context including class names, function names, and sometimes code from other files:
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
#
# Path: sectesting/streetart/forms/post.py
# class EditStreetArtPostForm(forms.ModelForm):
# """
# This is a form for editing a street art post.
# """
#
# class Meta:
# model = StreetArtPost
# fields = [
# "title",
# "description",
# "latitude",
# "longitude",
# ]
#
# class NewStreetArtPostForm(forms.ModelForm):
# """
# This is a form for creating new street art posts.
# """
#
# image = forms.ImageField()
#
# class Meta:
# model = StreetArtPost
# fields = ["title", "description"]
#
# Path: sectesting/streetart/views/pages/base.py
# class BaseListView(ListView):
# """
# This is a base class for all ListView pages used within the Street Art project.
# """
#
# class BaseDetailView(DetailView):
# """
# This is a base class for all DetailView pages used within the Street Art project.
# """
#
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseUpdateView(UpdateView):
# """
# This is a base class for all UpdateView pages used within the Street Art project.
# """
#
# class BaseDeleteView(DeleteView):
# """
# This is a base class for all DeleteView pages used within the Street Art project.
# """
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
. Output only the next line. | form_class = EditStreetArtPostForm |
Given snippet: <|code_start|> template_name = "pages/streetart_post_list.html"
model = StreetArtPost
paginate_by = 2
@requested_by("streetart.tests.requestors.pages.MyPostsListViewRequestor")
class MyPostsListView(LoginRequiredMixin, BaseListView):
"""
This is a page for displaying all of the posts associated with the logged-in user.
"""
template_name = "pages/streetart_post_list.html"
model = StreetArtPost
paginate_by = 2
def get_queryset(self):
"""
Get all of the posts that are associated with the requesting user.
:return: All of the posts that are associated with the requesting user.
"""
return self.request.user.posts.all()
@requested_by("streetart.tests.requestors.pages.CreatePostViewRequestor")
class CreatePostView(BaseFormView):
"""
This is a view for creating new street art posts.
"""
template_name = "pages/new_streetart_post.html"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from uuid import uuid4
from django.conf import settings
from django.urls import reverse_lazy
from django.db import connection
from ...models import StreetArtPost
from ...forms import NewStreetArtPostForm, EditStreetArtPostForm
from .base import BaseListView, BaseDetailView, BaseFormView, BaseUpdateView, BaseDeleteView, BaseTemplateView
from lib import ImageProcessingHelper, InvalidImageFileException, S3Helper
from streetart.tests import requested_by
and context:
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
#
# Path: sectesting/streetart/forms/post.py
# class EditStreetArtPostForm(forms.ModelForm):
# """
# This is a form for editing a street art post.
# """
#
# class Meta:
# model = StreetArtPost
# fields = [
# "title",
# "description",
# "latitude",
# "longitude",
# ]
#
# class NewStreetArtPostForm(forms.ModelForm):
# """
# This is a form for creating new street art posts.
# """
#
# image = forms.ImageField()
#
# class Meta:
# model = StreetArtPost
# fields = ["title", "description"]
#
# Path: sectesting/streetart/views/pages/base.py
# class BaseListView(ListView):
# """
# This is a base class for all ListView pages used within the Street Art project.
# """
#
# class BaseDetailView(DetailView):
# """
# This is a base class for all DetailView pages used within the Street Art project.
# """
#
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseUpdateView(UpdateView):
# """
# This is a base class for all UpdateView pages used within the Street Art project.
# """
#
# class BaseDeleteView(DeleteView):
# """
# This is a base class for all DeleteView pages used within the Street Art project.
# """
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
which might include code, classes, or functions. Output only the next line. | form_class = NewStreetArtPostForm |
Based on the snippet: <|code_start|> s3_helper = S3Helper.instance()
response = s3_helper.upload_file_to_bucket(
local_file_path=form.files["image"].temporary_file_path(),
key=post_uuid,
bucket=settings.AWS_S3_BUCKET,
)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise ValueError("Unable to upload image file to Amazon S3.")
user = self.request.user if self.request.user.is_authenticated else None
self._create_object(
latitude=latitude,
longitude=longitude,
title=form.cleaned_data["title"],
description=form.cleaned_data["description"],
s3_bucket=settings.AWS_S3_BUCKET,
s3_key=post_uuid,
uuid=post_uuid,
user=user,
)
return super(CreatePostView, self).form_valid(form)
def get_success_url(self):
"""
Get the URL to redirect users to after a successful post creation.
:return: The URL to redirect users to after a successful post creation.
"""
return "/post-successful/%s/" % (self.created_object.uuid,)
@requested_by("streetart.tests.requestors.pages.SuccessfulPostDetailViewRequestor")
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from uuid import uuid4
from django.conf import settings
from django.urls import reverse_lazy
from django.db import connection
from ...models import StreetArtPost
from ...forms import NewStreetArtPostForm, EditStreetArtPostForm
from .base import BaseListView, BaseDetailView, BaseFormView, BaseUpdateView, BaseDeleteView, BaseTemplateView
from lib import ImageProcessingHelper, InvalidImageFileException, S3Helper
from streetart.tests import requested_by
and context (classes, functions, sometimes code) from other files:
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
#
# Path: sectesting/streetart/forms/post.py
# class EditStreetArtPostForm(forms.ModelForm):
# """
# This is a form for editing a street art post.
# """
#
# class Meta:
# model = StreetArtPost
# fields = [
# "title",
# "description",
# "latitude",
# "longitude",
# ]
#
# class NewStreetArtPostForm(forms.ModelForm):
# """
# This is a form for creating new street art posts.
# """
#
# image = forms.ImageField()
#
# class Meta:
# model = StreetArtPost
# fields = ["title", "description"]
#
# Path: sectesting/streetart/views/pages/base.py
# class BaseListView(ListView):
# """
# This is a base class for all ListView pages used within the Street Art project.
# """
#
# class BaseDetailView(DetailView):
# """
# This is a base class for all DetailView pages used within the Street Art project.
# """
#
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseUpdateView(UpdateView):
# """
# This is a base class for all UpdateView pages used within the Street Art project.
# """
#
# class BaseDeleteView(DeleteView):
# """
# This is a base class for all DeleteView pages used within the Street Art project.
# """
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
. Output only the next line. | class SuccessfulPostDetailView(BaseDetailView): |
Given snippet: <|code_start|>class PostListView(BaseListView):
"""
This is the main landing view that presents the user with all of the street art posts
contained within the Street Art project database.
"""
template_name = "pages/streetart_post_list.html"
model = StreetArtPost
paginate_by = 2
@requested_by("streetart.tests.requestors.pages.MyPostsListViewRequestor")
class MyPostsListView(LoginRequiredMixin, BaseListView):
"""
This is a page for displaying all of the posts associated with the logged-in user.
"""
template_name = "pages/streetart_post_list.html"
model = StreetArtPost
paginate_by = 2
def get_queryset(self):
"""
Get all of the posts that are associated with the requesting user.
:return: All of the posts that are associated with the requesting user.
"""
return self.request.user.posts.all()
@requested_by("streetart.tests.requestors.pages.CreatePostViewRequestor")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from uuid import uuid4
from django.conf import settings
from django.urls import reverse_lazy
from django.db import connection
from ...models import StreetArtPost
from ...forms import NewStreetArtPostForm, EditStreetArtPostForm
from .base import BaseListView, BaseDetailView, BaseFormView, BaseUpdateView, BaseDeleteView, BaseTemplateView
from lib import ImageProcessingHelper, InvalidImageFileException, S3Helper
from streetart.tests import requested_by
and context:
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
#
# Path: sectesting/streetart/forms/post.py
# class EditStreetArtPostForm(forms.ModelForm):
# """
# This is a form for editing a street art post.
# """
#
# class Meta:
# model = StreetArtPost
# fields = [
# "title",
# "description",
# "latitude",
# "longitude",
# ]
#
# class NewStreetArtPostForm(forms.ModelForm):
# """
# This is a form for creating new street art posts.
# """
#
# image = forms.ImageField()
#
# class Meta:
# model = StreetArtPost
# fields = ["title", "description"]
#
# Path: sectesting/streetart/views/pages/base.py
# class BaseListView(ListView):
# """
# This is a base class for all ListView pages used within the Street Art project.
# """
#
# class BaseDetailView(DetailView):
# """
# This is a base class for all DetailView pages used within the Street Art project.
# """
#
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseUpdateView(UpdateView):
# """
# This is a base class for all UpdateView pages used within the Street Art project.
# """
#
# class BaseDeleteView(DeleteView):
# """
# This is a base class for all DeleteView pages used within the Street Art project.
# """
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
which might include code, classes, or functions. Output only the next line. | class CreatePostView(BaseFormView): |
Here is a snippet: <|code_start|>
def get_success_url(self):
"""
Get the URL to redirect users to after a successful post creation.
:return: The URL to redirect users to after a successful post creation.
"""
return "/post-successful/%s/" % (self.created_object.uuid,)
@requested_by("streetart.tests.requestors.pages.SuccessfulPostDetailViewRequestor")
class SuccessfulPostDetailView(BaseDetailView):
"""
This is the page for providing the user with details regarding the post that they uploaded.
"""
template_name = "pages/streetart_post_successful.html"
model = StreetArtPost
@requested_by("streetart.tests.requestors.pages.PostDetailViewRequestor")
class PostDetailView(BaseDetailView):
"""
This is the page for providing the user with details regarding a single post.
"""
template_name = "pages/streetart_post.html"
model = StreetArtPost
@requested_by("streetart.tests.requestors.pages.EditPostViewRequestor")
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from uuid import uuid4
from django.conf import settings
from django.urls import reverse_lazy
from django.db import connection
from ...models import StreetArtPost
from ...forms import NewStreetArtPostForm, EditStreetArtPostForm
from .base import BaseListView, BaseDetailView, BaseFormView, BaseUpdateView, BaseDeleteView, BaseTemplateView
from lib import ImageProcessingHelper, InvalidImageFileException, S3Helper
from streetart.tests import requested_by
and context from other files:
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
#
# Path: sectesting/streetart/forms/post.py
# class EditStreetArtPostForm(forms.ModelForm):
# """
# This is a form for editing a street art post.
# """
#
# class Meta:
# model = StreetArtPost
# fields = [
# "title",
# "description",
# "latitude",
# "longitude",
# ]
#
# class NewStreetArtPostForm(forms.ModelForm):
# """
# This is a form for creating new street art posts.
# """
#
# image = forms.ImageField()
#
# class Meta:
# model = StreetArtPost
# fields = ["title", "description"]
#
# Path: sectesting/streetart/views/pages/base.py
# class BaseListView(ListView):
# """
# This is a base class for all ListView pages used within the Street Art project.
# """
#
# class BaseDetailView(DetailView):
# """
# This is a base class for all DetailView pages used within the Street Art project.
# """
#
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseUpdateView(UpdateView):
# """
# This is a base class for all UpdateView pages used within the Street Art project.
# """
#
# class BaseDeleteView(DeleteView):
# """
# This is a base class for all DeleteView pages used within the Street Art project.
# """
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
, which may include functions, classes, or code. Output only the next line. | class EditPostView(LoginRequiredMixin, BaseUpdateView): |
Using the snippet: <|code_start|> """
This is the page for providing the user with details regarding the post that they uploaded.
"""
template_name = "pages/streetart_post_successful.html"
model = StreetArtPost
@requested_by("streetart.tests.requestors.pages.PostDetailViewRequestor")
class PostDetailView(BaseDetailView):
"""
This is the page for providing the user with details regarding a single post.
"""
template_name = "pages/streetart_post.html"
model = StreetArtPost
@requested_by("streetart.tests.requestors.pages.EditPostViewRequestor")
class EditPostView(LoginRequiredMixin, BaseUpdateView):
"""
This is the page for editing the contents of a street art post object.
"""
template_name = "pages/edit_streetart_post.html"
form_class = EditStreetArtPostForm
model = StreetArtPost
@requested_by("streetart.tests.requestors.pages.DeletePostViewRequestor")
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from uuid import uuid4
from django.conf import settings
from django.urls import reverse_lazy
from django.db import connection
from ...models import StreetArtPost
from ...forms import NewStreetArtPostForm, EditStreetArtPostForm
from .base import BaseListView, BaseDetailView, BaseFormView, BaseUpdateView, BaseDeleteView, BaseTemplateView
from lib import ImageProcessingHelper, InvalidImageFileException, S3Helper
from streetart.tests import requested_by
and context (class names, function names, or code) available:
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
#
# Path: sectesting/streetart/forms/post.py
# class EditStreetArtPostForm(forms.ModelForm):
# """
# This is a form for editing a street art post.
# """
#
# class Meta:
# model = StreetArtPost
# fields = [
# "title",
# "description",
# "latitude",
# "longitude",
# ]
#
# class NewStreetArtPostForm(forms.ModelForm):
# """
# This is a form for creating new street art posts.
# """
#
# image = forms.ImageField()
#
# class Meta:
# model = StreetArtPost
# fields = ["title", "description"]
#
# Path: sectesting/streetart/views/pages/base.py
# class BaseListView(ListView):
# """
# This is a base class for all ListView pages used within the Street Art project.
# """
#
# class BaseDetailView(DetailView):
# """
# This is a base class for all DetailView pages used within the Street Art project.
# """
#
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseUpdateView(UpdateView):
# """
# This is a base class for all UpdateView pages used within the Street Art project.
# """
#
# class BaseDeleteView(DeleteView):
# """
# This is a base class for all DeleteView pages used within the Street Art project.
# """
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
. Output only the next line. | class DeletePostView(LoginRequiredMixin, BaseDeleteView): |
Given snippet: <|code_start|> This is the page for providing the user with details regarding a single post.
"""
template_name = "pages/streetart_post.html"
model = StreetArtPost
@requested_by("streetart.tests.requestors.pages.EditPostViewRequestor")
class EditPostView(LoginRequiredMixin, BaseUpdateView):
"""
This is the page for editing the contents of a street art post object.
"""
template_name = "pages/edit_streetart_post.html"
form_class = EditStreetArtPostForm
model = StreetArtPost
@requested_by("streetart.tests.requestors.pages.DeletePostViewRequestor")
class DeletePostView(LoginRequiredMixin, BaseDeleteView):
"""
This is the page for deleting the contents of a street art post object.
"""
template_name = "pages/streetart_post_confirm_delete.html"
model = StreetArtPost
success_url = reverse_lazy("post-list")
@requested_by("streetart.tests.requestors.pages.GetPostsByTitleViewRequestor")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from uuid import uuid4
from django.conf import settings
from django.urls import reverse_lazy
from django.db import connection
from ...models import StreetArtPost
from ...forms import NewStreetArtPostForm, EditStreetArtPostForm
from .base import BaseListView, BaseDetailView, BaseFormView, BaseUpdateView, BaseDeleteView, BaseTemplateView
from lib import ImageProcessingHelper, InvalidImageFileException, S3Helper
from streetart.tests import requested_by
and context:
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
#
# Path: sectesting/streetart/forms/post.py
# class EditStreetArtPostForm(forms.ModelForm):
# """
# This is a form for editing a street art post.
# """
#
# class Meta:
# model = StreetArtPost
# fields = [
# "title",
# "description",
# "latitude",
# "longitude",
# ]
#
# class NewStreetArtPostForm(forms.ModelForm):
# """
# This is a form for creating new street art posts.
# """
#
# image = forms.ImageField()
#
# class Meta:
# model = StreetArtPost
# fields = ["title", "description"]
#
# Path: sectesting/streetart/views/pages/base.py
# class BaseListView(ListView):
# """
# This is a base class for all ListView pages used within the Street Art project.
# """
#
# class BaseDetailView(DetailView):
# """
# This is a base class for all DetailView pages used within the Street Art project.
# """
#
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseUpdateView(UpdateView):
# """
# This is a base class for all UpdateView pages used within the Street Art project.
# """
#
# class BaseDeleteView(DeleteView):
# """
# This is a base class for all DeleteView pages used within the Street Art project.
# """
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
which might include code, classes, or functions. Output only the next line. | class GetPostsByTitleView(BaseTemplateView): |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
class NewUserForm(forms.ModelForm):
"""
This is a form for handling the registration of a new user.
"""
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from django import forms
from ..models import StreetArtUser
and context including class names, function names, and sometimes code from other files:
# Path: sectesting/streetart/models/user.py
# class StreetArtUser(AbstractBaseUser, PermissionsMixin, BaseStreetArtModel):
# """
# This is a custom user class for users of the Street Art project.
# """
#
# # Columns
#
# email = models.EmailField(_('email address'), unique=True)
# first_name = models.CharField(_('first name'), max_length=30, blank=True)
# last_name = models.CharField(_('last name'), max_length=30, blank=True)
# date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
# is_active = models.BooleanField(_('active'), default=True)
# is_staff = models.BooleanField(default=False)
#
# USERNAME_FIELD = "email"
# REQUIRED_FIELDS = []
#
# objects = StreetArtUserManager()
#
# # Class Meta
#
# class Meta:
# verbose_name = _('user')
# verbose_name_plural = _('users')
#
# # Methods
#
# def get_full_name(self):
# """
# Get a string representing the user's full name.
# :return: A string representing the user's full name.
# """
# to_return = "%s %s" % (self.first_name, self.last_name)
# return to_return.strip()
#
# def get_short_name(self):
# """
# Get a string representing the user's short name.
# :return: A string representing the user's short name.
# """
# return self.first_name
#
# def send_email(self, subject, message, from_email=None, **kwargs):
# """
# Send an email to this user.
# :param subject: The subject for the email.
# :param message: The message to include in the email.
# :param from_email: The email address where the email should originate from.
# :param kwargs: Keyword arguments for send_mail.
# :return: None
# """
# send_mail(subject, message, from_email, [self.email], **kwargs)
. Output only the next line. | model = StreetArtUser |
Next line prediction: <|code_start|>
def get_trace_data(self, user="user_1"):
"""
Get a dictionary containing data to submit in HTTP TRACE requests to the view.
:param user: A string depicting the user to get TRACE data for.
:return: A dictionary containing data to submit in HTTP TRACE requests to the view.
"""
return None
def get_url_path(self, user="user_1"):
"""
Get the URL path to request through the methods found in this class.
:param user: A string depicting the user that the requested URL should be generated off
of.
:return: A string depicting the URL path to request.
"""
return None
def send_delete(self, user_string="user_1", do_auth=True, enforce_csrf_checks=False, *args, **kwargs):
"""
Send a DELETE request to the configured URL endpoint on behalf of the given user.
:param user_string: The user to send the request as.
:param do_auth: Whether or not to log the user in if the view requires authentication.
:param enforce_csrf_checks: Whether or not to enforce CSRF checks in the HTTP client.
:param args: Positional arguments for client.delete.
:param kwargs: Keyword arguments for client.delete.
:return: The HTTP response.
"""
client = Client(enforce_csrf_checks=enforce_csrf_checks)
if self.requires_auth and do_auth:
<|code_end|>
. Use current file imports:
(from django.test import Client
from ..safaker import SaFaker)
and context including class names, function names, or small code snippets from other files:
# Path: sectesting/streetart/tests/safaker.py
# class SaFaker(object):
# """
# This is a class for creating dummy database models for testing purposes.
# """
#
# # Class Members
#
# # Instantiation
#
# # Static Methods
#
# @staticmethod
# def create_posts_for_user(to_populate=None, count=100):
# """
# Create a number of StreetArtPost objects and associate them with the given
# user.
# :param to_populate: The user to populate.
# :param count: The number of posts to add to the user.
# :return: The newly-created posts.
# """
# new_posts = []
# faker = Faker()
# for i in range(count):
# new_posts.append(StreetArtPost.objects.create(
# latitude=float(faker.random_number()) * 0.01,
# longitude=float(faker.random_number()) * 0.01,
# title=faker.word(),
# description=faker.paragraph(),
# s3_bucket=faker.word(),
# s3_key=str(uuid4()),
# user=to_populate,
# ))
# return new_posts
#
# @staticmethod
# def create_users():
# """
# Create all of the test users for Street Art unit tests.
# :return: A list containing all of the users.
# """
# new_users = []
# for user_string in StreetArtTestData.USERS.keys():
# new_users.append(SaFaker.create_user(user_string))
# for new_user in new_users:
# SaFaker.populate_user(new_user)
# return new_users
#
# @staticmethod
# def create_user(user_string):
# """
# Create a user based on the given string.
# :param user_string: A string depicting which user to create.
# :return: The newly-created user.
# """
# user_data = StreetArtTestData.USERS[user_string]
# new_user = StreetArtUser.objects.create(**user_data)
# new_user.set_password(user_data["password"])
# new_user.save()
# return new_user
#
# @staticmethod
# def get_create_post_kwargs():
# """
# Get a dictionary of values to submit to the post creation endpoint.
# :return: A dictionary of values to submit to the post creation endpoint.
# """
# faker = Faker()
# f = open("streetart/tests/files/puppy.jpg", "r")
# return {
# "title": faker.word(),
# "description": faker.paragraph(),
# "image": f,
# }
#
# @staticmethod
# def get_create_user_kwargs():
# """
# Get a dictionary of values to submit to the user registration endpoint.
# :return: A dictionary of values to submit to the user registration endpoint.
# """
# faker = Faker()
# return {
# "email": faker.email(),
# "first_name": faker.first_name(),
# "last_name": faker.last_name(),
# "password": faker.password(),
# }
#
# @staticmethod
# def get_edit_post_kwargs():
# """
# Get a dictionary of values to submit to the edit post endpoint.
# :return: A dictionary of values to submit to the edit post endpoint.
# """
# faker = Faker()
# return {
# "title": faker.word(),
# "description": faker.paragraph(),
# "latitude": float(faker.pydecimal()),
# "longitude": float(faker.pydecimal()),
# }
#
# @staticmethod
# def get_post_for_user(user_string):
# """
# Get a StreetArtPost object owned by the given user.
# :param user_string: A string depicting the user to retrieve a post for.
# :return: A StreetArtPost corresponding to the given user.
# """
# user = SaFaker.get_user(user_string)
# return user.posts.first()
#
# @staticmethod
# def get_user(user_string):
# """
# Get the user object corresponding to the given string.
# :param user_string: A string depicting the user to retrieve.
# :return: The user corresponding to the given string.
# """
# user_data = StreetArtTestData.USERS[user_string]
# return StreetArtUser.objects.get(email=user_data["email"])
#
# @staticmethod
# def populate_user(to_populate):
# """
# Populate database data for the given user.
# :param to_populate: The user to populate.
# :return: None
# """
# SaFaker.create_posts_for_user(to_populate=to_populate)
#
# # Class Methods
#
# # Public Methods
#
# # Protected Methods
#
# # Private Methods
#
# # Properties
#
# # Representation and Comparison
. Output only the next line. | user = SaFaker.get_user(user_string) |
Continue the code snippet: <|code_start|> Assert that the contents of the given response indicate a redirect.
:param response: The response to check.
:param message: The message to print upon failure.
:return: None
"""
self.assertIn(
response.status_code,
[301, 302],
msg=message,
)
def _assert_response_successful(self, response, message):
"""
Assert that the contents of the given response indicate a successful response.
:param response: The response to check.
:param message: The message to print upon failure.
:return: None
"""
self.assertIn(
response.status_code,
[200, 201, 202, 301, 302],
msg=message,
)
def _get_requestor_for_view(self, view):
"""
Get the requestor class to use to send requests to the given view.
:param view: The view to retrieve the requestor class for.
:return: The requestor class to use to send requests to the given view.
"""
<|code_end|>
. Use current file imports:
from django.test import TestCase
from ..registry import TestRequestorRegistry
and context (classes, functions, or code) from other files:
# Path: sectesting/streetart/tests/registry.py
# class TestRequestorRegistry(object):
# """
# This is a class that maintains mappings from views to test cases that are configured to
# send HTTP requests to the view in question.
# """
#
# # Class Members
#
# # Instantiation
#
# def __init__(self):
# self._registry = {}
#
# # Static Methods
#
# # Class Methods
#
# # Public Methods
#
# def add_mapping(self, requestor_path=None, requested_view=None):
# """
# Add a mapping from the view to the given requestor class specified by requestor_path.
# :param requestor_path: The path to the requestor class configured for the given view.
# :param requested_view: The view that the requestor is meant to send requests for.
# :return: None
# """
# try:
# requestor_class = self.__import_class(requestor_path)
# except (ImportError, AttributeError) as e:
# raise RequestorNotFoundException(
# "Unable to load requestor at %s: %s."
# % (requestor_path, e.message)
# )
# if not issubclass(requestor_class, BaseRequestor):
# raise InvalidRequestorException(
# "Class of %s is not a valid requestor class."
# % (requestor_class.__name__,)
# )
# self._registry[requested_view] = requestor_class
#
# def does_view_have_mapping(self, view):
# """
# Check to see if a mapping exists between the given view and a requestor class.
# :param view: The view to check a mapping for.
# :return: Whether or not a mapping exists for the given view.
# """
# return view in self.registry
#
# def get_requestor_for_view(self, view):
# """
# Get the requestor configured to send requests to the given view.
# :param view: The view to retrieve the requestor for.
# :return: The requestor configured to send requests to the given view.
# """
# return self.registry[view]
#
# def print_mappings(self):
# """
# Print all of the mappings currently stored within the registry.
# :return: None
# """
# for k, v in self.registry.iteritems():
# print("%s --> %s" % (k, v))
#
# # Protected Methods
#
# # Private Methods
#
# def __import_class(self, class_path):
# """
# Import the class at the given class path and return it.
# :param class_path: The class path to the class to load.
# :return: The loaded class.
# """
# components = class_path.split(".")
# mod = __import__(components[0])
# for component in components[1:]:
# mod = getattr(mod, component)
# return mod
#
# # Properties
#
# @property
# def registry(self):
# """
# Get the registry mapping functions and classes to the test classes that are configured to
# submit HTTP requests to them.
# :return: the registry mapping functions and classes to the test classes that are
# configured to submit HTTP requests to them.
# """
# return self._registry
#
# # Representation and Comparison
. Output only the next line. | registry = TestRequestorRegistry.instance() |
Predict the next line for this snippet: <|code_start|> "Unexpected verbs found for view %s. Expected %s, got %s."
% (self.view, [x.upper() for x in supported_verbs], [x.upper() for x in allowed_verbs])
)
class AdminUnknownMethodsTestCase(BaseViewTestCase):
"""
This is a test case for testing whether or not a view returns the expected HTTP verbs through
an OPTIONS request from an admin user.
"""
def runTest(self):
"""
Tests that the HTTP verbs returned by an OPTIONS request match the expected values.
:return: None
"""
requestor = self._get_requestor_for_view(self.view)
response = requestor.send_options(user_string="admin_1")
allowed_verbs = response._headers.get("allow", None)
if not allowed_verbs:
raise ValueError("No allow header returned by view %s." % self.view)
allowed_verbs = [x.strip().lower() for x in allowed_verbs[1].split(",")]
supported_verbs = [x.lower() for x in requestor.supported_verbs]
self.assertTrue(
all([x.lower() in supported_verbs for x in allowed_verbs]),
"Unexpected verbs found for view %s. Expected %s, got %s."
% (self.view, [x.upper() for x in supported_verbs], [x.upper() for x in allowed_verbs])
)
<|code_end|>
with the help of current file imports:
from .base import BaseViewTestCase, BaseViewVerbTestCase
and context from other files:
# Path: sectesting/streetart/tests/cases/base.py
# class BaseViewTestCase(BaseStreetArtTestCase):
# """
# This is a base class for all test cases that run tests on a view specified within the test
# case constructor.
# """
#
# def __init__(self, view=None, *args, **kwargs):
# self.view = view
# super(BaseViewTestCase, self).__init__(*args, **kwargs)
#
# class BaseViewVerbTestCase(BaseViewTestCase):
# """
# This is a base class for all test cases that run tests on a view and a verb specified within the
# test case constructor.
# """
#
# def __init__(self, verb=None, *args, **kwargs):
# self.verb = verb
# super(BaseViewVerbTestCase, self).__init__(*args, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | class RegularVerbNotSupportedTestCase(BaseViewVerbTestCase): |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
class ViewHasRequestorTestCase(BaseViewTestCase):
"""
This is a test case for testing whether or not a view has a corresponding requestor
mapped to it.
"""
def runTest(self):
"""
Tests that the given view has a requestor mapped to it.
:return: None
"""
<|code_end|>
, generate the next line using the imports in this file:
from .base import BaseViewTestCase
from ..registry import TestRequestorRegistry
and context (functions, classes, or occasionally code) from other files:
# Path: sectesting/streetart/tests/cases/base.py
# class BaseViewTestCase(BaseStreetArtTestCase):
# """
# This is a base class for all test cases that run tests on a view specified within the test
# case constructor.
# """
#
# def __init__(self, view=None, *args, **kwargs):
# self.view = view
# super(BaseViewTestCase, self).__init__(*args, **kwargs)
#
# Path: sectesting/streetart/tests/registry.py
# class TestRequestorRegistry(object):
# """
# This is a class that maintains mappings from views to test cases that are configured to
# send HTTP requests to the view in question.
# """
#
# # Class Members
#
# # Instantiation
#
# def __init__(self):
# self._registry = {}
#
# # Static Methods
#
# # Class Methods
#
# # Public Methods
#
# def add_mapping(self, requestor_path=None, requested_view=None):
# """
# Add a mapping from the view to the given requestor class specified by requestor_path.
# :param requestor_path: The path to the requestor class configured for the given view.
# :param requested_view: The view that the requestor is meant to send requests for.
# :return: None
# """
# try:
# requestor_class = self.__import_class(requestor_path)
# except (ImportError, AttributeError) as e:
# raise RequestorNotFoundException(
# "Unable to load requestor at %s: %s."
# % (requestor_path, e.message)
# )
# if not issubclass(requestor_class, BaseRequestor):
# raise InvalidRequestorException(
# "Class of %s is not a valid requestor class."
# % (requestor_class.__name__,)
# )
# self._registry[requested_view] = requestor_class
#
# def does_view_have_mapping(self, view):
# """
# Check to see if a mapping exists between the given view and a requestor class.
# :param view: The view to check a mapping for.
# :return: Whether or not a mapping exists for the given view.
# """
# return view in self.registry
#
# def get_requestor_for_view(self, view):
# """
# Get the requestor configured to send requests to the given view.
# :param view: The view to retrieve the requestor for.
# :return: The requestor configured to send requests to the given view.
# """
# return self.registry[view]
#
# def print_mappings(self):
# """
# Print all of the mappings currently stored within the registry.
# :return: None
# """
# for k, v in self.registry.iteritems():
# print("%s --> %s" % (k, v))
#
# # Protected Methods
#
# # Private Methods
#
# def __import_class(self, class_path):
# """
# Import the class at the given class path and return it.
# :param class_path: The class path to the class to load.
# :return: The loaded class.
# """
# components = class_path.split(".")
# mod = __import__(components[0])
# for component in components[1:]:
# mod = getattr(mod, component)
# return mod
#
# # Properties
#
# @property
# def registry(self):
# """
# Get the registry mapping functions and classes to the test classes that are configured to
# submit HTTP requests to them.
# :return: the registry mapping functions and classes to the test classes that are
# configured to submit HTTP requests to them.
# """
# return self._registry
#
# # Representation and Comparison
. Output only the next line. | registry = TestRequestorRegistry.instance() |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
class NewStreetArtPostForm(forms.ModelForm):
"""
This is a form for creating new street art posts.
"""
image = forms.ImageField()
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from ..models import StreetArtPost
and context (classes, functions, sometimes code) from other files:
# Path: sectesting/streetart/models/post.py
# class StreetArtPost(BaseStreetArtModel):
# """
# This is a model for containing all of the relevant data for a post referencing street art.
# """
#
# # Columns
#
# latitude = models.FloatField(null=True)
# longitude = models.FloatField(null=True)
# title = models.CharField(max_length=32, null=True)
# description = models.CharField(max_length=256, null=True)
# s3_bucket = models.CharField(max_length=32, null=True)
# s3_key = models.CharField(max_length=64, null=True)
# current_vote = models.IntegerField(default=0)
#
# # Foreign Keys
#
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# related_name="posts",
# on_delete=models.CASCADE,
# null=True,
# )
#
# # Methods
#
# def get_absolute_url(self):
# """
# Get the absolute URL to view the contents of this post at.
# :return: The absolute URL to view the contents of this post at.
# """
# return "/view-post/%s/" % (self.uuid,)
#
# # Properties
#
# @property
# def coordinates_string(self):
# """
# Get a string representing the coordinates where this photograph was taken.
# :return: a string representing the coordinates where this photograph was taken.
# """
# return "%s, %s" % (self.latitude, self.longitude)
#
# @property
# def has_coordinates(self):
# """
# Get whether or not this post has coordinates associated with it.
# :return: whether or not this post has coordinates associated with it.
# """
# return self.latitude is not None and self.longitude is not None
#
# @property
# def s3_url(self):
# """
# Get a signed URL to retrieve the referenced image from Amazon S3.
# :return: a signed URL to retrieve the referenced image from Amazon S3.
# """
# s3_helper = S3Helper.instance()
# return s3_helper.get_signed_url_for_key(key=str(self.uuid), bucket=settings.AWS_S3_BUCKET)
. Output only the next line. | model = StreetArtPost |
Given the following code snippet before the placeholder: <|code_start|>@requested_by("streetart.tests.requestors.pages.CreateUserViewRequestor")
class CreateUserView(BaseFormView):
"""
This is a view for creating a new user.
"""
template_name = "pages/register.html"
form_class = NewUserForm
success_url = "/register-success/"
def form_valid(self, form):
"""
Handle the processing of the form to create a new Street Art user.
:param form: The form to process.
:return: The HTTP redirect response from super.form_valid.
"""
user = self._create_object(
email=form.cleaned_data["email"],
first_name=form.cleaned_data["first_name"],
last_name=form.cleaned_data["last_name"],
is_active=True,
is_staff=False,
is_superuser=False,
)
user.set_password(form.cleaned_data["password"])
user.save()
return super(CreateUserView, self).form_valid(form)
@requested_by("streetart.tests.requestors.pages.CreateUserSuccessRequestor")
<|code_end|>
, predict the next line using imports from the current file:
from .base import BaseFormView, BaseTemplateView
from ...forms import NewUserForm
from ...tests import requested_by
and context including class names, function names, and sometimes code from other files:
# Path: sectesting/streetart/views/pages/base.py
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
#
# Path: sectesting/streetart/forms/user.py
# class NewUserForm(forms.ModelForm):
# """
# This is a form for handling the registration of a new user.
# """
#
# class Meta:
# model = StreetArtUser
# fields = [
# "email",
# "first_name",
# "last_name",
# "password",
# ]
#
# Path: sectesting/streetart/tests/registry.py
# def requested_by(requestor_path):
# """
# This is a decorator for views that maps a requestor class to the view that it is configured to
# submit requests to.
# :param requestor_path: A string depicting the local file path to the requestor class for the given
# view.
# :return: A function that maps the view class to the requestor path and returns the called function
# or class.
# """
#
# def decorator(to_wrap):
#
# registry = TestRequestorRegistry.instance()
# registry.add_mapping(requestor_path=requestor_path, requested_view=to_wrap)
# return to_wrap
#
# return decorator
. Output only the next line. | class CreateUserSuccessView(BaseTemplateView): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
@requested_by("streetart.tests.requestors.pages.CreateUserViewRequestor")
class CreateUserView(BaseFormView):
"""
This is a view for creating a new user.
"""
template_name = "pages/register.html"
<|code_end|>
, determine the next line of code. You have imports:
from .base import BaseFormView, BaseTemplateView
from ...forms import NewUserForm
from ...tests import requested_by
and context (class names, function names, or code) available:
# Path: sectesting/streetart/views/pages/base.py
# class BaseFormView(FormView):
# """
# This is a base class for all FormView pages used within the Street Art project.
# """
#
# _created_object = None
#
# def _create_object(self, **create_kwargs):
# """
# Create an instance of the referenced model class and return it.
# :param create_kwargs: Keyword arguments to pass to the object create method.
# :return: The newly-created object.
# """
# self._created_object = self.form_class.Meta.model.objects.create(**create_kwargs)
# return self._created_object
#
# @property
# def created_object(self):
# """
# Get the model instance that was created by valid submission of the referenced form.
# :return: the model instance that was created by valid submission of the referenced form.
# """
# return self._created_object
#
# class BaseTemplateView(TemplateView):
# """
# This is a base class for all TemplateView pages used within the Street Art project.
# """
#
# Path: sectesting/streetart/forms/user.py
# class NewUserForm(forms.ModelForm):
# """
# This is a form for handling the registration of a new user.
# """
#
# class Meta:
# model = StreetArtUser
# fields = [
# "email",
# "first_name",
# "last_name",
# "password",
# ]
#
# Path: sectesting/streetart/tests/registry.py
# def requested_by(requestor_path):
# """
# This is a decorator for views that maps a requestor class to the view that it is configured to
# submit requests to.
# :param requestor_path: A string depicting the local file path to the requestor class for the given
# view.
# :return: A function that maps the view class to the requestor path and returns the called function
# or class.
# """
#
# def decorator(to_wrap):
#
# registry = TestRequestorRegistry.instance()
# registry.add_mapping(requestor_path=requestor_path, requested_view=to_wrap)
# return to_wrap
#
# return decorator
. Output only the next line. | form_class = NewUserForm |
Next line prediction: <|code_start|>
logger = logging.getLogger(__name__)
SEED_MAX = (1 << 32) - 1 # Used for seeding rng
def main(fp_out, fasta_fname, sample_name, bed_fname, seed, p_het, models):
"""
:param fp_out: output file pointer
:param fasta_fname:
:param sample_name:
:param bed_fname:
:param seed:
:param p_het:
:param models:
:return:
"""
logger.debug('Starting variant simulation ...')
t0 = time.time()
v_cnt_tot = 0
fp_out.write(generate_header(fasta_fname, sample_name))
fasta = pysam.FastaFile(fasta_fname)
rng = np.random.RandomState(seed=seed)
<|code_end|>
. Use current file imports:
(import time
import pysam
import numpy as np
import logging
from itertools import chain
from mitty.lib.bedfile import read_bed
from mitty.lib.sanitizeseq import sanitize)
and context including class names, function names, or small code snippets from other files:
# Path: mitty/lib/bedfile.py
# def read_bed(bed_fname):
# return list(map(lambda x: (x[0], int(x[1]), int(x[2])), map(lambda x: x.split(), open(bed_fname, 'r').readlines())))
#
# Path: mitty/lib/sanitizeseq.py
# def sanitize(seq):
# return seq.translate(sanitable)
. Output only the next line. | for region in read_bed(bed_fname): |
Using the snippet: <|code_start|> alt[n + 1] = dna[3]
return ''.join(alt)
def ins_model(rng, region, seq, p, p_het, min_size, max_size):
"""Insertions uniformly spanning minimum and maximum lengths. Sequences are generated using a Markov chain
generator"""
pos = place_poisson_seq(rng, p, seq)
ref = [seq[x] for x in pos]
alt = [markov_chain(r, rng, l) for r, l in zip(ref, rng.randint(min_size, max_size, size=pos.shape[0]))]
gt = genotype(p_het, rng, pos.shape[0])
return [pos + region[1] + 1, ref, alt, gt]
def del_model(rng, region, seq, p, p_het, min_size, max_size):
"""Deletions uniformly spanning minimum and maximum lengths"""
pos = place_poisson_seq(rng, p, seq)
ref = [seq[x:x + l + 1] for x, l in zip(pos, rng.randint(min_size, max_size, size=pos.shape[0]))]
alt = [seq[x] for x in pos]
gt = genotype(p_het, rng, pos.shape[0])
return [pos + region[1] + 1, ref, alt, gt]
def copy_ins_model(rng, region, seq, p, p_het, min_size, max_size):
"""The `CINS` model works just like the `INS` model except the insertion sequences, instead of being
novel DNA sequences created with a Markov chain generator, are exact copies of random parts of
the input reference genome. This creates insertions that are more challenging to align to and
assemble, especially when their lengths start to exceed the template size of the sequencing
technology used.
"""
<|code_end|>
, determine the next line of code. You have imports:
import time
import pysam
import numpy as np
import logging
from itertools import chain
from mitty.lib.bedfile import read_bed
from mitty.lib.sanitizeseq import sanitize
and context (class names, function names, or code) available:
# Path: mitty/lib/bedfile.py
# def read_bed(bed_fname):
# return list(map(lambda x: (x[0], int(x[1]), int(x[2])), map(lambda x: x.split(), open(bed_fname, 'r').readlines())))
#
# Path: mitty/lib/sanitizeseq.py
# def sanitize(seq):
# return seq.translate(sanitable)
. Output only the next line. | seq = sanitize(seq) |
Predict the next line for this snippet: <|code_start|> np.random.RandomState(shuffle_seed).shuffle(region_list)
for region in region_list:
yield region
# def read_generating_worker(worker_id, fasta_fname, sample_name, read_module, read_model, in_queue, out_queue):
# for ps, wd in enumerate(iter(in_queue.get, __process_stop_code__)):
# out_queue.put([str(ps), str(wd)])
def read_generating_worker(worker_id, fasta_fname, sample_name, read_module, read_model, in_queue, out_queue):
"""This worker will be given a fasta_fname, and region information. It is to generate the node_list,
the read locations and then, finally, the reads themselves. The reads - in FASTQ format - are returned
to the parent thread for writing.
:param worker_id: Just a serial that helps us number reads uniquely
:param fasta_fname:
:param sample_name: (This is just passed to the read qname)
:param model:
:param region_idx:
:param in_queue: will be sending work information as (region_idx, cpy)
:param out_queue: We'll be sending strings representing each template in FASTQ format
:return:
"""
fasta = pysam.FastaFile(fasta_fname)
total_cnt, t00 = 0, time.time()
for ps, wd in enumerate(iter(in_queue.get, __process_stop_code__)):
r_idx, cpy, rng_seed = wd['region_idx'], wd['region_cpy'], wd['rng_seed']
region = vcf_df[r_idx]['region']
<|code_end|>
with the help of current file imports:
import time
import pysam
import numpy as np
import mitty.lib.vcfio as vio
import mitty.simulation.rpc as rpc
import logging
from multiprocessing import Process, Queue
from mitty.lib.sanitizeseq import sanitize
from mitty.simulation.sequencing.writefastq import writer
and context from other files:
# Path: mitty/lib/sanitizeseq.py
# def sanitize(seq):
# return seq.translate(sanitable)
#
# Path: mitty/simulation/sequencing/writefastq.py
# def writer(fastq1_out, side_car_out, fastq2_out=None, data_queue=None, max_qname_len=__max_qname_len__):
# """Write templates to file
#
# :param fastq1_out: Name of FASTQ1
# :param side_car_out: Name of side car file for long qnames
# :param fastq2_out: If paired end, name of FASTQ2
# :param data_queue: multiprocessing queue
# :param max_qname_len: Send qnames longer than this to the overflow file
#
# The data format is as follows:
# (
# idx, - if this is None then we create an index afresh
# sample_name,
# chrom,
# copy,
# (
# (strand, pos, cigar, (v1,v2,...), MD, seq, qual)
# ... [repeated as for as many reads in this template]
# )
# )
#
# :return:
# """
# t0 = time.time()
#
# cnt = -1
# fastq_l, side_car_fp = [open(fastq1_out, 'w')], open(side_car_out, 'w')
# if fastq2_out is not None: fastq_l += [open(fastq2_out, 'w')]
# for cnt, template in enumerate(iter(data_queue.get, __process_stop_code__)):
# # @index|sn|chrom:copy|
# qname = '@{}|{}|{}:{}|'.format(template[0] or base_repr(cnt, 36), *template[1:4])
# # strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD*
# qname += '|'.join('{}:{}:{}:{}:{}'.format(*r[:3], str(r[3])[1:-1].replace(' ', ''), r[4]) for r in template[4]) + '*'
#
# if len(qname) > max_qname_len:
# side_car_fp.write(qname + '\n')
# qname = qname[:max_qname_len]
#
# for fp, r in zip(fastq_l, template[4]):
# fp.write('{}\n{}\n+\n{}\n'.format(qname, r[5], r[6]))
#
# for fp in fastq_l:
# fp.close()
#
# t1 = time.time()
# logger.debug('Writer finished: {} templates in {:0.2f}s ({:0.2f} t/s)'.format(cnt + 1, t1 - t0, (cnt + 1) / (t1 - t0)))
, which may contain function names, class names, or code. Output only the next line. | ref_seq = sanitize(fasta.fetch(reference=region[0], start=region[1], end=region[2])) |
Given snippet: <|code_start|> :param truncate_to: If set, shorten reads to this length
:param unpair: If True, for models that produce paired-end reads, produce single end, instead
:param threads:
:param seed:
:return:
"""
if truncate_to is not None:
model['mean_rlen'] = min(truncate_to, model['mean_rlen'])
logger.debug('Truncating mean read length to: {}bp'.format(model['mean_rlen']))
if unpair:
logger.debug('Un-pairing reads')
model['unpaired'] = True
assert fastq2_fname is None, 'For unpaired reads, no FASTQ2 should be supplied'
read_model = read_module.read_model_params(model, coverage)
global vcf_df
vcf_df = vio.load_variant_file(vcf_fname, sample_name, bed_fname)
in_queue = Queue()
out_queue = Queue(10000) # This is the key to preventing workers from dying
logger.debug('Starting {} workers'.format(threads))
workers = []
for worker_id in range(threads):
p = Process(target=read_generating_worker,
args=(worker_id, fasta_fname, sample_name, read_module, read_model, in_queue, out_queue))
p.start()
workers.append(p)
logger.debug('Starting writer process')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
import pysam
import numpy as np
import mitty.lib.vcfio as vio
import mitty.simulation.rpc as rpc
import logging
from multiprocessing import Process, Queue
from mitty.lib.sanitizeseq import sanitize
from mitty.simulation.sequencing.writefastq import writer
and context:
# Path: mitty/lib/sanitizeseq.py
# def sanitize(seq):
# return seq.translate(sanitable)
#
# Path: mitty/simulation/sequencing/writefastq.py
# def writer(fastq1_out, side_car_out, fastq2_out=None, data_queue=None, max_qname_len=__max_qname_len__):
# """Write templates to file
#
# :param fastq1_out: Name of FASTQ1
# :param side_car_out: Name of side car file for long qnames
# :param fastq2_out: If paired end, name of FASTQ2
# :param data_queue: multiprocessing queue
# :param max_qname_len: Send qnames longer than this to the overflow file
#
# The data format is as follows:
# (
# idx, - if this is None then we create an index afresh
# sample_name,
# chrom,
# copy,
# (
# (strand, pos, cigar, (v1,v2,...), MD, seq, qual)
# ... [repeated as for as many reads in this template]
# )
# )
#
# :return:
# """
# t0 = time.time()
#
# cnt = -1
# fastq_l, side_car_fp = [open(fastq1_out, 'w')], open(side_car_out, 'w')
# if fastq2_out is not None: fastq_l += [open(fastq2_out, 'w')]
# for cnt, template in enumerate(iter(data_queue.get, __process_stop_code__)):
# # @index|sn|chrom:copy|
# qname = '@{}|{}|{}:{}|'.format(template[0] or base_repr(cnt, 36), *template[1:4])
# # strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD*
# qname += '|'.join('{}:{}:{}:{}:{}'.format(*r[:3], str(r[3])[1:-1].replace(' ', ''), r[4]) for r in template[4]) + '*'
#
# if len(qname) > max_qname_len:
# side_car_fp.write(qname + '\n')
# qname = qname[:max_qname_len]
#
# for fp, r in zip(fastq_l, template[4]):
# fp.write('{}\n{}\n+\n{}\n'.format(qname, r[5], r[6]))
#
# for fp in fastq_l:
# fp.close()
#
# t1 = time.time()
# logger.debug('Writer finished: {} templates in {:0.2f}s ({:0.2f} t/s)'.format(cnt + 1, t1 - t0, (cnt + 1) / (t1 - t0)))
which might include code, classes, or functions. Output only the next line. | wr = Process(target=writer, args=(fastq1_fname, sidecar_fname, fastq2_fname, out_queue)) |
Using the snippet: <|code_start|>"""Contains the logic for handling read model corruption invocation"""
logger = logging.getLogger(__name__)
SEED_MAX = (1 << 32) - 1 # Used for seeding rng
__process_stop_code__ = 'SETECASTRONOMY'
def multi_process(read_module, read_model, fastq1_in, fastq1_out, sidecar_in, sidecar_out,
fastq2_in=None, fastq2_out=None, processes=2, seed=7):
"""
:param read_module:
:param read_model:
:param fastq1_in:
:param fastq1_out:
:param sidecar_in:
:param sidecar_out:
:param fastq2_in:
:param fastq2_out:
:param processes:
:param seed:
:return:
"""
<|code_end|>
, determine the next line of code. You have imports:
from multiprocessing import Process, Queue
from mitty.simulation.sequencing.writefastq import writer, load_qname_sidecar, parse_qname
import time
import pysam
import numpy as np
import logging
and context (class names, function names, or code) available:
# Path: mitty/simulation/sequencing/writefastq.py
# def writer(fastq1_out, side_car_out, fastq2_out=None, data_queue=None, max_qname_len=__max_qname_len__):
# """Write templates to file
#
# :param fastq1_out: Name of FASTQ1
# :param side_car_out: Name of side car file for long qnames
# :param fastq2_out: If paired end, name of FASTQ2
# :param data_queue: multiprocessing queue
# :param max_qname_len: Send qnames longer than this to the overflow file
#
# The data format is as follows:
# (
# idx, - if this is None then we create an index afresh
# sample_name,
# chrom,
# copy,
# (
# (strand, pos, cigar, (v1,v2,...), MD, seq, qual)
# ... [repeated as for as many reads in this template]
# )
# )
#
# :return:
# """
# t0 = time.time()
#
# cnt = -1
# fastq_l, side_car_fp = [open(fastq1_out, 'w')], open(side_car_out, 'w')
# if fastq2_out is not None: fastq_l += [open(fastq2_out, 'w')]
# for cnt, template in enumerate(iter(data_queue.get, __process_stop_code__)):
# # @index|sn|chrom:copy|
# qname = '@{}|{}|{}:{}|'.format(template[0] or base_repr(cnt, 36), *template[1:4])
# # strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD*
# qname += '|'.join('{}:{}:{}:{}:{}'.format(*r[:3], str(r[3])[1:-1].replace(' ', ''), r[4]) for r in template[4]) + '*'
#
# if len(qname) > max_qname_len:
# side_car_fp.write(qname + '\n')
# qname = qname[:max_qname_len]
#
# for fp, r in zip(fastq_l, template[4]):
# fp.write('{}\n{}\n+\n{}\n'.format(qname, r[5], r[6]))
#
# for fp in fastq_l:
# fp.close()
#
# t1 = time.time()
# logger.debug('Writer finished: {} templates in {:0.2f}s ({:0.2f} t/s)'.format(cnt + 1, t1 - t0, (cnt + 1) / (t1 - t0)))
#
# def load_qname_sidecar(sidecar_fn):
# def parse_sidecar_file(_fn):
# with open(_fn, 'r') as fp:
# for ln in fp:
# yield ln.split('|', 1)[0][1:], ln[1:-1]
# return {
# k: v
# for k, v in parse_sidecar_file(sidecar_fn)
# }
#
# def parse_qname(qname, long_qname_table=None):
# """Given a Mitty qname return us the POS and CIGAR as we would put in a BAM. There is also a special_cigar
# which is set for reads completely inside long insertions
#
# @index|sn|chrom:copy|strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD*
#
# :param qname:
# :param long_qname_table: If present, is a map of qname index and qname for just the long qnames
# :return: pos, cigar, special_cigar
# """
# def _parse_(_cigar, _v_list):
# """
# Parse cigar to extract special_cigar if needed
# Parse v_list
#
# :param _cigar:
# :param _v_list:
# :return:
# """
# if _cigar[0] == '>': # This is a special_cigar for a read from inside an insertion
# _special_cigar = _cigar
# _cigar = _cigar.split('+')[-1]
# else:
# _special_cigar = None
#
# return _cigar, _special_cigar, [int(v) for v in _v_list.split(',') if v is not '']
#
# def _split_(_r):
# strand, pos, cigar, v_list, md = _r.split(':')
# return (int(strand), int(pos)) + _parse_(cigar, v_list) + (md,)
#
# if qname[-1] != '*': # Truncated qname
# if long_qname_table is None:
# raise ValueError('Long qname with no table lookup') # It's the caller's responsibility to handle this error
# _qname = long_qname_table.get(qname.split('|', 1)[0], None)
# if _qname is None:
# raise ValueError('Long qname with no table lookup: {}, {}'.format(qname.split('|', 1)[0], qname))
# # It's the caller's responsibility to handle this error
# qname = _qname
#
# d = qname[:-1].split('|') # Strip out the terminal '*'
# serial, sample = d[:2]
# chrom, cpy = d[2].split(':')
# cpy = int(cpy)
# return [
# ri(serial, sample, chrom, cpy, *_split_(r))
# for r in d[3:]
# ]
. Output only the next line. | long_qname_table = load_qname_sidecar(sidecar_in) |
Given the code snippet: <|code_start|> def __init__(self, pos, ref, alt, cigarop, oplen):
self.pos = pos
self.ref = ref
self.alt = alt
self.cigarop = cigarop
self.oplen = oplen
def tuple(self):
return self.pos, self.ref, self.alt, self.cigarop, self.oplen
def __repr__(self):
return self.tuple().__repr__()
# Unphased variants always go into chrom copy 0|1
# We get results in the form of a ploid_bed
def load_variant_file(fname, sample, bed_fname):
"""Use pysam to read in a VCF file and convert it into a form suitable for use in Mitty
:param fname:
:param sample:
:return: dict of numpy recarrays
"""
mode = 'rb' if fname.endswith('bcf') else 'r'
vcf_fp = pysam.VariantFile(fname, mode)
vcf_fp.subset_samples([sample])
return [
split_copies(region,
[v for v in vcf_fp.fetch(contig=region[0], start=region[1], stop=region[2])],
sniff_ploidy(vcf_fp, region[0]))
<|code_end|>
, generate the next line using the imports in this file:
import logging
import time
import pysam
from mitty.lib.bedfile import read_bed
and context (functions, classes, or occasionally code) from other files:
# Path: mitty/lib/bedfile.py
# def read_bed(bed_fname):
# return list(map(lambda x: (x[0], int(x[1]), int(x[2])), map(lambda x: x.split(), open(bed_fname, 'r').readlines())))
. Output only the next line. | for region in read_bed(bed_fname) |
Continue the code snippet: <|code_start|>"""Given a FASTQ (or BAM) and a long-qnames file trancate the qnames to
whatever length we want and push the too-long qnames to the overflow
file. Also convert any old style qnames (not ending in a *) to new style
ones with a proper termination character"""
logger = logging.getLogger(__name__)
def main(mainfile_in, sidecar_in, mainfile_out, sidecar_out, truncate_to=240, file_type=None):
"""
:param mainfile_in:
:param sidecar_in:
:param mainfile_out:
:param sidecar_out:
:param truncate_to:
:param file_type: If supplied ("BAM" or "FASTQ") then we will not auto detect
:return:
"""
ft = {
'BAM': 1,
'FASTQ': 0
}.get(file_type or auto_detect(mainfile_in))
fp_in = pysam.AlignmentFile(mainfile_in, mode='rb') if ft else pysam.FastxFile(mainfile_in)
fp_out = pysam.AlignmentFile(mainfile_out, mode='wb', header=fp_in.header) if ft else open(mainfile_out, 'w')
side_car_fp = open(sidecar_out, 'w')
logger.debug('Starting conversion ...')
<|code_end|>
. Use current file imports:
import time
import logging
import pysam
from mitty.benchmarking.alignmentscore import load_qname_sidecar
and context (classes, functions, or code) from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | long_qname_table = load_qname_sidecar(sidecar_in) |
Next line prediction: <|code_start|>"""Code for assessing alignment accuracy"""
# good to have these together. Code that uses score_alignment_error is very likely to use
# ri, load_qname_sidecar and parse_qname
cigar_parser = re.compile(r'(\d+)(\D)')
def is_simple_case(cigar1, cigar2):
_, _, op1, _ = cigar_parser.split(cigar1, maxsplit=1)
_, _, op2, _ = cigar_parser.split(cigar2, maxsplit=1)
return op1 in ['=', 'M', 'X'] and op2 in ['M', 'X', '=']
def find_first_common_reference_matching_base_positions(r1, r2):
return next(
filter(
lambda x: x[0] is not None and x[1] is not None,
zip(r1.get_reference_positions(full_length=True),
r2.get_reference_positions(full_length=True))),
(None, None))
<|code_end|>
. Use current file imports:
(import re
import pysam
from mitty.simulation.sequencing.writefastq import ri, load_qname_sidecar, parse_qname
from mitty.lib.cigars import cigarv2_v1)
and context including class names, function names, or small code snippets from other files:
# Path: mitty/simulation/sequencing/writefastq.py
# def writer(fastq1_out, side_car_out, fastq2_out=None, data_queue=None, max_qname_len=__max_qname_len__):
# def parse_qname(qname, long_qname_table=None):
# def _parse_(_cigar, _v_list):
# def _split_(_r):
# def load_qname_sidecar(sidecar_fn):
# def parse_sidecar_file(_fn):
#
# Path: mitty/lib/cigars.py
# def cigarv2_v1(cigar_v2):
# """Convert a V2 cigar_v1 string to V1
#
# :param cigarstring:
# :return:
# """
# values = pattern.split(cigar_v2.replace('=', 'M').replace('X', 'M'))
# cigar_v1 = []
# last_op, op_cnt = values[1], 0
# for op in zip(values[::2], values[1::2]):
# if op[1] == last_op:
# op_cnt += int(op[0])
# else:
# cigar_v1 += [str(op_cnt), last_op]
# last_op, op_cnt = op[1], int(op[0])
# cigar_v1 += [str(op_cnt), last_op]
# return ''.join(cigar_v1)
. Output only the next line. | def score_alignment_error(r, ri, max_d=200, strict=False): |
Given the code snippet: <|code_start|>
If strict is True: Look at the distance between the simulated P and the aligned P
If strict is False:
If from inside an insertion, treat like strict
Else, find the first base in the read that is placed on the reference for both the
aligned and correct reads and compute the difference
If there is no such base, treat like strict
Look at the aligned CIGAR and compute the difference between exact P and
aligned P after accounting for any soft clip at the start of the read
:param r: aligned read
:param ri: readinfo for correct alignment
:param strict: If True, simply compute difference between simulated P and aligned P
if False, find first common reference matching base
:return: -max_d <= d_err <= max_d + 2
d_err = max_d + 1 if wrong chrom
d_err = max_d + 2 if unmapped
"""
if r.is_unmapped:
d_err = max_d + 2
elif r.reference_name != ri.chrom:
d_err = max_d + 1
else:
# This is what we score against when we are 'strict' or inside an insertion
# Or we can't find a common reference matching base in the correct and aligned reads
correct_pos, aligned_pos = ri.pos - 1, r.pos
# If we are not strict AND not in an insertion we use first common reference matching base
if not strict and ri.special_cigar is None and not is_simple_case(ri.cigar, r.cigarstring):
rc = pysam.AlignedSegment()
<|code_end|>
, generate the next line using the imports in this file:
import re
import pysam
from mitty.simulation.sequencing.writefastq import ri, load_qname_sidecar, parse_qname
from mitty.lib.cigars import cigarv2_v1
and context (functions, classes, or occasionally code) from other files:
# Path: mitty/simulation/sequencing/writefastq.py
# def writer(fastq1_out, side_car_out, fastq2_out=None, data_queue=None, max_qname_len=__max_qname_len__):
# def parse_qname(qname, long_qname_table=None):
# def _parse_(_cigar, _v_list):
# def _split_(_r):
# def load_qname_sidecar(sidecar_fn):
# def parse_sidecar_file(_fn):
#
# Path: mitty/lib/cigars.py
# def cigarv2_v1(cigar_v2):
# """Convert a V2 cigar_v1 string to V1
#
# :param cigarstring:
# :return:
# """
# values = pattern.split(cigar_v2.replace('=', 'M').replace('X', 'M'))
# cigar_v1 = []
# last_op, op_cnt = values[1], 0
# for op in zip(values[::2], values[1::2]):
# if op[1] == last_op:
# op_cnt += int(op[0])
# else:
# cigar_v1 += [str(op_cnt), last_op]
# last_op, op_cnt = op[1], int(op[0])
# cigar_v1 += [str(op_cnt), last_op]
# return ''.join(cigar_v1)
. Output only the next line. | rc.pos, rc.cigarstring = ri.pos - 1, cigarv2_v1(ri.cigar) |
Given the following code snippet before the placeholder: <|code_start|> """
hdr = vcf_fp.header.copy()
for k in hdr.info.keys():
if k != 'Regions':
hdr.info.remove_header(k)
for k in hdr.formats.keys():
if k != 'GT':
hdr.formats.remove_header(k)
hdr_lines = str(hdr).splitlines(keepends=True)
column_line = '\t'.join(hdr_lines[-1].split('\t')[:-2] + partition_list()) # Add the 12 samples
hdr_lines[-1] = '##INFO=<ID=Vtype,Number=1,Type=String,Description="High-level variant type (SNP|INDEL).">\n'
hdr_lines += [column_line]
out_fp.writelines(hdr_lines)
def partition_count_dict():
return {
k: {vtype: 0 for vtype in ['SNP', 'INDEL']}
for k in partition_list()
}
def variant_hash(v, alt):
return '{}.{}.{}.{}'.format(v.chrom, v.pos, v.ref, alt)
def process_v(v):
<|code_end|>
, predict the next line using imports from the current file:
import time
import numpy as np
import pysam
import logging
from mitty.lib.evcfparse import parse_line
and context including class names, function names, and sometimes code from other files:
# Path: mitty/lib/evcfparse.py
# def parse_line(v):
# """Given a variant (line) from the VCF categorize it as a TP, FP, FN or GT
#
# :param v:
# :return: (category,
# size)
# """
# t, q = v.samples['TRUTH'], v.samples['QUERY']
# cat = cat_dict.get(t['BD'] + q['BD'], None)
# if cat is not None and cat is not 'skip':
# alt = alt_dict[cat](t, q)
# sz = len(alt) - len(v.ref)
# else:
# alt, sz = None, None
#
# return cat, sz, alt
. Output only the next line. | cat, sz, alt = parse_line(v) if v is not None else (None, None, None) |
Using the snippet: <|code_start|>
def test_shannon():
"""complexity : Test shannon entropy for different k-mers"""
for k in range(1, 6):
se = ShannonEntropy(k=k)
assert se.complexity(de_bruijn('ACTG', k)) == 2 * k
def test_lc():
"""complexity : Lingusitic complexity for de Bruijn sequences"""
<|code_end|>
, determine the next line of code. You have imports:
from mitty.benchmarking.complexity import ShannonEntropy, LinguisticComplexity, de_bruijn
and context (class names, function names, or code) available:
# Path: mitty/benchmarking/complexity.py
# class ShannonEntropy:
# """Computes Shannon Entropy of k-mers in given sequence. Initialize with value of k.
# Shannon entropy of a sequence ranges from >0 to 4**k)
# """
# def __init__(self, k=1):
# self.k = k
# self.alphabet = list(dna_alphabet(k=k))
#
# def header_info(self):
# """Return a list of elements that should be added to the VCF header so:
#
# vcf_in.header.info.add(*se.header_info())
# """
# return 'SE{}'.format(self.k), 1, 'Float', '{}-mer Shannon entropy for the local region around the variant'.format(self.k)
#
# def complexity(self, s, **kwargs):
# l = len(s) - self.k + 1
# p = [s.count(a) / l for a in self.alphabet]
# return sum(- px * np.log2(max(px, 1e-6)) for px in p)
#
# class LinguisticComplexity:
# """Computes linguistic complexity"""
# @staticmethod
# def header_info():
# """Return a list of elements that should be added to the VCF header so:
#
# vcf_in.header.info.add(*lc.header_info())
# """
# return 'LC', 1, 'Float', 'Linguistic complexity of local sequence'
#
# @staticmethod
# def complexity(s, **kwargs):
# """Compute the linguistic complexity of sequence s
#
# :param s:
# :return:
# """
# num, den = 1, 1
# for k in range(1, len(s)):
# k4 = 4**k # For DNA
# num += min(len(set(s[i:i+k] for i in range(len(s) - k + 1))), k4)
# den += min(len(s) - k + 1, k4)
# return num / den
#
# def de_bruijn(k, n):
# """
# de Bruijn sequence for alphabet k
# and subsequences of length n.
# """
# alphabet = k
# k = len(k)
#
# a = [0] * k * n
# sequence = []
#
# def db(t, p):
# if t > n:
# if n % p == 0:
# sequence.extend(a[1:p + 1])
# else:
# a[t] = a[t - p]
# db(t + 1, p)
# for j in range(a[t - p] + 1, k):
# a[t] = j
# db(t + 1, t)
#
# db(1, 1)
# sequence.extend(sequence[:n - 1])
#
# return "".join(alphabet[i] for i in sequence)
. Output only the next line. | lc = LinguisticComplexity() |
Given the following code snippet before the placeholder: <|code_start|>
def test_shannon():
"""complexity : Test shannon entropy for different k-mers"""
for k in range(1, 6):
se = ShannonEntropy(k=k)
<|code_end|>
, predict the next line using imports from the current file:
from mitty.benchmarking.complexity import ShannonEntropy, LinguisticComplexity, de_bruijn
and context including class names, function names, and sometimes code from other files:
# Path: mitty/benchmarking/complexity.py
# class ShannonEntropy:
# """Computes Shannon Entropy of k-mers in given sequence. Initialize with value of k.
# Shannon entropy of a sequence ranges from >0 to 4**k)
# """
# def __init__(self, k=1):
# self.k = k
# self.alphabet = list(dna_alphabet(k=k))
#
# def header_info(self):
# """Return a list of elements that should be added to the VCF header so:
#
# vcf_in.header.info.add(*se.header_info())
# """
# return 'SE{}'.format(self.k), 1, 'Float', '{}-mer Shannon entropy for the local region around the variant'.format(self.k)
#
# def complexity(self, s, **kwargs):
# l = len(s) - self.k + 1
# p = [s.count(a) / l for a in self.alphabet]
# return sum(- px * np.log2(max(px, 1e-6)) for px in p)
#
# class LinguisticComplexity:
# """Computes linguistic complexity"""
# @staticmethod
# def header_info():
# """Return a list of elements that should be added to the VCF header so:
#
# vcf_in.header.info.add(*lc.header_info())
# """
# return 'LC', 1, 'Float', 'Linguistic complexity of local sequence'
#
# @staticmethod
# def complexity(s, **kwargs):
# """Compute the linguistic complexity of sequence s
#
# :param s:
# :return:
# """
# num, den = 1, 1
# for k in range(1, len(s)):
# k4 = 4**k # For DNA
# num += min(len(set(s[i:i+k] for i in range(len(s) - k + 1))), k4)
# den += min(len(s) - k + 1, k4)
# return num / den
#
# def de_bruijn(k, n):
# """
# de Bruijn sequence for alphabet k
# and subsequences of length n.
# """
# alphabet = k
# k = len(k)
#
# a = [0] * k * n
# sequence = []
#
# def db(t, p):
# if t > n:
# if n % p == 0:
# sequence.extend(a[1:p + 1])
# else:
# a[t] = a[t - p]
# db(t + 1, p)
# for j in range(a[t - p] + 1, k):
# a[t] = j
# db(t + 1, t)
#
# db(1, 1)
# sequence.extend(sequence[:n - 1])
#
# return "".join(alphabet[i] for i in sequence)
. Output only the next line. | assert se.complexity(de_bruijn('ACTG', k)) == 2 * k |
Next line prediction: <|code_start|>
:param titer:
:return:
"""
long_qname_table = load_qname_sidecar(sidecar_fname) if sidecar_fname is not None else None
for template in titer:
ri = parse_qname(
template[0].qname,
long_qname_table=long_qname_table
) if long_qname_table is not None else [None, None]
yield tuple(
{
'read': mate,
'read_info': ri[1 if mate.is_read2 else 0]
}
for mate in template
)
@cytoolz.curry
def compute_derr(titer, max_d=200):
"""Mutates dictionary: adds d_err field to it. Requires qname parsing step
:param max_d:
:param riter:
:return:
"""
for template in titer:
for mate in template:
<|code_end|>
. Use current file imports:
(import tempfile
import logging
import cytoolz
import numpy as np
import pysam
import pandas as pd
import xarray as xr
from collections import OrderedDict, Counter
from mitty.benchmarking.alignmentscore import score_alignment_error, correct_tlen, load_qname_sidecar, parse_qname)
and context including class names, function names, or small code snippets from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | mate['d_err'] = score_alignment_error(r=mate['read'], ri=mate['read_info'], max_d=max_d) |
Given the code snippet: <|code_start|>"""
Supplies primitives for streaming (filter based) analysis of BAMs produced from simulated data.
"""
logger = logging.getLogger(__name__)
@cytoolz.curry
def parse_read_qnames(sidecar_fname, titer):
"""Mutates dictionary: adds 'read_info' field to it.
:param titer:
:return:
"""
<|code_end|>
, generate the next line using the imports in this file:
import tempfile
import logging
import cytoolz
import numpy as np
import pysam
import pandas as pd
import xarray as xr
from collections import OrderedDict, Counter
from mitty.benchmarking.alignmentscore import score_alignment_error, correct_tlen, load_qname_sidecar, parse_qname
and context (functions, classes, or occasionally code) from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | long_qname_table = load_qname_sidecar(sidecar_fname) if sidecar_fname is not None else None |
Based on the snippet: <|code_start|>"""
Supplies primitives for streaming (filter based) analysis of BAMs produced from simulated data.
"""
logger = logging.getLogger(__name__)
@cytoolz.curry
def parse_read_qnames(sidecar_fname, titer):
"""Mutates dictionary: adds 'read_info' field to it.
:param titer:
:return:
"""
long_qname_table = load_qname_sidecar(sidecar_fname) if sidecar_fname is not None else None
for template in titer:
<|code_end|>
, predict the immediate next line with the help of imports:
import tempfile
import logging
import cytoolz
import numpy as np
import pysam
import pandas as pd
import xarray as xr
from collections import OrderedDict, Counter
from mitty.benchmarking.alignmentscore import score_alignment_error, correct_tlen, load_qname_sidecar, parse_qname
and context (classes, functions, sometimes code) from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | ri = parse_qname( |
Based on the snippet: <|code_start|> mode = 'rb' if evcf_fname.endswith('bcf') else 'r'
vcf_in = pysam.VariantFile(evcf_fname, mode)
for v in vcf_in:
if high_confidence_region is not None and high_confidence_region not in v.info.get('Regions', []):
continue
c, s, _ = parse_line(v)
if c is None:
print(v)
elif c is not 'skip':
data[c][min(max_n, max(0, offset + s))] += 1
np.savetxt(out_csv_fname, data, fmt='%d', delimiter=', ', header='TP, FN, GT, FP')
return data
# Ignoring bin size for now
def plot(data, fig_fname, bin_size=5, plot_range=None, title='P/R by variant size'):
max_size = int((data.shape[0] - 3)/2)
if plot_range is not None and plot_range < max_size:
n0, n1 = max_size + 1 - (plot_range + 1), max_size + 1 + (plot_range + 1) + 1
_data = data[n0:n1]
for k in data.dtype.names:
_data[0][k] = data[:n0][k].sum()
_data[-1][k] = data[n1:][k].sum()
data = _data
fig = plt.figure(figsize=(6, 11))
plt.subplots_adjust(bottom=0.05, top=0.95, hspace=0.01)
ax1 = plt.subplot(411)
<|code_end|>
, predict the immediate next line with the help of imports:
import matplotlib
import numpy as np
import pysam
import matplotlib.pyplot as plt
from mitty.benchmarking.plot.byvsize import plot_panels
from mitty.lib.evcfparse import parse_line
and context (classes, functions, sometimes code) from other files:
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
# color='k', linestyle='-', label='',
# yscale='linear', yticks=None, ylim=None, show_ax_label=False,
# ci=0.05):
# """Interpret y (an array of length 2 * N + 3) as follows:
# The indexes represent variant sizes from
#
# DEL len > N
# DEL len from N to 1
# SNPs
# INS len from 1 to N
# INS len > N
#
# :param ax:
# :param y: success rate
# :param cnt: number of counts in bin
# :param color:
# :param linestyle:
# :param label:
# :param yscale:
# :param yticks:
# :param ylim:
# :param show_ax_label:
# :return:
# """
# parts = bin_data_by_variant_size(num, den, bin_size)
# x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
# x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
# xticks, xticklabels = [], []
# for part in parts:
# line_with_ci(ax, part, color=color, linestyle=linestyle)
# xticks += part['xticks']
# xticklabels += part['xticklabels']
#
# # The fixed reference lines
# ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
#
# ax.set_xticks(xticks)
# ax.set_xticklabels(xticklabels if show_ax_label else [])
#
# ax.set_yscale(yscale)
# if yticks is not None:
# ax.set_yticks(yticks)
# if ylim is not None:
# ax.set_ylim(ylim)
# ax.get_yaxis().get_major_formatter().labelOnlyBase = False
# ax.set_xlim(x_lim)
#
# return mpatches.Patch(color=color, linestyle=linestyle, label=label) # patch_for_legend
#
# Path: mitty/lib/evcfparse.py
# def parse_line(v):
# """Given a variant (line) from the VCF categorize it as a TP, FP, FN or GT
#
# :param v:
# :return: (category,
# size)
# """
# t, q = v.samples['TRUTH'], v.samples['QUERY']
# cat = cat_dict.get(t['BD'] + q['BD'], None)
# if cat is not None and cat is not 'skip':
# alt = alt_dict[cat](t, q)
# sz = len(alt) - len(v.ref)
# else:
# alt, sz = None, None
#
# return cat, sz, alt
. Output only the next line. | r_p = plot_panels(ax1, |
Using the snippet: <|code_start|>"""Code to characterize the TP, FN and FP (and hence P/R) by variant size."""
matplotlib.use('Agg')
def main(evcf_fname, out_csv_fname, max_size=50, high_confidence_region=None):
data = np.zeros(shape=(2 * max_size + 1 + 2), dtype=[('TP', int), ('FN', int), ('GT', int), ('FP', int)])
offset, max_n = max_size + 1, 2 * max_size + 2
mode = 'rb' if evcf_fname.endswith('bcf') else 'r'
vcf_in = pysam.VariantFile(evcf_fname, mode)
for v in vcf_in:
if high_confidence_region is not None and high_confidence_region not in v.info.get('Regions', []):
continue
<|code_end|>
, determine the next line of code. You have imports:
import matplotlib
import numpy as np
import pysam
import matplotlib.pyplot as plt
from mitty.benchmarking.plot.byvsize import plot_panels
from mitty.lib.evcfparse import parse_line
and context (class names, function names, or code) available:
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
# color='k', linestyle='-', label='',
# yscale='linear', yticks=None, ylim=None, show_ax_label=False,
# ci=0.05):
# """Interpret y (an array of length 2 * N + 3) as follows:
# The indexes represent variant sizes from
#
# DEL len > N
# DEL len from N to 1
# SNPs
# INS len from 1 to N
# INS len > N
#
# :param ax:
# :param y: success rate
# :param cnt: number of counts in bin
# :param color:
# :param linestyle:
# :param label:
# :param yscale:
# :param yticks:
# :param ylim:
# :param show_ax_label:
# :return:
# """
# parts = bin_data_by_variant_size(num, den, bin_size)
# x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
# x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
# xticks, xticklabels = [], []
# for part in parts:
# line_with_ci(ax, part, color=color, linestyle=linestyle)
# xticks += part['xticks']
# xticklabels += part['xticklabels']
#
# # The fixed reference lines
# ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
#
# ax.set_xticks(xticks)
# ax.set_xticklabels(xticklabels if show_ax_label else [])
#
# ax.set_yscale(yscale)
# if yticks is not None:
# ax.set_yticks(yticks)
# if ylim is not None:
# ax.set_ylim(ylim)
# ax.get_yaxis().get_major_formatter().labelOnlyBase = False
# ax.set_xlim(x_lim)
#
# return mpatches.Patch(color=color, linestyle=linestyle, label=label) # patch_for_legend
#
# Path: mitty/lib/evcfparse.py
# def parse_line(v):
# """Given a variant (line) from the VCF categorize it as a TP, FP, FN or GT
#
# :param v:
# :return: (category,
# size)
# """
# t, q = v.samples['TRUTH'], v.samples['QUERY']
# cat = cat_dict.get(t['BD'] + q['BD'], None)
# if cat is not None and cat is not 'skip':
# alt = alt_dict[cat](t, q)
# sz = len(alt) - len(v.ref)
# else:
# alt, sz = None, None
#
# return cat, sz, alt
. Output only the next line. | c, s, _ = parse_line(v) |
Continue the code snippet: <|code_start|> def _finalize():
"""given a buffer of data bin it into the histogram
"""
for pah in aah:
pah.data += fastmultihist(buf[:idx, :], pah.attrs['bin_edges'])
assert histogram_def is not None, 'Histogram definition must be passed'
if not isinstance(histogram_def, (list, tuple)):
histogram_def = (histogram_def, )
aah = [initialize_histogram(**hd) for hd in histogram_def]
max_d_set = set(a.attrs['max_d'] for a in aah)
max_v_set = set(a.attrs['max_v'] for a in aah if a.attrs['max_v'] is not None)
max_d = max_d_set.pop()
max_v = max_v_set.pop() or 1 # We could have a case where we never bin by the max_v
if len(max_d_set) > 0:
raise RuntimeError('max_d for each histogram has to be the same')
if len(max_v_set) > 0:
raise RuntimeError('max_v for each histogram has to be the same')
temp_read = pysam.AlignedSegment()
bs = buf_size
buf = np.empty(shape=(bs, 8))
idx = 0
for tpl in titer:
# For efficiency this assumes we have PE reads and have paired them up using make_pairs
<|code_end|>
. Use current file imports:
from collections import OrderedDict, Counter
from mitty.benchmarking.alignmentscore import score_alignment_error, correct_tlen, load_qname_sidecar, parse_qname
import logging
import cytoolz
import numpy as np
import pysam
import xarray as xr
and context (classes, functions, or code) from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | ctl = correct_tlen(tpl[0]['read_info'], tpl[1]['read_info'], temp_read) |
Given the following code snippet before the placeholder: <|code_start|>
:param bam_fname:
:param sidecar_fname:
:param out_fname:
:param d_range:
:param reject_d_range:
:param v_range:
:param reject_v_range:
:param reject_reads_with_variants:
:param reject_reference_reads:
:param strict_scoring:
:param do_not_index:
:param processes:
:return:
"""
def _filter_pass(_r):
"""
:param _r:
:return: T/F, d_err
"""
ri = parse_qname(_r.qname, long_qname_table=long_qname_table)[1 if _r.is_read2 else 0]
is_ref_read = len(ri.v_list) == 0
if is_ref_read and reject_reference_reads:
return False, 0
if not is_ref_read and reject_reads_with_variants:
return False, 0
<|code_end|>
, predict the next line using imports from the current file:
import time
import logging
import os
import pysam
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname
and context including class names, function names, and sometimes code from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | _d_err = score_alignment_error(_r, ri=ri, max_d=max_d, strict=strict_scoring) |
Next line prediction: <|code_start|> def _filter_pass(_r):
"""
:param _r:
:return: T/F, d_err
"""
ri = parse_qname(_r.qname, long_qname_table=long_qname_table)[1 if _r.is_read2 else 0]
is_ref_read = len(ri.v_list) == 0
if is_ref_read and reject_reference_reads:
return False, 0
if not is_ref_read and reject_reads_with_variants:
return False, 0
_d_err = score_alignment_error(_r, ri=ri, max_d=max_d, strict=strict_scoring)
in_d_err_range = d_range[0] <= _d_err <= d_range[1]
if in_d_err_range == reject_d_range:
return False, 0
if not is_ref_read:
# All variants are inside/outside v_range and we want to/do not want to reject the range
if all((v_range[0] <= v <= v_range[1]) == reject_v_range for v in ri.v_list):
return False, 0
return True, _d_err
se_bam = is_single_end_bam(bam_fname)
bam_fp = pysam.AlignmentFile(bam_fname)
<|code_end|>
. Use current file imports:
(import time
import logging
import os
import pysam
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname)
and context including class names, function names, or small code snippets from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | long_qname_table = load_qname_sidecar(sidecar_fname) |
Here is a snippet: <|code_start|>
def main(bam_fname, sidecar_fname, out_fname,
d_range=(-200, 200), reject_d_range=False,
v_range=(-200, 200), reject_v_range=False,
reject_reads_with_variants=False,
reject_reference_reads=False,
strict_scoring=False, do_not_index=True, processes=2):
"""This function extracts reads from a simulation BAM that match the filter critera
:param bam_fname:
:param sidecar_fname:
:param out_fname:
:param d_range:
:param reject_d_range:
:param v_range:
:param reject_v_range:
:param reject_reads_with_variants:
:param reject_reference_reads:
:param strict_scoring:
:param do_not_index:
:param processes:
:return:
"""
def _filter_pass(_r):
"""
:param _r:
:return: T/F, d_err
"""
<|code_end|>
. Write the next line using the current file imports:
import time
import logging
import os
import pysam
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname
and context from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
, which may include functions, classes, or code. Output only the next line. | ri = parse_qname(_r.qname, long_qname_table=long_qname_table)[1 if _r.is_read2 else 0] |
Given the code snippet: <|code_start|>
def test_ref_matching_base():
"""d-err: Find first reference matching base positions"""
test_cases = [
((100, '100M'), (130, '30S70M')),
((100, '10I90M'), (100, '10S90M')),
((100, '10I10M10I70M'), (110, '30S70M')),
((100, '10M1000D90M'), (1110, '10S90M')),
((100, '10M1000D90M'), (1120, '20S90M')),
((100, '10M1000D80M10I'), (1120, '20S80M10S')),
((1000686, '96S154M'), (1000590, '250M')),
]
for tc1, tc2 in test_cases:
r1, r2 = pysam.AlignedSegment(), pysam.AlignedSegment()
r1.pos, r1.cigarstring = tc1[0], tc1[1]
r2.pos, r2.cigarstring = tc2[0], tc2[1]
<|code_end|>
, generate the next line using the imports in this file:
from mitty.benchmarking.alignmentscore import find_first_common_reference_matching_base_positions, pysam
and context (functions, classes, or occasionally code) from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | p1, p2 = find_first_common_reference_matching_base_positions(r1, r2) |
Given the following code snippet before the placeholder: <|code_start|>
def test_ref_matching_base():
"""d-err: Find first reference matching base positions"""
test_cases = [
((100, '100M'), (130, '30S70M')),
((100, '10I90M'), (100, '10S90M')),
((100, '10I10M10I70M'), (110, '30S70M')),
((100, '10M1000D90M'), (1110, '10S90M')),
((100, '10M1000D90M'), (1120, '20S90M')),
((100, '10M1000D80M10I'), (1120, '20S80M10S')),
((1000686, '96S154M'), (1000590, '250M')),
]
for tc1, tc2 in test_cases:
<|code_end|>
, predict the next line using imports from the current file:
from mitty.benchmarking.alignmentscore import find_first_common_reference_matching_base_positions, pysam
and context including class names, function names, and sometimes code from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | r1, r2 = pysam.AlignedSegment(), pysam.AlignedSegment() |
Given the following code snippet before the placeholder: <|code_start|> os.remove(bam_fname)
t1 = time.time()
logger.debug('... {:0.2f}s'.format(t1 - t0))
logger.debug('Shutting down thread for {}'.format(bam_fname))
def write_perfect_reads(qname, rg_id, long_qname_table, ref_dict, read_data, cigar_v2,
fp):
"""Given reads begining to a template, write out the perfect alignments to file
:param qname:
:param rg_id:
:param long_qname_table:
:param ref_dict: dict containing reference names mapped to ref_id
:param read_data: [x1, x2, ... ] where xi is (seq, qual)
and, e.g. [x1, x2] constitute a pair, if the input is paired end
:param cigar_v2: output CIGARs in V2 format
:param fp: pysam file pointer to write out
:return:
"""
reads = [
pysam.AlignedSegment()
for _ in range(len(read_data))
]
for n, (ri, rd, read) in enumerate(zip(parse_qname(qname, long_qname_table), read_data, reads)):
read.qname = qname
read.reference_id = ref_dict[ri.chrom]
read.pos = ri.pos - 1
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os
import sys
import time
import pysam
from multiprocessing import Process, Queue
from mitty.lib.cigars import cigarv2_v1
from mitty.simulation.readgenerate import DNA_complement
from mitty.simulation.sequencing.writefastq import load_qname_sidecar, parse_qname
from mitty.version import __version__
and context including class names, function names, and sometimes code from other files:
# Path: mitty/lib/cigars.py
# def cigarv2_v1(cigar_v2):
# """Convert a V2 cigar_v1 string to V1
#
# :param cigarstring:
# :return:
# """
# values = pattern.split(cigar_v2.replace('=', 'M').replace('X', 'M'))
# cigar_v1 = []
# last_op, op_cnt = values[1], 0
# for op in zip(values[::2], values[1::2]):
# if op[1] == last_op:
# op_cnt += int(op[0])
# else:
# cigar_v1 += [str(op_cnt), last_op]
# last_op, op_cnt = op[1], int(op[0])
# cigar_v1 += [str(op_cnt), last_op]
# return ''.join(cigar_v1)
#
# Path: mitty/simulation/readgenerate.py
# SEED_MAX = (1 << 32) - 1 # Used for seeding rng
# def process_multi_threaded(fasta_fname, vcf_fname, sample_name, bed_fname,
# read_module, model, coverage,
# fastq1_fname, sidecar_fname, fastq2_fname,
# truncate_to=None,
# unpair=False,
# threads=2, seed=7):
# def get_data_for_workers(model, vcf, seed):
# def read_generating_worker(worker_id, fasta_fname, sample_name, read_module, read_model, in_queue, out_queue):
# def validate_templates_from_read_model(tplt):
#
# Path: mitty/simulation/sequencing/writefastq.py
# def load_qname_sidecar(sidecar_fn):
# def parse_sidecar_file(_fn):
# with open(_fn, 'r') as fp:
# for ln in fp:
# yield ln.split('|', 1)[0][1:], ln[1:-1]
# return {
# k: v
# for k, v in parse_sidecar_file(sidecar_fn)
# }
#
# def parse_qname(qname, long_qname_table=None):
# """Given a Mitty qname return us the POS and CIGAR as we would put in a BAM. There is also a special_cigar
# which is set for reads completely inside long insertions
#
# @index|sn|chrom:copy|strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD*
#
# :param qname:
# :param long_qname_table: If present, is a map of qname index and qname for just the long qnames
# :return: pos, cigar, special_cigar
# """
# def _parse_(_cigar, _v_list):
# """
# Parse cigar to extract special_cigar if needed
# Parse v_list
#
# :param _cigar:
# :param _v_list:
# :return:
# """
# if _cigar[0] == '>': # This is a special_cigar for a read from inside an insertion
# _special_cigar = _cigar
# _cigar = _cigar.split('+')[-1]
# else:
# _special_cigar = None
#
# return _cigar, _special_cigar, [int(v) for v in _v_list.split(',') if v is not '']
#
# def _split_(_r):
# strand, pos, cigar, v_list, md = _r.split(':')
# return (int(strand), int(pos)) + _parse_(cigar, v_list) + (md,)
#
# if qname[-1] != '*': # Truncated qname
# if long_qname_table is None:
# raise ValueError('Long qname with no table lookup') # It's the caller's responsibility to handle this error
# _qname = long_qname_table.get(qname.split('|', 1)[0], None)
# if _qname is None:
# raise ValueError('Long qname with no table lookup: {}, {}'.format(qname.split('|', 1)[0], qname))
# # It's the caller's responsibility to handle this error
# qname = _qname
#
# d = qname[:-1].split('|') # Strip out the terminal '*'
# serial, sample = d[:2]
# chrom, cpy = d[2].split(':')
# cpy = int(cpy)
# return [
# ri(serial, sample, chrom, cpy, *_split_(r))
# for r in d[3:]
# ]
#
# Path: mitty/version.py
. Output only the next line. | read.cigarstring = ri.cigar if cigar_v2 else cigarv2_v1(ri.cigar) |
Based on the snippet: <|code_start|> """Given reads begining to a template, write out the perfect alignments to file
:param qname:
:param rg_id:
:param long_qname_table:
:param ref_dict: dict containing reference names mapped to ref_id
:param read_data: [x1, x2, ... ] where xi is (seq, qual)
and, e.g. [x1, x2] constitute a pair, if the input is paired end
:param cigar_v2: output CIGARs in V2 format
:param fp: pysam file pointer to write out
:return:
"""
reads = [
pysam.AlignedSegment()
for _ in range(len(read_data))
]
for n, (ri, rd, read) in enumerate(zip(parse_qname(qname, long_qname_table), read_data, reads)):
read.qname = qname
read.reference_id = ref_dict[ri.chrom]
read.pos = ri.pos - 1
read.cigarstring = ri.cigar if cigar_v2 else cigarv2_v1(ri.cigar)
read.mapq = 60
read.set_tag('RG', rg_id, value_type='Z')
# TODO: ask aligner people what the graph cigar tag is
# TODO: Set this as unmapped?
if ri.strand:
read.is_reverse = 1
read.mate_is_reverse = 0
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import os
import sys
import time
import pysam
from multiprocessing import Process, Queue
from mitty.lib.cigars import cigarv2_v1
from mitty.simulation.readgenerate import DNA_complement
from mitty.simulation.sequencing.writefastq import load_qname_sidecar, parse_qname
from mitty.version import __version__
and context (classes, functions, sometimes code) from other files:
# Path: mitty/lib/cigars.py
# def cigarv2_v1(cigar_v2):
# """Convert a V2 cigar_v1 string to V1
#
# :param cigarstring:
# :return:
# """
# values = pattern.split(cigar_v2.replace('=', 'M').replace('X', 'M'))
# cigar_v1 = []
# last_op, op_cnt = values[1], 0
# for op in zip(values[::2], values[1::2]):
# if op[1] == last_op:
# op_cnt += int(op[0])
# else:
# cigar_v1 += [str(op_cnt), last_op]
# last_op, op_cnt = op[1], int(op[0])
# cigar_v1 += [str(op_cnt), last_op]
# return ''.join(cigar_v1)
#
# Path: mitty/simulation/readgenerate.py
# SEED_MAX = (1 << 32) - 1 # Used for seeding rng
# def process_multi_threaded(fasta_fname, vcf_fname, sample_name, bed_fname,
# read_module, model, coverage,
# fastq1_fname, sidecar_fname, fastq2_fname,
# truncate_to=None,
# unpair=False,
# threads=2, seed=7):
# def get_data_for_workers(model, vcf, seed):
# def read_generating_worker(worker_id, fasta_fname, sample_name, read_module, read_model, in_queue, out_queue):
# def validate_templates_from_read_model(tplt):
#
# Path: mitty/simulation/sequencing/writefastq.py
# def load_qname_sidecar(sidecar_fn):
# def parse_sidecar_file(_fn):
# with open(_fn, 'r') as fp:
# for ln in fp:
# yield ln.split('|', 1)[0][1:], ln[1:-1]
# return {
# k: v
# for k, v in parse_sidecar_file(sidecar_fn)
# }
#
# def parse_qname(qname, long_qname_table=None):
# """Given a Mitty qname return us the POS and CIGAR as we would put in a BAM. There is also a special_cigar
# which is set for reads completely inside long insertions
#
# @index|sn|chrom:copy|strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD*
#
# :param qname:
# :param long_qname_table: If present, is a map of qname index and qname for just the long qnames
# :return: pos, cigar, special_cigar
# """
# def _parse_(_cigar, _v_list):
# """
# Parse cigar to extract special_cigar if needed
# Parse v_list
#
# :param _cigar:
# :param _v_list:
# :return:
# """
# if _cigar[0] == '>': # This is a special_cigar for a read from inside an insertion
# _special_cigar = _cigar
# _cigar = _cigar.split('+')[-1]
# else:
# _special_cigar = None
#
# return _cigar, _special_cigar, [int(v) for v in _v_list.split(',') if v is not '']
#
# def _split_(_r):
# strand, pos, cigar, v_list, md = _r.split(':')
# return (int(strand), int(pos)) + _parse_(cigar, v_list) + (md,)
#
# if qname[-1] != '*': # Truncated qname
# if long_qname_table is None:
# raise ValueError('Long qname with no table lookup') # It's the caller's responsibility to handle this error
# _qname = long_qname_table.get(qname.split('|', 1)[0], None)
# if _qname is None:
# raise ValueError('Long qname with no table lookup: {}, {}'.format(qname.split('|', 1)[0], qname))
# # It's the caller's responsibility to handle this error
# qname = _qname
#
# d = qname[:-1].split('|') # Strip out the terminal '*'
# serial, sample = d[:2]
# chrom, cpy = d[2].split(':')
# cpy = int(cpy)
# return [
# ri(serial, sample, chrom, cpy, *_split_(r))
# for r in d[3:]
# ]
#
# Path: mitty/version.py
. Output only the next line. | read.seq = rd[0].translate(DNA_complement)[::-1] |
Given the code snippet: <|code_start|> }
for n in range(0, len(ln), 2)]
def process_multi_threaded(
fasta, bam_fname, fastq1, sidecar_fname, fastq2=None, threads=1, max_templates=None,
platform='Illumina',
sample_name='Seven',
cigar_v2=True,
do_not_index=False):
"""
:param bam_fname:
:param bam_hdr:
:param fastq1:
:param sidecar_fname: File containing just the long qnames
:param fastq2:
:param threads:
:param max_templates:
:param platform:
:param sample_name:
:param cigar_v2: If True, write out CIGARs in V2 format
:param do_not_index: If True, the output BAMs will be collated into one bam, sorted and indexed
the N output BAMs created by the individual workers will be deleted at the end.
If False, the N output BAMs created by the individual workers will remain. This
option allows users to merge, sort and index the BAM fragments with their own tools
:return:
Note: The pysam sort invocation expects 1GB/thread to be available
"""
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
import sys
import time
import pysam
from multiprocessing import Process, Queue
from mitty.lib.cigars import cigarv2_v1
from mitty.simulation.readgenerate import DNA_complement
from mitty.simulation.sequencing.writefastq import load_qname_sidecar, parse_qname
from mitty.version import __version__
and context (functions, classes, or occasionally code) from other files:
# Path: mitty/lib/cigars.py
# def cigarv2_v1(cigar_v2):
# """Convert a V2 cigar_v1 string to V1
#
# :param cigarstring:
# :return:
# """
# values = pattern.split(cigar_v2.replace('=', 'M').replace('X', 'M'))
# cigar_v1 = []
# last_op, op_cnt = values[1], 0
# for op in zip(values[::2], values[1::2]):
# if op[1] == last_op:
# op_cnt += int(op[0])
# else:
# cigar_v1 += [str(op_cnt), last_op]
# last_op, op_cnt = op[1], int(op[0])
# cigar_v1 += [str(op_cnt), last_op]
# return ''.join(cigar_v1)
#
# Path: mitty/simulation/readgenerate.py
# SEED_MAX = (1 << 32) - 1 # Used for seeding rng
# def process_multi_threaded(fasta_fname, vcf_fname, sample_name, bed_fname,
# read_module, model, coverage,
# fastq1_fname, sidecar_fname, fastq2_fname,
# truncate_to=None,
# unpair=False,
# threads=2, seed=7):
# def get_data_for_workers(model, vcf, seed):
# def read_generating_worker(worker_id, fasta_fname, sample_name, read_module, read_model, in_queue, out_queue):
# def validate_templates_from_read_model(tplt):
#
# Path: mitty/simulation/sequencing/writefastq.py
# def load_qname_sidecar(sidecar_fn):
# def parse_sidecar_file(_fn):
# with open(_fn, 'r') as fp:
# for ln in fp:
# yield ln.split('|', 1)[0][1:], ln[1:-1]
# return {
# k: v
# for k, v in parse_sidecar_file(sidecar_fn)
# }
#
# def parse_qname(qname, long_qname_table=None):
# """Given a Mitty qname return us the POS and CIGAR as we would put in a BAM. There is also a special_cigar
# which is set for reads completely inside long insertions
#
# @index|sn|chrom:copy|strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD*
#
# :param qname:
# :param long_qname_table: If present, is a map of qname index and qname for just the long qnames
# :return: pos, cigar, special_cigar
# """
# def _parse_(_cigar, _v_list):
# """
# Parse cigar to extract special_cigar if needed
# Parse v_list
#
# :param _cigar:
# :param _v_list:
# :return:
# """
# if _cigar[0] == '>': # This is a special_cigar for a read from inside an insertion
# _special_cigar = _cigar
# _cigar = _cigar.split('+')[-1]
# else:
# _special_cigar = None
#
# return _cigar, _special_cigar, [int(v) for v in _v_list.split(',') if v is not '']
#
# def _split_(_r):
# strand, pos, cigar, v_list, md = _r.split(':')
# return (int(strand), int(pos)) + _parse_(cigar, v_list) + (md,)
#
# if qname[-1] != '*': # Truncated qname
# if long_qname_table is None:
# raise ValueError('Long qname with no table lookup') # It's the caller's responsibility to handle this error
# _qname = long_qname_table.get(qname.split('|', 1)[0], None)
# if _qname is None:
# raise ValueError('Long qname with no table lookup: {}, {}'.format(qname.split('|', 1)[0], qname))
# # It's the caller's responsibility to handle this error
# qname = _qname
#
# d = qname[:-1].split('|') # Strip out the terminal '*'
# serial, sample = d[:2]
# chrom, cpy = d[2].split(':')
# cpy = int(cpy)
# return [
# ri(serial, sample, chrom, cpy, *_split_(r))
# for r in d[3:]
# ]
#
# Path: mitty/version.py
. Output only the next line. | long_qname_table = load_qname_sidecar(sidecar_fname) |
Predict the next line for this snippet: <|code_start|>
logger.debug('Sorting {} -> {}'.format(bam_fname, bam_fname + '.sorted'))
t0 = time.time()
pysam.sort('-m', '1G', '-o', bam_fname + '.sorted', bam_fname)
os.remove(bam_fname)
t1 = time.time()
logger.debug('... {:0.2f}s'.format(t1 - t0))
logger.debug('Shutting down thread for {}'.format(bam_fname))
def write_perfect_reads(qname, rg_id, long_qname_table, ref_dict, read_data, cigar_v2,
fp):
"""Given reads begining to a template, write out the perfect alignments to file
:param qname:
:param rg_id:
:param long_qname_table:
:param ref_dict: dict containing reference names mapped to ref_id
:param read_data: [x1, x2, ... ] where xi is (seq, qual)
and, e.g. [x1, x2] constitute a pair, if the input is paired end
:param cigar_v2: output CIGARs in V2 format
:param fp: pysam file pointer to write out
:return:
"""
reads = [
pysam.AlignedSegment()
for _ in range(len(read_data))
]
<|code_end|>
with the help of current file imports:
import logging
import os
import sys
import time
import pysam
from multiprocessing import Process, Queue
from mitty.lib.cigars import cigarv2_v1
from mitty.simulation.readgenerate import DNA_complement
from mitty.simulation.sequencing.writefastq import load_qname_sidecar, parse_qname
from mitty.version import __version__
and context from other files:
# Path: mitty/lib/cigars.py
# def cigarv2_v1(cigar_v2):
# """Convert a V2 cigar_v1 string to V1
#
# :param cigarstring:
# :return:
# """
# values = pattern.split(cigar_v2.replace('=', 'M').replace('X', 'M'))
# cigar_v1 = []
# last_op, op_cnt = values[1], 0
# for op in zip(values[::2], values[1::2]):
# if op[1] == last_op:
# op_cnt += int(op[0])
# else:
# cigar_v1 += [str(op_cnt), last_op]
# last_op, op_cnt = op[1], int(op[0])
# cigar_v1 += [str(op_cnt), last_op]
# return ''.join(cigar_v1)
#
# Path: mitty/simulation/readgenerate.py
# SEED_MAX = (1 << 32) - 1 # Used for seeding rng
# def process_multi_threaded(fasta_fname, vcf_fname, sample_name, bed_fname,
# read_module, model, coverage,
# fastq1_fname, sidecar_fname, fastq2_fname,
# truncate_to=None,
# unpair=False,
# threads=2, seed=7):
# def get_data_for_workers(model, vcf, seed):
# def read_generating_worker(worker_id, fasta_fname, sample_name, read_module, read_model, in_queue, out_queue):
# def validate_templates_from_read_model(tplt):
#
# Path: mitty/simulation/sequencing/writefastq.py
# def load_qname_sidecar(sidecar_fn):
# def parse_sidecar_file(_fn):
# with open(_fn, 'r') as fp:
# for ln in fp:
# yield ln.split('|', 1)[0][1:], ln[1:-1]
# return {
# k: v
# for k, v in parse_sidecar_file(sidecar_fn)
# }
#
# def parse_qname(qname, long_qname_table=None):
# """Given a Mitty qname return us the POS and CIGAR as we would put in a BAM. There is also a special_cigar
# which is set for reads completely inside long insertions
#
# @index|sn|chrom:copy|strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD*
#
# :param qname:
# :param long_qname_table: If present, is a map of qname index and qname for just the long qnames
# :return: pos, cigar, special_cigar
# """
# def _parse_(_cigar, _v_list):
# """
# Parse cigar to extract special_cigar if needed
# Parse v_list
#
# :param _cigar:
# :param _v_list:
# :return:
# """
# if _cigar[0] == '>': # This is a special_cigar for a read from inside an insertion
# _special_cigar = _cigar
# _cigar = _cigar.split('+')[-1]
# else:
# _special_cigar = None
#
# return _cigar, _special_cigar, [int(v) for v in _v_list.split(',') if v is not '']
#
# def _split_(_r):
# strand, pos, cigar, v_list, md = _r.split(':')
# return (int(strand), int(pos)) + _parse_(cigar, v_list) + (md,)
#
# if qname[-1] != '*': # Truncated qname
# if long_qname_table is None:
# raise ValueError('Long qname with no table lookup') # It's the caller's responsibility to handle this error
# _qname = long_qname_table.get(qname.split('|', 1)[0], None)
# if _qname is None:
# raise ValueError('Long qname with no table lookup: {}, {}'.format(qname.split('|', 1)[0], qname))
# # It's the caller's responsibility to handle this error
# qname = _qname
#
# d = qname[:-1].split('|') # Strip out the terminal '*'
# serial, sample = d[:2]
# chrom, cpy = d[2].split(':')
# cpy = int(cpy)
# return [
# ri(serial, sample, chrom, cpy, *_split_(r))
# for r in d[3:]
# ]
#
# Path: mitty/version.py
, which may contain function names, class names, or code. Output only the next line. | for n, (ri, rd, read) in enumerate(zip(parse_qname(qname, long_qname_table), read_data, reads)): |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger(__name__)
__process_stop_code__ = 'SETECASTRONOMY'
def construct_header(fasta_ann, rg_id, sample='S', platform='Illumina'):
return {
'HD': {'VN': '1.0'},
'PG': [{'CL': ' '.join(sys.argv),
'ID': 'mitty-god-aligner',
'PN': 'god-aligner',
<|code_end|>
using the current file's imports:
import logging
import os
import sys
import time
import pysam
from multiprocessing import Process, Queue
from mitty.lib.cigars import cigarv2_v1
from mitty.simulation.readgenerate import DNA_complement
from mitty.simulation.sequencing.writefastq import load_qname_sidecar, parse_qname
from mitty.version import __version__
and any relevant context from other files:
# Path: mitty/lib/cigars.py
# def cigarv2_v1(cigar_v2):
# """Convert a V2 cigar_v1 string to V1
#
# :param cigarstring:
# :return:
# """
# values = pattern.split(cigar_v2.replace('=', 'M').replace('X', 'M'))
# cigar_v1 = []
# last_op, op_cnt = values[1], 0
# for op in zip(values[::2], values[1::2]):
# if op[1] == last_op:
# op_cnt += int(op[0])
# else:
# cigar_v1 += [str(op_cnt), last_op]
# last_op, op_cnt = op[1], int(op[0])
# cigar_v1 += [str(op_cnt), last_op]
# return ''.join(cigar_v1)
#
# Path: mitty/simulation/readgenerate.py
# SEED_MAX = (1 << 32) - 1 # Used for seeding rng
# def process_multi_threaded(fasta_fname, vcf_fname, sample_name, bed_fname,
# read_module, model, coverage,
# fastq1_fname, sidecar_fname, fastq2_fname,
# truncate_to=None,
# unpair=False,
# threads=2, seed=7):
# def get_data_for_workers(model, vcf, seed):
# def read_generating_worker(worker_id, fasta_fname, sample_name, read_module, read_model, in_queue, out_queue):
# def validate_templates_from_read_model(tplt):
#
# Path: mitty/simulation/sequencing/writefastq.py
# def load_qname_sidecar(sidecar_fn):
# def parse_sidecar_file(_fn):
# with open(_fn, 'r') as fp:
# for ln in fp:
# yield ln.split('|', 1)[0][1:], ln[1:-1]
# return {
# k: v
# for k, v in parse_sidecar_file(sidecar_fn)
# }
#
# def parse_qname(qname, long_qname_table=None):
# """Given a Mitty qname return us the POS and CIGAR as we would put in a BAM. There is also a special_cigar
# which is set for reads completely inside long insertions
#
# @index|sn|chrom:copy|strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD*
#
# :param qname:
# :param long_qname_table: If present, is a map of qname index and qname for just the long qnames
# :return: pos, cigar, special_cigar
# """
# def _parse_(_cigar, _v_list):
# """
# Parse cigar to extract special_cigar if needed
# Parse v_list
#
# :param _cigar:
# :param _v_list:
# :return:
# """
# if _cigar[0] == '>': # This is a special_cigar for a read from inside an insertion
# _special_cigar = _cigar
# _cigar = _cigar.split('+')[-1]
# else:
# _special_cigar = None
#
# return _cigar, _special_cigar, [int(v) for v in _v_list.split(',') if v is not '']
#
# def _split_(_r):
# strand, pos, cigar, v_list, md = _r.split(':')
# return (int(strand), int(pos)) + _parse_(cigar, v_list) + (md,)
#
# if qname[-1] != '*': # Truncated qname
# if long_qname_table is None:
# raise ValueError('Long qname with no table lookup') # It's the caller's responsibility to handle this error
# _qname = long_qname_table.get(qname.split('|', 1)[0], None)
# if _qname is None:
# raise ValueError('Long qname with no table lookup: {}, {}'.format(qname.split('|', 1)[0], qname))
# # It's the caller's responsibility to handle this error
# qname = _qname
#
# d = qname[:-1].split('|') # Strip out the terminal '*'
# serial, sample = d[:2]
# chrom, cpy = d[2].split(':')
# cpy = int(cpy)
# return [
# ri(serial, sample, chrom, cpy, *_split_(r))
# for r in d[3:]
# ]
#
# Path: mitty/version.py
. Output only the next line. | 'VN': __version__}], |
Using the snippet: <|code_start|> :param max_vlen:
:param strict_scoring:
:return:
"""
logger.debug('Starting worker {} ...'.format(worker_id))
t0, tot_cnt = time.time(), 0
xmv_mat = np.zeros(shape=(2 * max_xd + 3, max_MQ + 1, 2 * max_vlen + 1 + 2 + 1), dtype=int)
v_off_idx, max_v_idx = max_vlen + 2, 2 * max_vlen + 3
bam_fp = pysam.AlignmentFile(bam_fname)
for reference in iter(in_q.get, __process_stop_code__):
logger.debug('Worker {}: Contig {} ...'.format(worker_id, reference))
t1 = time.time()
cnt = process_contig(bam_fp, long_qname_table, max_MQ, max_v_idx, max_xd, reference, strict_scoring, v_off_idx,
xmv_mat)
t2 = time.time()
logger.debug(
'Worker {}: Contig {}: {} reads in {:2f}s ({:2f} r/s)'.format(worker_id, reference, cnt, t2 - t1, cnt / (t2 - t1)))
tot_cnt += cnt
out_q.put([xmv_mat, tot_cnt])
t1 = time.time()
logger.debug('Worker {}: Processed {} reads in {:2f}s ({:2f} r/s)'.format(worker_id, tot_cnt, t1 - t0, tot_cnt / (t1 - t0)))
def process_contig(bam_fp, long_qname_table, max_MQ, max_v_idx, max_xd, reference, strict_scoring, v_off_idx,
xmv_mat):
cnt = 0
<|code_end|>
, determine the next line of code. You have imports:
from multiprocessing import Process, Queue
from matplotlib.colors import LogNorm
from mitty.lib.bamfetch import fetch
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname
from mitty.benchmarking.plot.byvsize import plot_panels
import time
import logging
import matplotlib
import matplotlib.pyplot as plt
import pysam
import numpy as np
and context (class names, function names, or code) available:
# Path: mitty/lib/bamfetch.py
# def fetch(bam_fp, reference):
# return chain(*[bam_fp.fetch(reference=reference)] +
# ([bam_fp.fetch(until_eof=True)] if reference == bam_fp.references[-1] else []))
#
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
#
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
# color='k', linestyle='-', label='',
# yscale='linear', yticks=None, ylim=None, show_ax_label=False,
# ci=0.05):
# """Interpret y (an array of length 2 * N + 3) as follows:
# The indexes represent variant sizes from
#
# DEL len > N
# DEL len from N to 1
# SNPs
# INS len from 1 to N
# INS len > N
#
# :param ax:
# :param y: success rate
# :param cnt: number of counts in bin
# :param color:
# :param linestyle:
# :param label:
# :param yscale:
# :param yticks:
# :param ylim:
# :param show_ax_label:
# :return:
# """
# parts = bin_data_by_variant_size(num, den, bin_size)
# x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
# x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
# xticks, xticklabels = [], []
# for part in parts:
# line_with_ci(ax, part, color=color, linestyle=linestyle)
# xticks += part['xticks']
# xticklabels += part['xticklabels']
#
# # The fixed reference lines
# ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
#
# ax.set_xticks(xticks)
# ax.set_xticklabels(xticklabels if show_ax_label else [])
#
# ax.set_yscale(yscale)
# if yticks is not None:
# ax.set_yticks(yticks)
# if ylim is not None:
# ax.set_ylim(ylim)
# ax.get_yaxis().get_major_formatter().labelOnlyBase = False
# ax.set_xlim(x_lim)
#
# return mpatches.Patch(color=color, linestyle=linestyle, label=label) # patch_for_legend
. Output only the next line. | for r in fetch(bam_fp, reference=reference): |
Based on the snippet: <|code_start|> logger.debug('Starting worker {} ...'.format(worker_id))
t0, tot_cnt = time.time(), 0
xmv_mat = np.zeros(shape=(2 * max_xd + 3, max_MQ + 1, 2 * max_vlen + 1 + 2 + 1), dtype=int)
v_off_idx, max_v_idx = max_vlen + 2, 2 * max_vlen + 3
bam_fp = pysam.AlignmentFile(bam_fname)
for reference in iter(in_q.get, __process_stop_code__):
logger.debug('Worker {}: Contig {} ...'.format(worker_id, reference))
t1 = time.time()
cnt = process_contig(bam_fp, long_qname_table, max_MQ, max_v_idx, max_xd, reference, strict_scoring, v_off_idx,
xmv_mat)
t2 = time.time()
logger.debug(
'Worker {}: Contig {}: {} reads in {:2f}s ({:2f} r/s)'.format(worker_id, reference, cnt, t2 - t1, cnt / (t2 - t1)))
tot_cnt += cnt
out_q.put([xmv_mat, tot_cnt])
t1 = time.time()
logger.debug('Worker {}: Processed {} reads in {:2f}s ({:2f} r/s)'.format(worker_id, tot_cnt, t1 - t0, tot_cnt / (t1 - t0)))
def process_contig(bam_fp, long_qname_table, max_MQ, max_v_idx, max_xd, reference, strict_scoring, v_off_idx,
xmv_mat):
cnt = 0
for r in fetch(bam_fp, reference=reference):
if r.flag & 0b100100000000: continue # Skip supplementary or secondary alignments
cnt += 1
ri = parse_qname(r.qname, long_qname_table=long_qname_table)[1 if r.is_read2 else 0]
<|code_end|>
, predict the immediate next line with the help of imports:
from multiprocessing import Process, Queue
from matplotlib.colors import LogNorm
from mitty.lib.bamfetch import fetch
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname
from mitty.benchmarking.plot.byvsize import plot_panels
import time
import logging
import matplotlib
import matplotlib.pyplot as plt
import pysam
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: mitty/lib/bamfetch.py
# def fetch(bam_fp, reference):
# return chain(*[bam_fp.fetch(reference=reference)] +
# ([bam_fp.fetch(until_eof=True)] if reference == bam_fp.references[-1] else []))
#
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
#
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
# color='k', linestyle='-', label='',
# yscale='linear', yticks=None, ylim=None, show_ax_label=False,
# ci=0.05):
# """Interpret y (an array of length 2 * N + 3) as follows:
# The indexes represent variant sizes from
#
# DEL len > N
# DEL len from N to 1
# SNPs
# INS len from 1 to N
# INS len > N
#
# :param ax:
# :param y: success rate
# :param cnt: number of counts in bin
# :param color:
# :param linestyle:
# :param label:
# :param yscale:
# :param yticks:
# :param ylim:
# :param show_ax_label:
# :return:
# """
# parts = bin_data_by_variant_size(num, den, bin_size)
# x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
# x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
# xticks, xticklabels = [], []
# for part in parts:
# line_with_ci(ax, part, color=color, linestyle=linestyle)
# xticks += part['xticks']
# xticklabels += part['xticklabels']
#
# # The fixed reference lines
# ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
#
# ax.set_xticks(xticks)
# ax.set_xticklabels(xticklabels if show_ax_label else [])
#
# ax.set_yscale(yscale)
# if yticks is not None:
# ax.set_yticks(yticks)
# if ylim is not None:
# ax.set_ylim(ylim)
# ax.get_yaxis().get_major_formatter().labelOnlyBase = False
# ax.set_xlim(x_lim)
#
# return mpatches.Patch(color=color, linestyle=linestyle, label=label) # patch_for_legend
. Output only the next line. | d_err = score_alignment_error(r, ri=ri, max_d=max_xd, strict=strict_scoring) |
Given the following code snippet before the placeholder: <|code_start|>__process_stop_code__ = 'SETECASTRONOMY'
logger = logging.getLogger(__name__)
def main(bam_fname, sidecar_fname, max_xd=200, max_MQ=70, strict_scoring=False, max_vlen=200, processes=2):
"""This function rips through a BAM from simulated reads and bins reads into a three dimensional histogram.
The dimensions are:
Xd - alignment error [0] -max_xd, ... 0, ... +max_xd, wrong_chrom, unmapped (2 * max_xd + 3)
MQ - mapping quality [1] 0, ... max_MQ (max_MQ + 1)
vlen - length of variant carried by read [2] Ref, < -max_vlen , -max_vlen, ... 0, ... +max_vlen, > +max_vlen
( 2 * max_vlen + 1 + 2 + 1)
:param bam_fname:
:param sidecar_fname:
:param max_xd:
:param max_MQ:
:param strict_scoring:
:param max_vlen:
:param processes:
:return:
"""
# Set up the I/O queues and place all BAM contigs on the work queue
work_q, result_q = Queue(), Queue()
for ref in pysam.AlignmentFile(bam_fname).references:
work_q.put(ref)
for _ in range(processes):
work_q.put(__process_stop_code__)
# Start workers
<|code_end|>
, predict the next line using imports from the current file:
from multiprocessing import Process, Queue
from matplotlib.colors import LogNorm
from mitty.lib.bamfetch import fetch
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname
from mitty.benchmarking.plot.byvsize import plot_panels
import time
import logging
import matplotlib
import matplotlib.pyplot as plt
import pysam
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: mitty/lib/bamfetch.py
# def fetch(bam_fp, reference):
# return chain(*[bam_fp.fetch(reference=reference)] +
# ([bam_fp.fetch(until_eof=True)] if reference == bam_fp.references[-1] else []))
#
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
#
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
# color='k', linestyle='-', label='',
# yscale='linear', yticks=None, ylim=None, show_ax_label=False,
# ci=0.05):
# """Interpret y (an array of length 2 * N + 3) as follows:
# The indexes represent variant sizes from
#
# DEL len > N
# DEL len from N to 1
# SNPs
# INS len from 1 to N
# INS len > N
#
# :param ax:
# :param y: success rate
# :param cnt: number of counts in bin
# :param color:
# :param linestyle:
# :param label:
# :param yscale:
# :param yticks:
# :param ylim:
# :param show_ax_label:
# :return:
# """
# parts = bin_data_by_variant_size(num, den, bin_size)
# x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
# x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
# xticks, xticklabels = [], []
# for part in parts:
# line_with_ci(ax, part, color=color, linestyle=linestyle)
# xticks += part['xticks']
# xticklabels += part['xticklabels']
#
# # The fixed reference lines
# ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
#
# ax.set_xticks(xticks)
# ax.set_xticklabels(xticklabels if show_ax_label else [])
#
# ax.set_yscale(yscale)
# if yticks is not None:
# ax.set_yticks(yticks)
# if ylim is not None:
# ax.set_ylim(ylim)
# ax.get_yaxis().get_major_formatter().labelOnlyBase = False
# ax.set_xlim(x_lim)
#
# return mpatches.Patch(color=color, linestyle=linestyle, label=label) # patch_for_legend
. Output only the next line. | long_qname_table = load_qname_sidecar(sidecar_fname) |
Based on the snippet: <|code_start|> """
logger.debug('Starting worker {} ...'.format(worker_id))
t0, tot_cnt = time.time(), 0
xmv_mat = np.zeros(shape=(2 * max_xd + 3, max_MQ + 1, 2 * max_vlen + 1 + 2 + 1), dtype=int)
v_off_idx, max_v_idx = max_vlen + 2, 2 * max_vlen + 3
bam_fp = pysam.AlignmentFile(bam_fname)
for reference in iter(in_q.get, __process_stop_code__):
logger.debug('Worker {}: Contig {} ...'.format(worker_id, reference))
t1 = time.time()
cnt = process_contig(bam_fp, long_qname_table, max_MQ, max_v_idx, max_xd, reference, strict_scoring, v_off_idx,
xmv_mat)
t2 = time.time()
logger.debug(
'Worker {}: Contig {}: {} reads in {:2f}s ({:2f} r/s)'.format(worker_id, reference, cnt, t2 - t1, cnt / (t2 - t1)))
tot_cnt += cnt
out_q.put([xmv_mat, tot_cnt])
t1 = time.time()
logger.debug('Worker {}: Processed {} reads in {:2f}s ({:2f} r/s)'.format(worker_id, tot_cnt, t1 - t0, tot_cnt / (t1 - t0)))
def process_contig(bam_fp, long_qname_table, max_MQ, max_v_idx, max_xd, reference, strict_scoring, v_off_idx,
xmv_mat):
cnt = 0
for r in fetch(bam_fp, reference=reference):
if r.flag & 0b100100000000: continue # Skip supplementary or secondary alignments
cnt += 1
<|code_end|>
, predict the immediate next line with the help of imports:
from multiprocessing import Process, Queue
from matplotlib.colors import LogNorm
from mitty.lib.bamfetch import fetch
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname
from mitty.benchmarking.plot.byvsize import plot_panels
import time
import logging
import matplotlib
import matplotlib.pyplot as plt
import pysam
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: mitty/lib/bamfetch.py
# def fetch(bam_fp, reference):
# return chain(*[bam_fp.fetch(reference=reference)] +
# ([bam_fp.fetch(until_eof=True)] if reference == bam_fp.references[-1] else []))
#
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
#
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
# color='k', linestyle='-', label='',
# yscale='linear', yticks=None, ylim=None, show_ax_label=False,
# ci=0.05):
# """Interpret y (an array of length 2 * N + 3) as follows:
# The indexes represent variant sizes from
#
# DEL len > N
# DEL len from N to 1
# SNPs
# INS len from 1 to N
# INS len > N
#
# :param ax:
# :param y: success rate
# :param cnt: number of counts in bin
# :param color:
# :param linestyle:
# :param label:
# :param yscale:
# :param yticks:
# :param ylim:
# :param show_ax_label:
# :return:
# """
# parts = bin_data_by_variant_size(num, den, bin_size)
# x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
# x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
# xticks, xticklabels = [], []
# for part in parts:
# line_with_ci(ax, part, color=color, linestyle=linestyle)
# xticks += part['xticks']
# xticklabels += part['xticklabels']
#
# # The fixed reference lines
# ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
#
# ax.set_xticks(xticks)
# ax.set_xticklabels(xticklabels if show_ax_label else [])
#
# ax.set_yscale(yscale)
# if yticks is not None:
# ax.set_yticks(yticks)
# if ylim is not None:
# ax.set_ylim(ylim)
# ax.get_yaxis().get_major_formatter().labelOnlyBase = False
# ax.set_xlim(x_lim)
#
# return mpatches.Patch(color=color, linestyle=linestyle, label=label) # patch_for_legend
. Output only the next line. | ri = parse_qname(r.qname, long_qname_table=long_qname_table)[1 if r.is_read2 else 0] |
Based on the snippet: <|code_start|> ax = plt.subplot(211)
plot_alignment_accuracy_by_vsize(ax, xmv_mat, plot_bin_size=plot_bin_size)
ax = plt.subplot(212)
plot_vcounts(ax, xmv_mat, plot_bin_size=plot_bin_size)
plt.savefig(fig_prefix + '_V.png')
def alignment_accuracy_by_vsize(xmv_mat, d_err_threshold):
max_derr = int((xmv_mat.shape[0] - 3) / 2)
derr_mat = xmv_mat.sum(axis=1)
d_idx = (max_derr - d_err_threshold, max_derr + d_err_threshold + 1)
num = derr_mat[d_idx[0]:d_idx[1], :].sum(axis=0)[1:]
den = derr_mat.sum(axis=0)[1:]
return num, den
def plot_alignment_accuracy_by_vsize(ax, xmv_mat, plot_bin_size=5):
"""
:param ax:
:param xmv_mat:
:param plot_bin_size:
:param show_ax_label:
:return:
"""
n0, d0 = alignment_accuracy_by_vsize(xmv_mat, 0)
n50, d50 = alignment_accuracy_by_vsize(xmv_mat, 50)
<|code_end|>
, predict the immediate next line with the help of imports:
from multiprocessing import Process, Queue
from matplotlib.colors import LogNorm
from mitty.lib.bamfetch import fetch
from mitty.benchmarking.alignmentscore import score_alignment_error, load_qname_sidecar, parse_qname
from mitty.benchmarking.plot.byvsize import plot_panels
import time
import logging
import matplotlib
import matplotlib.pyplot as plt
import pysam
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: mitty/lib/bamfetch.py
# def fetch(bam_fp, reference):
# return chain(*[bam_fp.fetch(reference=reference)] +
# ([bam_fp.fetch(until_eof=True)] if reference == bam_fp.references[-1] else []))
#
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
#
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
# color='k', linestyle='-', label='',
# yscale='linear', yticks=None, ylim=None, show_ax_label=False,
# ci=0.05):
# """Interpret y (an array of length 2 * N + 3) as follows:
# The indexes represent variant sizes from
#
# DEL len > N
# DEL len from N to 1
# SNPs
# INS len from 1 to N
# INS len > N
#
# :param ax:
# :param y: success rate
# :param cnt: number of counts in bin
# :param color:
# :param linestyle:
# :param label:
# :param yscale:
# :param yticks:
# :param ylim:
# :param show_ax_label:
# :return:
# """
# parts = bin_data_by_variant_size(num, den, bin_size)
# x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
# x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
# xticks, xticklabels = [], []
# for part in parts:
# line_with_ci(ax, part, color=color, linestyle=linestyle)
# xticks += part['xticks']
# xticklabels += part['xticklabels']
#
# # The fixed reference lines
# ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
#
# ax.set_xticks(xticks)
# ax.set_xticklabels(xticklabels if show_ax_label else [])
#
# ax.set_yscale(yscale)
# if yticks is not None:
# ax.set_yticks(yticks)
# if ylim is not None:
# ax.set_ylim(ylim)
# ax.get_yaxis().get_major_formatter().labelOnlyBase = False
# ax.set_xlim(x_lim)
#
# return mpatches.Patch(color=color, linestyle=linestyle, label=label) # patch_for_legend
. Output only the next line. | d0_p = plot_panels(ax, |
Predict the next line after this snippet: <|code_start|>
return [_part(n) for n in range(2 ** n_bams)]
def process_these_reads(part_d, rl, scoring_fn, threshold, long_qname_table):
p = scoring_fn(rl, threshold, long_qname_table)
if p is not None:
# several of these scoring functions mutate reads in rl
for bam_fp, r in zip(part_d[p]['filehandles'], rl):
bam_fp.write(r)
part_d[p]['total'] += 1
def get_partition_label(n, no):
if no == 0:
return []
return [labels[n % 2][no - 1]] + get_partition_label(int(n / 2), no - 1)
# Partition functions ---------------------------------------------------------------
# The functions return a number between 0 and 2^n - 1 indicating the partition the read should
# go into. If the result is None, this read should be discarded (does not contribute to any counts)
def partition_by_d_err(rl, x, long_qname_table):
"""
:param rl: a list of read objects [0, 1, 2, ...]
:param x: threshold
:return:
"""
<|code_end|>
using the current file's imports:
import os
import time
import logging
import pysam
from mitty.benchmarking.alignmentscore import ri, load_qname_sidecar, parse_qname, score_alignment_error, tag_alignment
and any relevant context from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | ri = parse_qname(rl[0].qname, long_qname_table)[0 if rl[0].is_read1 else 1] |
Continue the code snippet: <|code_start|>
:param bam_fp_l:
:return:
"""
bl = [bam_fp.fetch(until_eof=True) for bam_fp in bam_fp_l]
while 1:
rl = [next(bam_fp, None) for bam_fp in bl]
if any(rl):
for n, r in enumerate(rl):
if r is None: continue
if r.flag & 0x900 != 0: continue # Not primary alignment
yield n, r
else:
break
def main(bam_in_l, out_prefix, criterion, threshold, sidecar_fname=None):
"""
:param bam_in_l:
:param out_prefix:
:param criterion: {'d_err', 'MQ', 'mapped', 'p_diff'}
:param threshold:
:param simulated:
:param sidecar_fname
:return:
"""
assert len(bam_in_l) <= MAX_ORIGINS, "Can't do more than {} sets".format(MAX_ORIGINS)
bam_fp_l = [pysam.AlignmentFile(bam_in) for bam_in in bam_in_l]
<|code_end|>
. Use current file imports:
import os
import time
import logging
import pysam
from mitty.benchmarking.alignmentscore import ri, load_qname_sidecar, parse_qname, score_alignment_error, tag_alignment
and context (classes, functions, or code) from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | long_qname_table = load_qname_sidecar(sidecar_fname) if sidecar_fname else None |
Given the code snippet: <|code_start|>
return [_part(n) for n in range(2 ** n_bams)]
def process_these_reads(part_d, rl, scoring_fn, threshold, long_qname_table):
p = scoring_fn(rl, threshold, long_qname_table)
if p is not None:
# several of these scoring functions mutate reads in rl
for bam_fp, r in zip(part_d[p]['filehandles'], rl):
bam_fp.write(r)
part_d[p]['total'] += 1
def get_partition_label(n, no):
if no == 0:
return []
return [labels[n % 2][no - 1]] + get_partition_label(int(n / 2), no - 1)
# Partition functions ---------------------------------------------------------------
# The functions return a number between 0 and 2^n - 1 indicating the partition the read should
# go into. If the result is None, this read should be discarded (does not contribute to any counts)
def partition_by_d_err(rl, x, long_qname_table):
"""
:param rl: a list of read objects [0, 1, 2, ...]
:param x: threshold
:return:
"""
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
import logging
import pysam
from mitty.benchmarking.alignmentscore import ri, load_qname_sidecar, parse_qname, score_alignment_error, tag_alignment
and context (functions, classes, or occasionally code) from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | ri = parse_qname(rl[0].qname, long_qname_table)[0 if rl[0].is_read1 else 1] |
Based on the snippet: <|code_start|>
def process_these_reads(part_d, rl, scoring_fn, threshold, long_qname_table):
p = scoring_fn(rl, threshold, long_qname_table)
if p is not None:
# several of these scoring functions mutate reads in rl
for bam_fp, r in zip(part_d[p]['filehandles'], rl):
bam_fp.write(r)
part_d[p]['total'] += 1
def get_partition_label(n, no):
if no == 0:
return []
return [labels[n % 2][no - 1]] + get_partition_label(int(n / 2), no - 1)
# Partition functions ---------------------------------------------------------------
# The functions return a number between 0 and 2^n - 1 indicating the partition the read should
# go into. If the result is None, this read should be discarded (does not contribute to any counts)
def partition_by_d_err(rl, x, long_qname_table):
"""
:param rl: a list of read objects [0, 1, 2, ...]
:param x: threshold
:return:
"""
ri = parse_qname(rl[0].qname, long_qname_table)[0 if rl[0].is_read1 else 1]
for r in rl:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import time
import logging
import pysam
from mitty.benchmarking.alignmentscore import ri, load_qname_sidecar, parse_qname, score_alignment_error, tag_alignment
and context (classes, functions, sometimes code) from other files:
# Path: mitty/benchmarking/alignmentscore.py
# def is_simple_case(cigar1, cigar2):
# def find_first_common_reference_matching_base_positions(r1, r2):
# def score_alignment_error(r, ri, max_d=200, strict=False):
# def correct_tlen(ri1, ri2, r):
# def tag_alignment(r, ri, max_d=200, strict=False):
. Output only the next line. | tag_alignment(r, ri) |
Continue the code snippet: <|code_start|>"""Program to go through a VCF and compute the distribution of variant sizes"""
matplotlib.use('Agg')
def main(vcf_fname, sample_name=None, max_size=50):
data = np.zeros(shape=(2 * max_size + 1 + 2), dtype=int)
offset, max_n = max_size + 1, 2 * max_size + 2
mode = 'rb' if vcf_fname.endswith('bcf') else 'r'
vcf_in = pysam.VariantFile(vcf_fname, mode)
if sample_name is not None:
vcf_in.subset_samples([sample_name])
for v in vcf_in:
for alt in v.alts:
sz = len(alt) - len(v.ref)
data[min(max_n, max(0, offset + sz))] += 1
return data
def plot(data, fig_fname, bin_size=5, title='Variant size distribution'):
fig = plt.figure(figsize=(11, 6))
plt.subplots_adjust(bottom=0.05, top=0.95, hspace=0.01)
ax1 = plt.subplot(111)
n_max = 10 ** np.ceil(np.log10(data.max()))
n_min = 10 ** int(np.log10(data.min() + 1))
<|code_end|>
. Use current file imports:
import numpy as np
import pysam
import matplotlib
import matplotlib.pyplot as plt
from mitty.benchmarking.plot.byvsize import plot_panels
and context (classes, functions, or code) from other files:
# Path: mitty/benchmarking/plot/byvsize.py
# def plot_panels(ax, num, den=None, bin_size=None,
# color='k', linestyle='-', label='',
# yscale='linear', yticks=None, ylim=None, show_ax_label=False,
# ci=0.05):
# """Interpret y (an array of length 2 * N + 3) as follows:
# The indexes represent variant sizes from
#
# DEL len > N
# DEL len from N to 1
# SNPs
# INS len from 1 to N
# INS len > N
#
# :param ax:
# :param y: success rate
# :param cnt: number of counts in bin
# :param color:
# :param linestyle:
# :param label:
# :param yscale:
# :param yticks:
# :param ylim:
# :param show_ax_label:
# :return:
# """
# parts = bin_data_by_variant_size(num, den, bin_size)
# x1, x0 = parts[-1]['x'][0], parts[0]['x'][0]
# x_lim = [x0 - .1 *(x1 - x0), x1 + .1 *(x1 - x0)]
# xticks, xticklabels = [], []
# for part in parts:
# line_with_ci(ax, part, color=color, linestyle=linestyle)
# xticks += part['xticks']
# xticklabels += part['xticklabels']
#
# # The fixed reference lines
# ax.axvline(x=parts[0]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[2]['x'], color='k', linestyle=':')
# ax.axvline(x=parts[4]['x'], color='k', linestyle=':')
#
# ax.set_xticks(xticks)
# ax.set_xticklabels(xticklabels if show_ax_label else [])
#
# ax.set_yscale(yscale)
# if yticks is not None:
# ax.set_yticks(yticks)
# if ylim is not None:
# ax.set_ylim(ylim)
# ax.get_yaxis().get_major_formatter().labelOnlyBase = False
# ax.set_xlim(x_lim)
#
# return mpatches.Patch(color=color, linestyle=linestyle, label=label) # patch_for_legend
. Output only the next line. | r_p = plot_panels(ax1, |
Predict the next line after this snippet: <|code_start|>
def test_cigar_conversion():
"""Cigars: Converting cigar V2 to V1"""
test_cases = [
('33=1X79=1X26=1X109=', '250M'),
('1X26=1X123=1X82=1X15=', '250M'),
('89=10D161=', '89M10D161M'),
('99M1X', '100M'),
('10M10D1X9M', '10M10D10M')
]
for tc in test_cases:
<|code_end|>
using the current file's imports:
from mitty.lib.cigars import cigarv2_v1
and any relevant context from other files:
# Path: mitty/lib/cigars.py
# def cigarv2_v1(cigar_v2):
# """Convert a V2 cigar_v1 string to V1
#
# :param cigarstring:
# :return:
# """
# values = pattern.split(cigar_v2.replace('=', 'M').replace('X', 'M'))
# cigar_v1 = []
# last_op, op_cnt = values[1], 0
# for op in zip(values[::2], values[1::2]):
# if op[1] == last_op:
# op_cnt += int(op[0])
# else:
# cigar_v1 += [str(op_cnt), last_op]
# last_op, op_cnt = op[1], int(op[0])
# cigar_v1 += [str(op_cnt), last_op]
# return ''.join(cigar_v1)
. Output only the next line. | assert cigarv2_v1(tc[0]) == tc[1], cigarv2_v1(tc[0]) |
Predict the next line for this snippet: <|code_start|>
self.default_test["sampling"] = {}
self.default_test["sampling"]["enable"] = True
self.default_test["sampling"]["ratio"] = None
self.default_test["sampling"]["region_len_multiplier"] = 10
self.default_test["sampling"]["region_len"] = None
self.default_test["sampling"]["region_pad"] = None
self.default_test["simulator"] = None
self.default_test["reference"] = None
self.default_test["platform"] = "illumina"
self.default_test["read_length"] = 100
self.default_test["read_count"] = None
self.default_test["paired"] = False
self.default_test["insert_size"] = 500
self.default_test["insert_size_error"] = 50
self.default_test["coverage"] = 1
self.default_test["mutation_rate"] = 0.001
self.default_test["mutation_indel_frac"] = 0.3
self.default_test["mutation_indel_avg_len"] = 1
self.default_test["error_rate_mult"] = 1
self.default_test["extra_params"] = ""
self.default_test["simulator_cmd"] = ""
self.default_test["import_read_files"] = None
self.default_test["import_gold_standard_file"] = None
self.created_count = 0
<|code_end|>
with the help of current file imports:
import os
import shutil
import time
import yaml
import util
import simulator
import main
from lib import gsample
from tools import fastq2sam
from lib import sam
and context from other files:
# Path: lib/gsample.py
# def log(msg):
# def index(reference, fastindex_path = "tools/fastindex"):
# def index_legacy(reference):
# def downsample(index, contig_filename, downsampled_filename, region_count, target_len, single_contig=False,
# region_list=False, spacer_len=200):
# def csample(infile, region_size, sample_fraction, spacer_len=200, fastindex_path=""):
# def ctranslate(reference_file, sampled_index_file, sam_file, target_file, fastindex_path=""):
#
# Path: tools/fastq2sam.py
# def encode_qname(qname, retain_petag=True):
# def __init__(self):
# def __init__(self, filename, pe):
# def readline(self):
# def next_read(self):
# def __init__(self):
# def align(read):
# def align(self, read, paired=False, is_read1=True):
# def align_pair(self, read1, read2):
# def align(self, read, paired=False, is_read1=True):
# def align_pair(self, read1, read2):
# def __init__(self, aligner, outfile):
# def write(self, what):
# def write_sam_header(self, reads):
# def write_single(self, read, to):
# def align_se(self, infile):
# def align_pe(self, infile_1, infile_2):
# class Object:
# class FASTQ:
# class Aligner:
# class DummyAligner(Aligner):
# class dwgsim(Aligner):
# class Converter:
#
# Path: lib/sam.py
# class SAMRow:
# class SAMFile:
# class Object:
# class FASTQ:
# def __init__(self):
# def getTag(self,tag_name):
# def __init__(self, filename):
# def close(self):
# def hasLast(self):
# def getLast(self):
# def getCurr(self):
# def getHeader(self):
# def isSorted(self):
# def next(self):
# def __init__(self):
# def __init__(self, filename, write=False):
# def readline(self):
# def next_read(self):
# def write_read(self,read):
# def close(self):
, which may contain function names, class names, or code. Output only the next line. | gsample.log = lambda msg: self.log(msg) |
Predict the next line for this snippet: <|code_start|>
def makeDatasetNoSim(self,test):
util.enterRootDir()
if test["import_read_files"] == None or len(test["import_read_files"])==0:
self.mate.error("Teaser: No read files given to import for test '%s'"%test["name"])
test["type"]=None
raise RuntimeError
if test["paired"]:
if len(test["import_read_files"]) != 2:
self.mate.error("Teaser: Expected 2 files in field 'import_read_files' for paired-end test '%s', got %d"%(test["name"],len(test["import_read_files"])))
raise RuntimeError
else:
if len(test["import_read_files"]) != 1:
self.mate.error("Teaser: Expected 1 file in field 'import_read_files' for paired-end test '%s', got %d"%(test["name"],len(test["import_read_files"])))
raise RuntimeError
for filename in test["import_read_files"]:
if not self.isFastq(filename):
self.mate.error("Teaser: Unsupported read file type of '%s' for test '%s'. Expected FASTQ." % (filename,test["name"]) )
raise RuntimeError
if test["type"] == "simulated_custom":
self.importDatasetCustom(test)
elif test["type"] == "real":
self.importDatasetReal(test)
self.ch(test)
self.log("Generate dummy alignments")
<|code_end|>
with the help of current file imports:
import os
import shutil
import time
import yaml
import util
import simulator
import main
from lib import gsample
from tools import fastq2sam
from lib import sam
and context from other files:
# Path: lib/gsample.py
# def log(msg):
# def index(reference, fastindex_path = "tools/fastindex"):
# def index_legacy(reference):
# def downsample(index, contig_filename, downsampled_filename, region_count, target_len, single_contig=False,
# region_list=False, spacer_len=200):
# def csample(infile, region_size, sample_fraction, spacer_len=200, fastindex_path=""):
# def ctranslate(reference_file, sampled_index_file, sam_file, target_file, fastindex_path=""):
#
# Path: tools/fastq2sam.py
# def encode_qname(qname, retain_petag=True):
# def __init__(self):
# def __init__(self, filename, pe):
# def readline(self):
# def next_read(self):
# def __init__(self):
# def align(read):
# def align(self, read, paired=False, is_read1=True):
# def align_pair(self, read1, read2):
# def align(self, read, paired=False, is_read1=True):
# def align_pair(self, read1, read2):
# def __init__(self, aligner, outfile):
# def write(self, what):
# def write_sam_header(self, reads):
# def write_single(self, read, to):
# def align_se(self, infile):
# def align_pe(self, infile_1, infile_2):
# class Object:
# class FASTQ:
# class Aligner:
# class DummyAligner(Aligner):
# class dwgsim(Aligner):
# class Converter:
#
# Path: lib/sam.py
# class SAMRow:
# class SAMFile:
# class Object:
# class FASTQ:
# def __init__(self):
# def getTag(self,tag_name):
# def __init__(self, filename):
# def close(self):
# def hasLast(self):
# def getLast(self):
# def getCurr(self):
# def getHeader(self):
# def isSorted(self):
# def next(self):
# def __init__(self):
# def __init__(self, filename, write=False):
# def readline(self):
# def next_read(self):
# def write_read(self,read):
# def close(self):
, which may contain function names, class names, or code. Output only the next line. | aligner = fastq2sam.DummyAligner() |
Predict the next line for this snippet: <|code_start|>
def importDatasetCustom(self,test):
self.cp(test["import_gold_standard_file"],test["dir"]+"/mapping_comparison.sam")
test["read_count"] = self.importReadFiles(test)
self.log("Data set import successful")
def importReadFiles(self,test):
if len(test["import_read_files"]) > 1:
i=1
for f in test["import_read_files"]:
self.cp(f,test["dir"]+("/reads%d.fastq"%i) )
if i==1:
line_count = util.line_count(f)
i+=1
else:
self.cp(test["import_read_files"][0],test["dir"]+("/reads.fastq"))
line_count = util.line_count(test["import_read_files"][0])
return (line_count - line_count%4)/4
def importDatasetReal(self,test):
if test["sampling"]["enable"] == False:
self.log("Subsampling disabled; Importing all reads")
test["read_count"] = self.importReadFiles(test)
self.log("Data set import successful")
return
if test["read_count"] == None:
self.log("No target read count given for real data test, estimating using reference and avg. read length")
<|code_end|>
with the help of current file imports:
import os
import shutil
import time
import yaml
import util
import simulator
import main
from lib import gsample
from tools import fastq2sam
from lib import sam
and context from other files:
# Path: lib/gsample.py
# def log(msg):
# def index(reference, fastindex_path = "tools/fastindex"):
# def index_legacy(reference):
# def downsample(index, contig_filename, downsampled_filename, region_count, target_len, single_contig=False,
# region_list=False, spacer_len=200):
# def csample(infile, region_size, sample_fraction, spacer_len=200, fastindex_path=""):
# def ctranslate(reference_file, sampled_index_file, sam_file, target_file, fastindex_path=""):
#
# Path: tools/fastq2sam.py
# def encode_qname(qname, retain_petag=True):
# def __init__(self):
# def __init__(self, filename, pe):
# def readline(self):
# def next_read(self):
# def __init__(self):
# def align(read):
# def align(self, read, paired=False, is_read1=True):
# def align_pair(self, read1, read2):
# def align(self, read, paired=False, is_read1=True):
# def align_pair(self, read1, read2):
# def __init__(self, aligner, outfile):
# def write(self, what):
# def write_sam_header(self, reads):
# def write_single(self, read, to):
# def align_se(self, infile):
# def align_pe(self, infile_1, infile_2):
# class Object:
# class FASTQ:
# class Aligner:
# class DummyAligner(Aligner):
# class dwgsim(Aligner):
# class Converter:
#
# Path: lib/sam.py
# class SAMRow:
# class SAMFile:
# class Object:
# class FASTQ:
# def __init__(self):
# def getTag(self,tag_name):
# def __init__(self, filename):
# def close(self):
# def hasLast(self):
# def getLast(self):
# def getCurr(self):
# def getHeader(self):
# def isSorted(self):
# def next(self):
# def __init__(self):
# def __init__(self, filename, write=False):
# def readline(self):
# def next_read(self):
# def write_read(self,read):
# def close(self):
, which may contain function names, class names, or code. Output only the next line. | fastq=sam.FASTQ(test["import_read_files"][0]) |
Given the code snippet: <|code_start|> if cleaned > 0:
self.log("Cleaned " + str(cleaned) + " tests from cache")
def cleanCacheFull(self):
# if self.no_cleanup:
# return
version = self.getVersionHash()
cleaned = 0
for filename in os.listdir(self.config["cache_directory"]):
name, ext = os.path.splitext(filename)
if ext == ".test":
os.remove(self.config["cache_directory"] + "/" + filename)
cleaned = cleaned + 1
if cleaned > 0:
self.log("Cleaned " + str(cleaned) + " tests from cache (full clean)")
def triggerCleanupEvents(self, tests):
if self.no_cleanup:
return
for test_name in tests:
the_test = tests[test_name]
if the_test.getWasRun():
the_test.cleanup()
<|code_end|>
, generate the next line using the imports in this file:
from lib import teaser
from datetime import datetime
from lib import test
from lib import util
from lib import report
import os
import time
import copy
import sys
import pickle
import yaml
import argparse
import hashlib
import traceback
import fnmatch
and context (functions, classes, or occasionally code) from other files:
# Path: lib/test.py
# class Test:
# def __init__(self, id, name, directory, mate, mapper):
# def _(self, field, default=None):
# def setc(self, field, new_value):
# def getReportDirectory(self):
# def log(self, text, level=2, newline="\n"):
# def dbg(self, text, prefix="INFO"):
# def warn(self, text, affected_file=None, affected_pos=None):
# def error(self, text, affected_file=None, affected_pos=None):
# def fatal_error(self, text, affected_file=None, affected_pos=None):
# def getWarnings(self):
# def getErrors(self):
# def getSuccess(self):
# def getErrorCount(self):
# def getWarningCount(self):
# def getComment(self):
# def getVersionHash(self):
# def serialize(self):
# def unserialize(self, ser):
# def getLocals(self):
# def buildAbsoluteScriptPath(self, filename):
# def getTestDirectoryByPath(self, test_name_full):
# def getTestNameByPath(self, test_name_full):
# def load(self):
# def getParentTest(self):
# def evaluate(self):
# def getMapper(self):
# def getName(self):
# def getFullName(self):
# def getId(self):
# def getTitle(self):
# def getPath(self):
# def getConfig(self):
# def getRunTime(self):
# def getCreateTime(self):
# def getShouldRun(self):
# def getWasRun(self):
# def getWasFinished(self):
# def getSuccess(self):
# def getIsBasic(self):
# def getResultOverviewText(self, indent=""):
# def consoleReport(self):
# def executePipeline(self, event, args=()):
# def run(self):
# def sub(self,command,description="",detailed=False):
# def enterWorkingDirectory(self):
# def restoreWorkingDirectory(self):
# def cleanup(self):
# def setRunResults(self, results):
# def getRunResults(self):
# def setHumanizedRunResults(self, results):
# def getHumanizedRunResults(self):
# def getSubResults(self):
# def getComparisonTest(self):
# def setComparisonTest(self, comp):
# def getCSVPath(self,title):
# def writeCSV(self,title,csv):
#
# Path: lib/util.py
# STATUS_NORMAL=1
# STATUS_MAX_MEMORY_EXCEEDED=2
# STATUS_MAX_RUNTIME_EXCEEDED=3
# MAX_LEN_OUT = 10000
# def runAndMeasure(command,detailed=True,maxtime=0,maxmem=0):
# def runSimple(command):
# def runAndMeasureInternal(return_queue,command,maxtime=0,maxmem=0):
# def runInternal(control_queue,command,max_memory):
# def measureProcess(queue, initial_pids, command, measurement_interval=1, max_runtime=0, max_memory=0, debug=False):
# def extendTargets(targets, proc):
# def killTargets(targets):
# def updateTargets(targets, metrics):
# def updateMetrics(target, metrics):
# def loadConfig(name, parent_dir="", already_included=[]):
# def setCallDir(d):
# def setRootDir(d):
# def enterCallDir():
# def enterRootDir():
# def getRootDir():
# def nl2br(text):
# def msg(text="", level=1):
# def yes_no(b):
# def md5(text):
# def merge(x, y):
# def formatFilesize(n):
# def percent(val, base, offset=0):
# def abs_path(path):
# def get_sam_header_line_count(filename):
# def is_sam_sorted(filename):
# def sort_sam(filename,threads=1):
# def sort_sam_picard(filename,threads=-1):
# def line_count(filename):
# def sanitize_string(s):
# def makeExportDropdown(plot_id,csv_filename):
# def parseMD(md,seq):
#
# Path: lib/report.py
# class ReportHTMLGenerator:
# def __init__(self, mate, plotgen):
# def nltobr(self, text):
# def write(self, text):
# def openPanel(self, title="Panel", style="default"):
# def closePanel(self):
# def collapsible(self, heading, text, opened=False):
# def openCollapsiblePanel(self, heading, opened=False):
# def closeCollapsiblePanel(self):
# def getMapperBinaryPath(self, mapper):
# def makeTestNavList(self):
# def makeTestMapperNavList(self, test_objects):
# def generateMainErrorList(self):
# def generateErrorList(self, test):
# def generateMainErrorList(self):
# def generateTestList(self):
# def generateSetup(self):
# def generateLogs(self):
# def generateSubprocessOutputs(self, test):
# def generateOverviewPlot(self, page, measure):
# def generate(self):
# def generateProgress(self):
. Output only the next line. | def getTestCachedPath(self, test): |
Given snippet: <|code_start|> cleaned = 0
for filename in os.listdir(self.config["cache_directory"]):
name, ext = os.path.splitext(filename)
if ext == ".test":
os.remove(self.config["cache_directory"] + "/" + filename)
cleaned = cleaned + 1
if cleaned > 0:
self.log("Cleaned " + str(cleaned) + " tests from cache (full clean)")
def triggerCleanupEvents(self, tests):
if self.no_cleanup:
return
for test_name in tests:
the_test = tests[test_name]
if the_test.getWasRun():
the_test.cleanup()
def getTestCachedPath(self, test):
return self.getCachePathPrefix() + test.getVersionHash() + ".test"
def getCachePathPrefix(self):
return self.config["cache_directory"] + "/" + self.framework_hash + "_"
def loadTestsFor(self, mapper_id):
mapper_conf = self.config["mappers"][mapper_id]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from lib import teaser
from datetime import datetime
from lib import test
from lib import util
from lib import report
import os
import time
import copy
import sys
import pickle
import yaml
import argparse
import hashlib
import traceback
import fnmatch
and context:
# Path: lib/test.py
# class Test:
# def __init__(self, id, name, directory, mate, mapper):
# def _(self, field, default=None):
# def setc(self, field, new_value):
# def getReportDirectory(self):
# def log(self, text, level=2, newline="\n"):
# def dbg(self, text, prefix="INFO"):
# def warn(self, text, affected_file=None, affected_pos=None):
# def error(self, text, affected_file=None, affected_pos=None):
# def fatal_error(self, text, affected_file=None, affected_pos=None):
# def getWarnings(self):
# def getErrors(self):
# def getSuccess(self):
# def getErrorCount(self):
# def getWarningCount(self):
# def getComment(self):
# def getVersionHash(self):
# def serialize(self):
# def unserialize(self, ser):
# def getLocals(self):
# def buildAbsoluteScriptPath(self, filename):
# def getTestDirectoryByPath(self, test_name_full):
# def getTestNameByPath(self, test_name_full):
# def load(self):
# def getParentTest(self):
# def evaluate(self):
# def getMapper(self):
# def getName(self):
# def getFullName(self):
# def getId(self):
# def getTitle(self):
# def getPath(self):
# def getConfig(self):
# def getRunTime(self):
# def getCreateTime(self):
# def getShouldRun(self):
# def getWasRun(self):
# def getWasFinished(self):
# def getSuccess(self):
# def getIsBasic(self):
# def getResultOverviewText(self, indent=""):
# def consoleReport(self):
# def executePipeline(self, event, args=()):
# def run(self):
# def sub(self,command,description="",detailed=False):
# def enterWorkingDirectory(self):
# def restoreWorkingDirectory(self):
# def cleanup(self):
# def setRunResults(self, results):
# def getRunResults(self):
# def setHumanizedRunResults(self, results):
# def getHumanizedRunResults(self):
# def getSubResults(self):
# def getComparisonTest(self):
# def setComparisonTest(self, comp):
# def getCSVPath(self,title):
# def writeCSV(self,title,csv):
#
# Path: lib/util.py
# STATUS_NORMAL=1
# STATUS_MAX_MEMORY_EXCEEDED=2
# STATUS_MAX_RUNTIME_EXCEEDED=3
# MAX_LEN_OUT = 10000
# def runAndMeasure(command,detailed=True,maxtime=0,maxmem=0):
# def runSimple(command):
# def runAndMeasureInternal(return_queue,command,maxtime=0,maxmem=0):
# def runInternal(control_queue,command,max_memory):
# def measureProcess(queue, initial_pids, command, measurement_interval=1, max_runtime=0, max_memory=0, debug=False):
# def extendTargets(targets, proc):
# def killTargets(targets):
# def updateTargets(targets, metrics):
# def updateMetrics(target, metrics):
# def loadConfig(name, parent_dir="", already_included=[]):
# def setCallDir(d):
# def setRootDir(d):
# def enterCallDir():
# def enterRootDir():
# def getRootDir():
# def nl2br(text):
# def msg(text="", level=1):
# def yes_no(b):
# def md5(text):
# def merge(x, y):
# def formatFilesize(n):
# def percent(val, base, offset=0):
# def abs_path(path):
# def get_sam_header_line_count(filename):
# def is_sam_sorted(filename):
# def sort_sam(filename,threads=1):
# def sort_sam_picard(filename,threads=-1):
# def line_count(filename):
# def sanitize_string(s):
# def makeExportDropdown(plot_id,csv_filename):
# def parseMD(md,seq):
#
# Path: lib/report.py
# class ReportHTMLGenerator:
# def __init__(self, mate, plotgen):
# def nltobr(self, text):
# def write(self, text):
# def openPanel(self, title="Panel", style="default"):
# def closePanel(self):
# def collapsible(self, heading, text, opened=False):
# def openCollapsiblePanel(self, heading, opened=False):
# def closeCollapsiblePanel(self):
# def getMapperBinaryPath(self, mapper):
# def makeTestNavList(self):
# def makeTestMapperNavList(self, test_objects):
# def generateMainErrorList(self):
# def generateErrorList(self, test):
# def generateMainErrorList(self):
# def generateTestList(self):
# def generateSetup(self):
# def generateLogs(self):
# def generateSubprocessOutputs(self, test):
# def generateOverviewPlot(self, page, measure):
# def generate(self):
# def generateProgress(self):
which might include code, classes, or functions. Output only the next line. | mapper_module = util.locate("lib.mapper") |
Given the code snippet: <|code_start|>class Mate:
def __init__(self):
self.deployment_mode = "production"
self.config = False
self.config_original = False
self.script_locals = {"self": self}
self.tests_run_count = 0
self.tests_success_count = 0
self.tests_err_count = 0
self.tests_warn_count = 0
self.tests_aborted_count = 0
self.run_only = False
self.is_stats_run = True
self.no_cleanup = False
self.force_run = False
self.force_gen = False
self.tests = {}
self.run_id = str(int(time.time()))
self.version_hash = False
self.clear_fs_cache = False
self.list_tests = False
self.tests_ran = 0
self.mapper_list = False
self.parameter_list = False
self.measure_cputime = False
self.measure_preload = False
self.report_name = None
<|code_end|>
, generate the next line using the imports in this file:
from lib import teaser
from datetime import datetime
from lib import test
from lib import util
from lib import report
import os
import time
import copy
import sys
import pickle
import yaml
import argparse
import hashlib
import traceback
import fnmatch
and context (functions, classes, or occasionally code) from other files:
# Path: lib/test.py
# class Test:
# def __init__(self, id, name, directory, mate, mapper):
# def _(self, field, default=None):
# def setc(self, field, new_value):
# def getReportDirectory(self):
# def log(self, text, level=2, newline="\n"):
# def dbg(self, text, prefix="INFO"):
# def warn(self, text, affected_file=None, affected_pos=None):
# def error(self, text, affected_file=None, affected_pos=None):
# def fatal_error(self, text, affected_file=None, affected_pos=None):
# def getWarnings(self):
# def getErrors(self):
# def getSuccess(self):
# def getErrorCount(self):
# def getWarningCount(self):
# def getComment(self):
# def getVersionHash(self):
# def serialize(self):
# def unserialize(self, ser):
# def getLocals(self):
# def buildAbsoluteScriptPath(self, filename):
# def getTestDirectoryByPath(self, test_name_full):
# def getTestNameByPath(self, test_name_full):
# def load(self):
# def getParentTest(self):
# def evaluate(self):
# def getMapper(self):
# def getName(self):
# def getFullName(self):
# def getId(self):
# def getTitle(self):
# def getPath(self):
# def getConfig(self):
# def getRunTime(self):
# def getCreateTime(self):
# def getShouldRun(self):
# def getWasRun(self):
# def getWasFinished(self):
# def getSuccess(self):
# def getIsBasic(self):
# def getResultOverviewText(self, indent=""):
# def consoleReport(self):
# def executePipeline(self, event, args=()):
# def run(self):
# def sub(self,command,description="",detailed=False):
# def enterWorkingDirectory(self):
# def restoreWorkingDirectory(self):
# def cleanup(self):
# def setRunResults(self, results):
# def getRunResults(self):
# def setHumanizedRunResults(self, results):
# def getHumanizedRunResults(self):
# def getSubResults(self):
# def getComparisonTest(self):
# def setComparisonTest(self, comp):
# def getCSVPath(self,title):
# def writeCSV(self,title,csv):
#
# Path: lib/util.py
# STATUS_NORMAL=1
# STATUS_MAX_MEMORY_EXCEEDED=2
# STATUS_MAX_RUNTIME_EXCEEDED=3
# MAX_LEN_OUT = 10000
# def runAndMeasure(command,detailed=True,maxtime=0,maxmem=0):
# def runSimple(command):
# def runAndMeasureInternal(return_queue,command,maxtime=0,maxmem=0):
# def runInternal(control_queue,command,max_memory):
# def measureProcess(queue, initial_pids, command, measurement_interval=1, max_runtime=0, max_memory=0, debug=False):
# def extendTargets(targets, proc):
# def killTargets(targets):
# def updateTargets(targets, metrics):
# def updateMetrics(target, metrics):
# def loadConfig(name, parent_dir="", already_included=[]):
# def setCallDir(d):
# def setRootDir(d):
# def enterCallDir():
# def enterRootDir():
# def getRootDir():
# def nl2br(text):
# def msg(text="", level=1):
# def yes_no(b):
# def md5(text):
# def merge(x, y):
# def formatFilesize(n):
# def percent(val, base, offset=0):
# def abs_path(path):
# def get_sam_header_line_count(filename):
# def is_sam_sorted(filename):
# def sort_sam(filename,threads=1):
# def sort_sam_picard(filename,threads=-1):
# def line_count(filename):
# def sanitize_string(s):
# def makeExportDropdown(plot_id,csv_filename):
# def parseMD(md,seq):
#
# Path: lib/report.py
# class ReportHTMLGenerator:
# def __init__(self, mate, plotgen):
# def nltobr(self, text):
# def write(self, text):
# def openPanel(self, title="Panel", style="default"):
# def closePanel(self):
# def collapsible(self, heading, text, opened=False):
# def openCollapsiblePanel(self, heading, opened=False):
# def closeCollapsiblePanel(self):
# def getMapperBinaryPath(self, mapper):
# def makeTestNavList(self):
# def makeTestMapperNavList(self, test_objects):
# def generateMainErrorList(self):
# def generateErrorList(self, test):
# def generateMainErrorList(self):
# def generateTestList(self):
# def generateSetup(self):
# def generateLogs(self):
# def generateSubprocessOutputs(self, test):
# def generateOverviewPlot(self, page, measure):
# def generate(self):
# def generateProgress(self):
. Output only the next line. | self.report = False |
Next line prediction: <|code_start|> self.enterWorkingDirectory()
platform_ids = {"illumina":0,"ion_torrent":2}
params = ""
if self.dataset["platform"] == "ion_torrent":
params += " -f TACGTACGTCTGAGCATCGATCGATGTACAGC "
read_length_1 = str(self.dataset["read_length"])
if self.dataset["paired"]:
read_length_2 = read_length_1
read_2_fastq2sam = " dwgout.bwa.read2.fastq"
read_count = int(self.dataset["read_count"]/2)
else:
read_length_2 = "0"
read_2_fastq2sam = ""
read_count = self.dataset["read_count"]
if self.dataset["insert_size"] != None:
params += " -d %d -s %d " % (self.dataset["insert_size"],self.dataset["insert_size_error"])
if self.dataset["error_rate_mult"] != 1:
self.dataset["extra_params"] += " -e %f " % (self.dataset["error_rate_mult"] * 0.02)
params += " -r %f " % self.dataset["mutation_rate"]
params += " -R %f " % self.dataset["mutation_indel_frac"]
self.dataset["simulator_cmd"] = self.bin_path + " -c " + str(platform_ids[self.dataset["platform"]]) + " -1 " + read_length_1 + " -2 " + read_length_2 + " -N " + str(read_count) + params + " -y 0 " + self.dataset["extra_params"] + " " + self.dataset["reference_sim"] + " dwgout"
self.subprogram(self.dataset["simulator_cmd"])
<|code_end|>
. Use current file imports:
(import os
import shutil
import time
import yaml
from lib import util
from lib import gsample
from tools import fastq2sam)
and context including class names, function names, or small code snippets from other files:
# Path: lib/util.py
# STATUS_NORMAL=1
# STATUS_MAX_MEMORY_EXCEEDED=2
# STATUS_MAX_RUNTIME_EXCEEDED=3
# MAX_LEN_OUT = 10000
# def runAndMeasure(command,detailed=True,maxtime=0,maxmem=0):
# def runSimple(command):
# def runAndMeasureInternal(return_queue,command,maxtime=0,maxmem=0):
# def runInternal(control_queue,command,max_memory):
# def measureProcess(queue, initial_pids, command, measurement_interval=1, max_runtime=0, max_memory=0, debug=False):
# def extendTargets(targets, proc):
# def killTargets(targets):
# def updateTargets(targets, metrics):
# def updateMetrics(target, metrics):
# def loadConfig(name, parent_dir="", already_included=[]):
# def setCallDir(d):
# def setRootDir(d):
# def enterCallDir():
# def enterRootDir():
# def getRootDir():
# def nl2br(text):
# def msg(text="", level=1):
# def yes_no(b):
# def md5(text):
# def merge(x, y):
# def formatFilesize(n):
# def percent(val, base, offset=0):
# def abs_path(path):
# def get_sam_header_line_count(filename):
# def is_sam_sorted(filename):
# def sort_sam(filename,threads=1):
# def sort_sam_picard(filename,threads=-1):
# def line_count(filename):
# def sanitize_string(s):
# def makeExportDropdown(plot_id,csv_filename):
# def parseMD(md,seq):
#
# Path: lib/gsample.py
# def log(msg):
# def index(reference, fastindex_path = "tools/fastindex"):
# def index_legacy(reference):
# def downsample(index, contig_filename, downsampled_filename, region_count, target_len, single_contig=False,
# region_list=False, spacer_len=200):
# def csample(infile, region_size, sample_fraction, spacer_len=200, fastindex_path=""):
# def ctranslate(reference_file, sampled_index_file, sam_file, target_file, fastindex_path=""):
#
# Path: tools/fastq2sam.py
# def encode_qname(qname, retain_petag=True):
# def __init__(self):
# def __init__(self, filename, pe):
# def readline(self):
# def next_read(self):
# def __init__(self):
# def align(read):
# def align(self, read, paired=False, is_read1=True):
# def align_pair(self, read1, read2):
# def align(self, read, paired=False, is_read1=True):
# def align_pair(self, read1, read2):
# def __init__(self, aligner, outfile):
# def write(self, what):
# def write_sam_header(self, reads):
# def write_single(self, read, to):
# def align_se(self, infile):
# def align_pe(self, infile_1, infile_2):
# class Object:
# class FASTQ:
# class Aligner:
# class DummyAligner(Aligner):
# class dwgsim(Aligner):
# class Converter:
. Output only the next line. | aligner = fastq2sam.dwgsim() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.