Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|>class CSVStorage(FileStorageBase): name = 'csv' extension = 'csv' def load_accounts(self): filename = self.get_accounts_filename() if not os.path.exists(filename): return [] with codecs.open(filename) as f: return map(self._csv_ro...
return Account(row[0], row[1], float(row[2]))
Using the snippet: <|code_start|> def load_accounts(self): filename = self.get_accounts_filename() if not os.path.exists(filename): return [] with codecs.open(filename) as f: return map(self._csv_row_to_account, unicodecsv.reader(f)) def load_transactions(self, f...
return Transaction(row[0], row[1], datetime.datetime.strptime(row[2], "%Y-%m-%d").date(),
Based on the snippet: <|code_start|> def get_storage(name): for o in globals().values(): if inspect.isclass(o) and issubclass(o, StorageBase) and o is not StorageBase and o.name == name: return o class StorageBase(object): def __init__(self, config): self.config = config def ...
for date in period_to_months(start_date, end_date):
Given the following code snippet before the placeholder: <|code_start|> def get_storage(name): for o in globals().values(): if inspect.isclass(o) and issubclass(o, StorageBase) and o is not StorageBase and o.name == name: return o class StorageBase(object): def __init__(self, config): ...
return filter_transactions_period(transactions, start_date, end_date)
Based on the snippet: <|code_start|> class Command(BaseCommand): help = "Create set of new pastes" args = "[how many]" def handle(self, how_many=100, **options): for i in range(int(how_many)): <|code_end|> , predict the immediate next line with the help of imports: from django.core.management.bas...
w = Wklejka(**wklejka())
Based on the snippet: <|code_start|> def get_txt(self, obj): url = obj.get_txt_url() response = self.client.get(url) self.assertEquals(response.status_code, 200) self.assertEquals(response._headers['content-type'], ('Content-Type', 'text/plain; charset=utf-8...
new_obj = Wklejka.objects.get(pk=obj.id)
Based on the snippet: <|code_start|> def test_private_url(self): w = Wklejka(is_private=True, hash="foobar", user=self.user) w.save() self.get(w) self.get_txt(w) self.get_dl(w) self.get_del(w) self.post_del(w) def test_banned_lexer(self): w = Wklej...
userprofile = UserProfile(user=self.user)
Here is a snippet: <|code_start|> class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) display_name = models.CharField(max_length=30) current_salt = models.CharField(max_length=50) def __unicode__(self): return self.user.username def username(self): return ...
new_salt = generate_salt()
Predict the next line after this snippet: <|code_start|> class WklejkaTestCase(TestCase): def test_author(self): user = User(username="joedoe") <|code_end|> using the current file's imports: from apps.wklej.models import Wklejka from django.contrib.auth.models import User from django.test import TestCa...
self.wklejka = Wklejka(
Predict the next line after this snippet: <|code_start|>#coding: utf-8 def single(request, id=0, hash=''): """ This is very important view because it displays a single paste. It's actually the most viewed view ever """ if id: <|code_end|> using the current file's imports: from django.contrib.a...
w = get_object_or_404(Wklejka, pk=id, is_private=False)
Continue the code snippet: <|code_start|>#coding: utf-8 def single(request, id=0, hash=''): """ This is very important view because it displays a single paste. It's actually the most viewed view ever """ if id: w = get_object_or_404(Wklejka, pk=id, is_private=False) elif hash: ...
if hl in BANNED_LEXERS:
Based on the snippet: <|code_start|>dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) # Py 2.5 # model def rpc_handler(request): """ the actual handler: if you setup your urls.py properly, all calls to the xml-rpc service should be routed through here. If post data is defined,...
w = Wklejka(nickname=autor, body=tresc, syntax=syntax)
Next line prediction: <|code_start|> """ Pozwala zdalnie dodawac wpisy do wkleja. """ w = Wklejka(nickname=autor, body=tresc, syntax=syntax) w.save() return w.get_absolute_url() def dodaj_prywatny_wpis(tresc, syntax, autor="Anonim"): """ Pozwala zdalnie dodawać prywatne wpisy do wklej...
p = UserProfile.objects.get(current_salt=salt)
Using the snippet: <|code_start|>#coding: utf-8 class WklejAdmin(admin.ModelAdmin): list_display = ['user', 'nickname', 'syntax', 'is_private'] search_fields = ['user', 'nickname', 'comment', 'body', 'ip'] list_filter = ['is_private', 'is_deleted', 'is_spam'] raw_id_fields = ['parent', ] <|code_end...
admin.site.register(Wklejka, WklejAdmin)
Given snippet: <|code_start|>#-*- coding: utf-8 -*- class WklejkaForm(forms.ModelForm): nickname = forms.CharField(required=False) class Meta: <|code_end|> , continue by predicting the next line. Consider current file imports: from django import forms from apps.wklej.models import Wklejka from lib.antispa...
model = Wklejka
Next line prediction: <|code_start|>#-*- coding: utf-8 -*- class WklejkaForm(forms.ModelForm): nickname = forms.CharField(required=False) class Meta: model = Wklejka fields = '__all__' def clean_nickname(self): if len(self.cleaned_data['nickname']) == 0: self.cleane...
if settings.USE_CAPTCHA and check_for_link_spam(self.cleaned_data['body']):
Next line prediction: <|code_start|> return self.cleaned_data['nickname'] def clean_body(self): if settings.USE_CAPTCHA and check_for_link_spam(self.cleaned_data['body']): raise forms.ValidationError("This paste looks like spam.") return self.cleaned_data['body'] # TODO: FIXME:...
widget=forms.Select(choices=LEXERS))
Given the code snippet: <|code_start|>#-*- coding: utf-8 -*- def homepage(request): """ This view is responsible for displaying form on the homepage. This is actualy all what it's doing. it displays, validate, and submits new paste into database. """ if not request.method == 'POST': ...
form = WklejkaForm(initial={'syntax': syntax})
Predict the next line after this snippet: <|code_start|>#-*- coding: utf-8 -*- def homepage(request): """ This view is responsible for displaying form on the homepage. This is actualy all what it's doing. it displays, validate, and submits new paste into database. """ if not request.method =...
form = WklejkaCaptchaForm(request.POST)
Next line prediction: <|code_start|> class UserProfileTest(TestCase): def setUp(self): self.user = User(username="foobar") self.user.save() self.wklejka = Wklejka(user=self.user, body="foobarbaz").save() <|code_end|> . Use current file imports: (from apps.userstuff.models import UserProfi...
self.userprofile = UserProfile(user=self.user)
Given the code snippet: <|code_start|> class UserProfileTest(TestCase): def setUp(self): self.user = User(username="foobar") self.user.save() <|code_end|> , generate the next line using the imports in this file: from apps.userstuff.models import UserProfile from apps.wklej.models import Wklejka f...
self.wklejka = Wklejka(user=self.user, body="foobarbaz").save()
Predict the next line after this snippet: <|code_start|> ### single paste: url(r'^id/(?P<id>\d+)/$', 'wklej.views.single', name="single"), # and it's txt version: url(r'^id/(?P<id>\d+)/txt/$', 'wklej.views.txt', name="txt"), # and it's downloadable: url(r'^id/(?P<id>\d+)/dl/$', 'wklej.views.down...
{'profile_callback': UserProfile.objects.create},
Using the snippet: <|code_start|> 'django.contrib.auth.views.password_reset', {"template_name": 'registration/password_reset_form.html'}, name="password_reset"), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm', {'temp...
(r'^xmlrpc/$', rpc_handler),
Given the code snippet: <|code_start|> ''' connection = pika.BlockingConnection(pika.ConnectionParameters( host=host)) channel = connection.channel() channel.exchange_declare(exchange=exchange_info[0], exchange_type=exchange_info[1]) chann...
if signal == application_created:
Here is a snippet: <|code_start|> connection = pika.BlockingConnection(pika.ConnectionParameters( host=host)) channel = connection.channel() channel.exchange_declare(exchange=exchange_info[0], exchange_type=exchange_info[1]) channel.basic_publish(e...
elif signal == application_accepted_by_reviewer:
Using the snippet: <|code_start|> host=host)) channel = connection.channel() channel.exchange_declare(exchange=exchange_info[0], exchange_type=exchange_info[1]) channel.basic_publish(exchange=exchange_info[0], routing_key=routing, ...
elif signal == application_rejected_by_reviewer:
Here is a snippet: <|code_start|> class CommitteeTestCase(TestCase): def test_fields(self): ''' This model requires a committee member and the optional count should default to 0. ''' <|code_end|> . Write the next line using the current file imports: from django...
self.assertRaises(IntegrityError, Committee.objects.create)
Predict the next line after this snippet: <|code_start|> class CommitteeTestCase(TestCase): def test_fields(self): ''' This model requires a committee member and the optional count should default to 0. ''' self.assertRaises(IntegrityError, Committee.obje...
self.assertIsInstance(Committee.objects, CommitteeManager)
Continue the code snippet: <|code_start|>''' This will test the forms code for the ethicsapplication application Created on Jul 25, 2012 @author: jasonmarshall ''' class FormsTest(TestCase): def test_EthicsApplication_form_title(self): ''' Check that the form provdes a field that cannot ...
form = EthicsApplicationForm()
Here is a snippet: <|code_start|> class FullApplicationChecklistLinkTestCase(TestCase): def test_fields(self): ''' This model should specify the following fields: checklist_question - ForeignKey(Question) included_group - ForeignKey (QuestionGroup) orde...
self.assertRaises(IntegrityError, FullApplicationChecklistLink.objects.create)
Next line prediction: <|code_start|> class FullApplicationChecklistLinkTestCase(TestCase): def test_fields(self): ''' This model should specify the following fields: checklist_question - ForeignKey(Question) included_group - ForeignKey (QuestionGroup) o...
self.assertIsInstance(FullApplicationChecklistLink.objects, FullApplicationChecklistLinkManager)
Given the following code snippet before the placeholder: <|code_start|> It is thisobject that will be manipulated by the workflow engine. ''' title = models.CharField(max_length=255, default=None) #default=None stops null strings which effectively makes it mandatory principle_investigator = ...
application_created.send(sender=self, application=self)
Next line prediction: <|code_start|># copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS ...
fupload = FileUpload.get_by_path(filename)
Given the code snippet: <|code_start|># Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, dist...
Page.query
Predict the next line for this snippet: <|code_start|>""" class test_branchScale_ExpCM(unittest.TestCase): """Tests `branchScale` of `ExpCM_empirical_phi` model.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-argument...
phi = numpy.random.dirichlet([7] * N_NT)
Here is a snippet: <|code_start|>"""Tests branch scaling. Makes sure we can correctly re-scale branch lengths into units of substitutions per site. Written by Jesse Bloom. """ class test_branchScale_ExpCM(unittest.TestCase): """Tests `branchScale` of `ExpCM_empirical_phi` model.""" # use approach here to ...
rprefs = numpy.random.dirichlet([1] * N_AA)
Here is a snippet: <|code_start|>"""Tests branch scaling. Makes sure we can correctly re-scale branch lengths into units of substitutions per site. Written by Jesse Bloom. """ class test_branchScale_ExpCM(unittest.TestCase): """Tests `branchScale` of `ExpCM_empirical_phi` model.""" # use approach here to ...
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Continue the code snippet: <|code_start|> # create initial ExpCM g = numpy.random.dirichlet([3] * N_NT) omega = 0.7 kappa = 2.5 beta = 1.2 self.expcm = (phydmslib.models .ExpCM_empirical_phi(self.prefs, g=g, omega=omega, ...
for x in range(N_CODON):
Given the following code snippet before the placeholder: <|code_start|>"""Tests `phydmslib.models.ExpCM_empirical_phi` class. Written by Jesse Bloom. """ class testExpCM_empirical_phi(unittest.TestCase): """Tests ``ExpCM`` with empirical phi.""" def test_ExpCM_empirical_phi(self): """Initialize `E...
g = numpy.random.dirichlet([3] * N_NT)
Predict the next line for this snippet: <|code_start|> omega = 0.7 kappa = 2.5 beta = 1.2 self.expcm = (phydmslib.models .ExpCM_empirical_phi(self.prefs, g=g, omega=omega, kappa=kappa, beta=beta)) self.assertTrue(num...
nt_freqs[w] += self.expcm.prx[r][x] * CODON_NT_COUNT[w][x]
Given snippet: <|code_start|>"""Tests `phydmslib.models.ExpCM_empirical_phi` class. Written by Jesse Bloom. """ class testExpCM_empirical_phi(unittest.TestCase): """Tests ``ExpCM`` with empirical phi.""" def test_ExpCM_empirical_phi(self): """Initialize `ExpCM_empirical_phi`, test, update, test ag...
self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Predict the next line after this snippet: <|code_start|>"""Tests `phydmslib.models.ExpCM_empirical_phi` class. Written by Jesse Bloom. """ class testExpCM_empirical_phi(unittest.TestCase): """Tests ``ExpCM`` with empirical phi.""" def test_ExpCM_empirical_phi(self): """Initialize `ExpCM_empirical_...
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Here is a snippet: <|code_start|> [pirAy, random.uniform(0.01, 0.5)], [omega, random.uniform(0.1, 2.0)]] self.assertTrue(abs(values[1][1] - values[2][1]) > diffpref, "choose another random number seed as pirAx and " ...
if CODON_TO_AA[x] == CODON_TO_AA[y]:
Given the code snippet: <|code_start|> (1 - (pirAx / pirAy)**beta)) dFrxy_dpirAx = ((-omega * beta / pirAx) * ((pirAx / pirAy)**beta * (sympy.ln((pirAx / pirAy)**beta) - 1) + 1) / ((1 - (pirAx / pirAy)**beta)**2)) dFr...
for x in range(N_CODON):
Given the following code snippet before the placeholder: <|code_start|> (self .assertTrue((numpy .allclose(float(dFrxy_dpirAx_equal .subs(values.items()) ...
rprefs = numpy.random.dirichlet([0.7] * N_AA)
Given the following code snippet before the placeholder: <|code_start|> ), (-expcm_fitprefs .tildeFrxy[r][x][y]) / values[pirAx])))) ...
self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Given snippet: <|code_start|> self.assertTrue(numpy.allclose( float(dFrxy_dpirAy_equal .subs(values.items())), expcm_fitprefs.tildeFrxy[r][x][y] / ...
phi=numpy.random.dirichlet([5] * N_NT)
Here is a snippet: <|code_start|> """Test that `TreeLikelihood` initializes properly.""" tl = (phydmslib.treelikelihood .TreeLikelihood(self.tree, self.alignment, self.model, underflowfreq=self.underfl...
x = random.randint(0, N_CODON - 1)
Given snippet: <|code_start|> class test_BrLenDerivatives_ExpCM(unittest.TestCase): """`TreeLikelihood` branch length derivatives for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydms...
e_pw = numpy.ndarray((3, N_NT), dtype='float')
Here is a snippet: <|code_start|> os.remove(tempfile) # simulate alignment with pyvolve pyvolvetree = pyvolve.read_tree(tree=self.newick) self.nsites = 50 self.nseqs = self.tree.count_terminals() e_pw = numpy.ndarray((3, N_NT), dtype='float') e_pw.fill(0.25) ...
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Continue the code snippet: <|code_start|> with open(tempfile, 'w') as f: f.write(self.newick) self.tree = Bio.Phylo.read(tempfile, 'newick') os.remove(tempfile) # simulate alignment with pyvolve pyvolvetree = pyvolve.read_tree(tree=self.newick) self.nsites = 5...
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Given snippet: <|code_start|>"""Tests ``--diffprefsbysite`` option to ``phydms`` on simulated data. Written by Jesse Bloom. """ matplotlib.use('pdf') class test_DiffPrefsBySiteExpCM(unittest.TestCase): """Tests ``--diffprefsbysite`` to ``phydms`` for `ExpCM`.""" gammaomega_arg = [] def setUp(self): ...
aas = [INDEX_TO_AA[a] for a in range(N_AA)]
Next line prediction: <|code_start|>"""Tests ``--diffprefsbysite`` option to ``phydms`` on simulated data. Written by Jesse Bloom. """ matplotlib.use('pdf') class test_DiffPrefsBySiteExpCM(unittest.TestCase): """Tests ``--diffprefsbysite`` to ``phydms`` for `ExpCM`.""" gammaomega_arg = [] def setUp(s...
aas = [INDEX_TO_AA[a] for a in range(N_AA)]
Using the snippet: <|code_start|> matplotlib.use('pdf') class test_DiffPrefsBySiteExpCM(unittest.TestCase): """Tests ``--diffprefsbysite`` to ``phydms`` for `ExpCM`.""" gammaomega_arg = [] def setUp(self): """Set up test.""" random.seed(1) numpy.random.seed(1) self.tree =...
rprefs[AA_TO_INDEX[self.targetaas[r]]] = hipref
Using the snippet: <|code_start|> J. Kyte & R. F. Doolittle: "A simple method for displaying the hydropathic character of a protein." J Mol Biol, 157, 105-132 More positive values indicate higher hydrophobicity, while more negative values indicate lower hydrophobicity. The returned ...
aas = sorted(AA_TO_INDEX.keys())
Using the snippet: <|code_start|> 'kd'(Kyte-Doolittle hydrophobicity scale, default), 'mw' (molecular weight), 'functionalgroup' (functional groups: small, nucleophilic, hydrophobic, aromatic, basic, acidic, and amide), 'charge' (charge at neutral pH), and 'singlecolor'. If 'charge' i...
if set(characters) == set(NT_TO_INDEX.keys()):
Given the following code snippet before the placeholder: <|code_start|> # re-set to old value, make sure return to original values tl.paramsarray = copy.deepcopy(paramsarray) self.assertTrue(numpy.allclose(logl, tl.loglik)) for (param, value) in modelparams.items(): self.asser...
partials = numpy.zeros(shape=(self.nsites, N_CODON))
Here is a snippet: <|code_start|> # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM DISTRIBUTIONMODEL = None def setUp(self): """Set up parameters for test.""" r...
e_pw = numpy.ndarray((3, N_NT), dtype="float")
Given the code snippet: <|code_start|> info = "_temp_info.txt" rates = "_temp_ratefile.txt" evolver = pyvolve.Evolver(partitions=partitions, tree=pyvolvetree) evolver(seqfile=alignment, infofile=info, ratefile=rates) self.alignment = [(s.description, str(s.seq)) ...
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Predict the next line after this snippet: <|code_start|> yngkp_m0 = phydmslib.models.YNGKP_M0(e_pw, self.nsites) partitions = phydmslib.simulate.pyvolvePartitions(yngkp_m0) alignment = "_temp_simulatedalignment.fasta" info = "_temp_info.txt" rates = "_temp_ratefile.txt" ev...
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Here is a snippet: <|code_start|> i = name[-1] # node number self.brlen[int(i)] = float(brlen) # simulate alignment with pyvolve pyvolvetree = pyvolve.read_tree(tree=self.newick) self.nsites = 60 self.nseqs = self.tree.count_terminals() e_pw = num...
self.codons[i][r] = CODON_TO_INDEX[codon]
Here is a snippet: <|code_start|>"""Tests `phydmslib.models.GammaDistributedBetaModel` class. Written by Jesse Bloom and Sarah Hilton. """ class test_GammaBeta_ExpCM(unittest.TestCase): """Test gamma distributed beta for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com...
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Here is a snippet: <|code_start|> Written by Jesse Bloom and Sarah Hilton. """ class test_GammaBeta_ExpCM(unittest.TestCase): """Test gamma distributed beta for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with...
paramvalues = {"eta": numpy.random.dirichlet([5] * (N_NT - 1)),
Next line prediction: <|code_start|>"""Tests `phydmslib.models.GammaDistributedBetaModel` class. Written by Jesse Bloom and Sarah Hilton. """ class test_GammaBeta_ExpCM(unittest.TestCase): """Test gamma distributed beta for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow....
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Based on the snippet: <|code_start|> class test_simulateAlignment_ExpCM(unittest.TestCase): """Tests `simulateAlignment` of `simulate.py` module.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phyd...
phi = numpy.random.dirichlet([7] * N_NT)
Predict the next line after this snippet: <|code_start|> Makes sure we can correctly simulate an alignment given a model and a tree. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateAlignment_ExpCM(unittest.TestCase): """Tests `simulateAlignment` of `simulate.py` module.""" # use approach he...
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Next line prediction: <|code_start|>"""Tests alignment simulation. Makes sure we can correctly simulate an alignment given a model and a tree. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateAlignment_ExpCM(unittest.TestCase): """Tests `simulateAlignment` of `simulate.py` module.""" # use ...
rprefs = numpy.random.dirichlet([1] * N_AA)
Using the snippet: <|code_start|>"""Tests the calculation of spielmanwr, following Spielman and Wilke, 2015. Written by Jesse Bloom and Sarah Hilton. """ class testExpCM_spielmanwr(unittest.TestCase): """Test the calculation of `spielmanwr` using the model `ExpCM`.""" # use approach here to run multiple t...
g = numpy.random.dirichlet([5] * N_NT)
Continue the code snippet: <|code_start|>"""Tests the calculation of spielmanwr, following Spielman and Wilke, 2015. Written by Jesse Bloom and Sarah Hilton. """ class testExpCM_spielmanwr(unittest.TestCase): """Test the calculation of `spielmanwr` using the model `ExpCM`.""" # use approach here to run mu...
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Next line prediction: <|code_start|>"""Tests the calculation of spielmanwr, following Spielman and Wilke, 2015. Written by Jesse Bloom and Sarah Hilton. """ class testExpCM_spielmanwr(unittest.TestCase): """Test the calculation of `spielmanwr` using the model `ExpCM`.""" # use approach here to run multipl...
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Predict the next line after this snippet: <|code_start|> # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM def testExpCM_spielmanwr(self): """Test the `ExpCM` function `_spielman_wr`.""" # create models ra...
for x in range(N_CODON):
Predict the next line after this snippet: <|code_start|> def testExpCM_spielmanwr(self): """Test the `ExpCM` function `_spielman_wr`.""" # create models random.seed(1) numpy.random.seed(1) nsites = 10 g = numpy.random.dirichlet([5] * N_NT) prefs = [] m...
if CODON_SINGLEMUT[x][y] and CODON_NONSYN[x][y]:
Based on the snippet: <|code_start|> def testExpCM_spielmanwr(self): """Test the `ExpCM` function `_spielman_wr`.""" # create models random.seed(1) numpy.random.seed(1) nsites = 10 g = numpy.random.dirichlet([5] * N_NT) prefs = [] minpref = 0.01 ...
if CODON_SINGLEMUT[x][y] and CODON_NONSYN[x][y]:
Based on the snippet: <|code_start|>""" class test_simulateRandomSeed_ExpCM(unittest.TestCase): """Tests `simulate.simulateAlignment` module with different seeds.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-argumen...
phi = numpy.random.dirichlet([7] * N_NT)
Continue the code snippet: <|code_start|>"""Tests random number seeding in aligment simulation. Makes sure the random numbering seeding gives reproducible results. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateRandomSeed_ExpCM(unittest.TestCase): """Tests `simulate.simulateAlignment` module w...
rprefs = numpy.random.dirichlet([1] * N_AA)
Based on the snippet: <|code_start|>"""Tests random number seeding in aligment simulation. Makes sure the random numbering seeding gives reproducible results. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateRandomSeed_ExpCM(unittest.TestCase): """Tests `simulate.simulateAlignment` module with d...
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Predict the next line after this snippet: <|code_start|> "--brlen", "scale"]) omegabysitefile = simulateprefix + "_omegabysite.txt" omegas = pandas.read_csv(omegabysitefile, sep="\t", comment="#") divpressureomegas = omegas[omegas["site"].isin(divpressuresites)] ...
e_pw = numpy.full((3, N_NT), 1.0 / N_NT, dtype="float")
Here is a snippet: <|code_start|>"""Tests `phydmslib.models.YNGKP_M0` class. Written by Jesse Bloom. Edited by Sarah Hilton Uses `sympy` to make sure attributes and derivatives of attributes are correct for `YNGKP_M0` implemented in `phydmslib.models`. """ class testYNGKP_M0(unittest.TestCase): """Test YNGKP ...
self.e_pa = numpy.random.uniform(0.12, 1.0, size=(3, N_NT))
Continue the code snippet: <|code_start|> omega = 0.4 kappa = 2.5 self.YNGKP_M0 = phydmslib.models.YNGKP_M0( self.e_pa, self.nsites, omega=omega, kappa=kappa) self.assertTrue(numpy.allclose(omega, self.YNGKP_M0.omega)) self.assertTrue(numpy.allclose(kappa, self.YNGKP_M...
diag = numpy.eye(N_CODON, dtype="bool")
Next line prediction: <|code_start|> divsites = [] assert all((1 <= r <= model.nsites for r in divsites)) partitions = [] for r in range(model.nsites): matrix = numpy.zeros((len(codons), len(codons)), dtype='float') for (xi, x) in enumerate(codons): for (yi, y) in enumer...
qxy *= model.phi[NT_TO_INDEX[ynt]]
Given the code snippet: <|code_start|> assert all((1 <= r <= model.nsites for r in divsites)) partitions = [] for r in range(model.nsites): matrix = numpy.zeros((len(codons), len(codons)), dtype='float') for (xi, x) in enumerate(codons): for (yi, y) in enumerate(codons): ...
pix = model.pi[r][AA_TO_INDEX[xaa]]**model.beta
Given snippet: <|code_start|> partitions = [] for r in range(model.nsites): matrix = numpy.zeros((len(codons), len(codons)), dtype='float') for (xi, x) in enumerate(codons): for (yi, y) in enumerate(codons): ntdiffs = [(x[j], y[j]) for j in range(3) if x[j] != y[j]] ...
if abs(pix - piy) > ALMOST_ZERO:
Given the following code snippet before the placeholder: <|code_start|>"""Tests alignment simulation. Makes sure we can correctly simulate an alignment given an `ExpCM` with divpressure and a tree. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateAlignment_ExpCM_divselection(unittest.TestCase): ...
rprefs = numpy.random.dirichlet([1] * N_AA)
Predict the next line after this snippet: <|code_start|>Makes sure we can correctly simulate an alignment given an `ExpCM` with divpressure and a tree. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateAlignment_ExpCM_divselection(unittest.TestCase): """Tests `simulateAlignment` of `simulate.py` m...
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Given the following code snippet before the placeholder: <|code_start|> """Tests `simulateAlignment` of `simulate.py` module.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_emp...
g = numpy.random.dirichlet([7] * N_NT)
Continue the code snippet: <|code_start|> def tfunc(x): """Negative log likelihood when `x` is branch lengths.""" self.t = x return -self.loglik def tdfunc(x): """Negative gradient loglik with respect to branch lengths.""" self.t = x ...
'bounds': [(ALMOST_ZERO, None)] * len(self.t),
Continue the code snippet: <|code_start|> else: self._dLshape[param] = (len(paramvalue), self.nsites, N_CODON) else: raise ValueError("Cannot handle param: {0}, {1}".format( ...
elif codon in CODON_TO_INDEX:
Given the code snippet: <|code_start|> assert all({len(seq) == 3 * self.nsites for (head, seq) in alignment}) assert set({head for (head, seq) in alignment} ) == {clade.name for clade in tree.get_terminals()} self.alignment = copy.deepcopy(alignment) self.nseqs = len(al...
self._Lshape = (self.model.ncats, self.nsites, N_CODON)
Next line prediction: <|code_start|> """`TreeLikelihood` branch length optimization for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM DISTRIBUTIONMODEL = None ...
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Based on the snippet: <|code_start|> class test_BrLenOptimize_ExpCM(unittest.TestCase): """`TreeLikelihood` branch length optimization for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = ph...
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Predict the next line for this snippet: <|code_start|>"""Tests `phydmslib.models.GammaDistributedOmegaModel` class. Written by Jesse Bloom. """ class test_GammaDistributedOmega_ExpCM(unittest.TestCase): """Test gamma distributed omega for `ExpCM`.""" # use approach here to run multiple tests: # http:/...
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Given snippet: <|code_start|>"""Tests `phydmslib.models.GammaDistributedOmegaModel` class. Written by Jesse Bloom. """ class test_GammaDistributedOmega_ExpCM(unittest.TestCase): """Test gamma distributed omega for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questi...
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Given the code snippet: <|code_start|>"""Tests `phydmslib.models.GammaDistributedOmegaModel` class. Written by Jesse Bloom. """ class test_GammaDistributedOmega_ExpCM(unittest.TestCase): """Test gamma distributed omega for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.c...
paramvalues = {"eta": numpy.random.dirichlet([5] * (N_NT - 1)),
Given the code snippet: <|code_start|> `kappa`, `omega`, `beta`, `mu`, `phi` Model params described in main class doc string. `freeparams` (list of strings) Specifies free parameters. """ self._nsites = len(prefs) assert self.nsites > 0, "No...
self.pi_codon = numpy.full((self.nsites, N_CODON), -1, dtype='float')
Continue the code snippet: <|code_start|> def _update_pi_vars(self): """Update variables that depend on `pi`. These are `pi_codon`, `ln_pi_codon`, `piAx_piAy`, `piAx_piAy_beta`, `ln_piAx_piAy_beta`. Update using current `pi` and `beta`. """ with numpy.errstate(divide...
where=numpy.logical_and(CODON_NONSYN, numpy.fabs(1 - self.piAx_piAy_beta) # noqa: E501
Given the following code snippet before the placeholder: <|code_start|> dM_param[j] = (broadcastMatrixVectorMultiply(self.A, broadcastGetCols(broadcastMatrixMultiply(self.B[param][j] * V, self.Ainv), tips))) # noqa: E501 if gaps is not None:...
self.Qxy[CODON_TRANSITION] *= self.kappa
Given the code snippet: <|code_start|> gene-wide `omega`. Returns: `wr` (list) list of `omega_r` values of length `nsites` Following `Spielman and Wilke, MBE, 32:1097-1108 <https://doi.org/10.1093/molbev/msv003>`_, we c...
j = numpy.where((CODON_SINGLEMUT[i] * CODON_NONSYN[i]) == 1)[0]
Given the code snippet: <|code_start|> `dprx` (dict) Keyed by strings in `freeparams`, each value is `numpy.ndarray` of floats giving derivative of `prx` with respect to that param, or 0 if if `prx` does not depend on parameter. The shape of each array is `(nsites,...
'pi': (ALMOST_ZERO, 1),
Given the code snippet: <|code_start|> """Update `B`.""" for param in self.freeparams: if param == 'mu': continue paramval = getattr(self, param) if isinstance(paramval, float): self.B[param] = (broadcastMatrixMultiply(self.Ainv, ...
boolterm += ((i <= CODON_NT_INDEX[j]).astype('float')
Here is a snippet: <|code_start|> return bs @property def nsites(self): """See docs for `Model` abstract base class.""" return self._nsites @property def freeparams(self): """See docs for `Model` abstract base class.""" return self._freeparams @property ...
codonFrequency = STOP_CODON_TO_NT_INDICES[x] * phi_reshape