Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|> """
return False
@property
def multiproc_safe(self):
"""This wrapper guarantees multiprocessing safety"""
return True
def store(self, *args, **kwargs):
raise NotImplementedError('Implement this!')
class ZMQServer(HasLogger):
""" Generic zmq server """
PING = 'PING' # for connection testing
PONG = 'PONG' # for connection testing
DONE = 'DONE' # signals stopping of server
CLOSED = 'CLOSED' # signals closing of server
def __init__(self, url="tcp://127.0.0.1:7777"):
self._url = url # server url
self._set_logger()
self._context = None
self._socket = None
def _start(self):
self._logger.info('Starting Server at `%s`' % self._url)
self._context = zmq.Context()
self._socket = self._context.socket(zmq.REP)
<|code_end|>
, determine the next line of code. You have imports:
from threading import ThreadError
from collections import deque
from threading import Thread
from pypet.pypetlogging import HasLogger
from pypet.utils.decorators import retry
from pypet.utils.helpful_functions import is_ipv6
import queue
import pickle
import zmq
import copy as cp
import gc
import sys
import time
import os
import socket
import pypet.pypetconstants as pypetconstants
and context (class names, function names, or code) available:
# Path: pypet/pypetlogging.py
# class HasLogger(HasSlots):
# """Abstract super class that automatically adds a logger to a class.
#
# To add a logger to a sub-class of yours simply call ``myobj._set_logger(name)``.
# If ``name=None`` the logger is chosen as follows:
#
# ``self._logger = logging.getLogger(self.__class.__.__module__ + '.' + self.__class__.__name__)``
#
# The logger can be accessed via ``myobj._logger``.
#
# """
#
# __slots__ = ('_logger',)
#
# def __getstate__(self):
# """Called for pickling.
#
# Removes the logger to allow pickling and returns a copy of `__dict__`.
#
# """
# state_dict = super(HasLogger, self).__getstate__()
# if '_logger' in state_dict:
# # Pickling does not work with loggers objects,
# # so we just keep the logger's name:
# state_dict['_logger'] = self._logger.name
# return state_dict
#
# def __setstate__(self, statedict):
# """Called after loading a pickle dump.
#
# Restores `__dict__` from `statedict` and adds a new logger.
#
# """
# super(HasLogger, self).__setstate__(statedict)
# if '_logger' in statedict:
# # If we re-instantiate the component the
# # logger attribute only contains a name,
# # so we also need to re-create the logger:
# self._set_logger(statedict['_logger'])
#
# def _set_logger(self, name=None):
# """Adds a logger with a given `name`.
#
# If no name is given, name is constructed as
# `type(self).__name__`.
#
# """
# if name is None:
# cls = self.__class__
# name = '%s.%s' % (cls.__module__, cls.__name__)
# self._logger = logging.getLogger(name)
#
# Path: pypet/utils/decorators.py
# def retry(n, errors, wait=0.0, logger_name=None):
# """This is a decorator that retries a function.
#
# Tries `n` times and catches a given tuple of `errors`.
#
# If the `n` retries are not enough, the error is reraised.
#
# If desired `waits` some seconds.
#
# Optionally takes a 'logger_name' of a given logger to print the caught error.
#
# """
#
# def wrapper(func):
# @functools.wraps(func)
# def new_func(*args, **kwargs):
# retries = 0
# while True:
# try:
# result = func(*args, **kwargs)
# if retries and logger_name:
# logger = logging.getLogger(logger_name)
# logger.debug('Retry of `%s` successful' % func.__name__)
# return result
# except errors:
# if retries >= n:
# if logger_name:
# logger = logging.getLogger(logger_name)
# logger.exception('I could not execute `%s` with args %s and kwargs %s, '
# 'starting next try. ' % (func.__name__,
# str(args),
# str(kwargs)))
# raise
# elif logger_name:
# logger = logging.getLogger(logger_name)
# logger.debug('I could not execute `%s` with args %s and kwargs %s, '
# 'starting next try. ' % (func.__name__,
# str(args),
# str(kwargs)))
# retries += 1
# if wait:
# time.sleep(wait)
# return new_func
#
# return wrapper
#
# Path: pypet/utils/helpful_functions.py
# def is_ipv6(url):
# return '[' in url
. Output only the next line. | self._socket.ipv6 = is_ipv6(self._url) |
Predict the next line for this snippet: <|code_start|>__author__ = 'Robert Meyer'
class NoseTestDummy(unittest.TestCase):
pass
<|code_end|>
with the help of current file imports:
import getopt
import sys
import os
import sys
import unittest
from pypet.tests.testutils.ioutils import discover_tests, TEST_IMPORT_ERROR
and context from other files:
# Path: pypet/tests/testutils/ioutils.py
# def discover_tests(predicate=None):
# """Builds a LambdaTestLoader and discovers tests according to `predicate`."""
# loader = LambdaTestDiscoverer(predicate)
# start_dir = os.path.dirname(os.path.abspath(__file__))
# start_dir = os.path.abspath(os.path.join(start_dir, '..'))
# suite = loader.discover(start_dir=start_dir, pattern='*test.py')
# return suite
#
# TEST_IMPORT_ERROR = 'ModuleImportFailure'
, which may contain function names, class names, or code. Output only the next line. | suite = discover_tests(predicate= lambda class_name, test_name, tags: |
Continue the code snippet: <|code_start|>__author__ = 'Robert Meyer'
class NoseTestDummy(unittest.TestCase):
pass
suite = discover_tests(predicate= lambda class_name, test_name, tags:
<|code_end|>
. Use current file imports:
import getopt
import sys
import os
import sys
import unittest
from pypet.tests.testutils.ioutils import discover_tests, TEST_IMPORT_ERROR
and context (classes, functions, or code) from other files:
# Path: pypet/tests/testutils/ioutils.py
# def discover_tests(predicate=None):
# """Builds a LambdaTestLoader and discovers tests according to `predicate`."""
# loader = LambdaTestDiscoverer(predicate)
# start_dir = os.path.dirname(os.path.abspath(__file__))
# start_dir = os.path.abspath(os.path.join(start_dir, '..'))
# suite = loader.discover(start_dir=start_dir, pattern='*test.py')
# return suite
#
# TEST_IMPORT_ERROR = 'ModuleImportFailure'
. Output only the next line. | class_name != TEST_IMPORT_ERROR) |
Predict the next line for this snippet: <|code_start|> valstr = self._translate_key(idx)
self.f_set_single(valstr, arg)
for key, arg in kwargs.items():
self.f_set_single(key, arg)
def f_remove(self, key):
"""Removes `key` from annotations"""
key = self._translate_key(key)
try:
del self._dict[key]
except KeyError:
raise AttributeError('Your annotations do not contain %s' % key)
def f_set_single(self, name, data):
""" Sets a single annotation. """
self._dict[name] = data
def f_ann_to_str(self):
"""Returns all annotations lexicographically sorted as a concatenated string."""
resstr = ''
for key in sorted(self._dict.keys()):
resstr += '%s=%s; ' % (key, str(self._dict[key]))
return resstr[:-2]
def __str__(self):
return self.f_ann_to_str()
<|code_end|>
with the help of current file imports:
from pypet.pypetlogging import HasLogger
from pypet.slots import HasSlots
and context from other files:
# Path: pypet/pypetlogging.py
# class HasLogger(HasSlots):
# """Abstract super class that automatically adds a logger to a class.
#
# To add a logger to a sub-class of yours simply call ``myobj._set_logger(name)``.
# If ``name=None`` the logger is chosen as follows:
#
# ``self._logger = logging.getLogger(self.__class.__.__module__ + '.' + self.__class__.__name__)``
#
# The logger can be accessed via ``myobj._logger``.
#
# """
#
# __slots__ = ('_logger',)
#
# def __getstate__(self):
# """Called for pickling.
#
# Removes the logger to allow pickling and returns a copy of `__dict__`.
#
# """
# state_dict = super(HasLogger, self).__getstate__()
# if '_logger' in state_dict:
# # Pickling does not work with loggers objects,
# # so we just keep the logger's name:
# state_dict['_logger'] = self._logger.name
# return state_dict
#
# def __setstate__(self, statedict):
# """Called after loading a pickle dump.
#
# Restores `__dict__` from `statedict` and adds a new logger.
#
# """
# super(HasLogger, self).__setstate__(statedict)
# if '_logger' in statedict:
# # If we re-instantiate the component the
# # logger attribute only contains a name,
# # so we also need to re-create the logger:
# self._set_logger(statedict['_logger'])
#
# def _set_logger(self, name=None):
# """Adds a logger with a given `name`.
#
# If no name is given, name is constructed as
# `type(self).__name__`.
#
# """
# if name is None:
# cls = self.__class__
# name = '%s.%s' % (cls.__module__, cls.__name__)
# self._logger = logging.getLogger(name)
#
# Path: pypet/slots.py
# class HasSlots(object, metaclass=MetaSlotMachine):
# """Top-class that allows mixing of classes with and without slots.
#
# Takes care that instances can still be pickled with the lowest
# protocol. Moreover, provides a generic `__dir__` method that
# lists all slots.
#
# """
# __slots__ = ('__weakref__',)
#
# def __getstate__(self):
# if hasattr(self, '__dict__'):
# # We don't require that all sub-classes also define slots,
# # so they may provide a dictionary
# statedict = self.__dict__.copy()
# else:
# statedict = {}
# # Get all slots of potential parent classes
# for slot in self.__all_slots__:
# try:
# value = getattr(self, slot)
# statedict[slot] = value
# except AttributeError:
# pass
# # Pop slots that cannot or should not be pickled
# statedict.pop('__dict__', None)
# statedict.pop('__weakref__', None)
# return statedict
#
# def __setstate__(self, state):
# """Recalls state for items with slots"""
# for key in state:
# setattr(self, key, state[key])
#
# def __dir__(self):
# """Includes all slots in the `dir` method"""
# result = set()
# result.update(dir(self.__class__), self.__all_slots__)
# if hasattr(self, '__dict__'):
# result.update(self.__dict__.keys())
# return list(result)
, which may contain function names, class names, or code. Output only the next line. | class WithAnnotations(HasLogger): |
Given snippet: <|code_start|>""" Module defining annotations.
This module contains two classes:
1. :class:`~pypet.annotations.Annotations`
Container class for annotations. There are no restrictions regarding what is considered
to be an annotation. In principle, this can be any python object. However,
if using the standard :class:`~pypet.storageservice.HDF5StorageService`,
these annotations are stored as hdf5 node attributes.
Accordingly, annotations should be rather small since reading
and writing these attributes to disk is slow.
2. :class:`~pypet.annotations.WithAnnotations`
Abstract class to subclass from. Instances that subclass `WithAnnotations`
have the `v_annotations` property which is an instance of the `Annotations` class
to handle annotations. They also acquire some functions to put annotations directly
into the `v_annotations` object like `f_set_annotations`.
"""
__author__ = 'Robert Meyer'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pypet.pypetlogging import HasLogger
from pypet.slots import HasSlots
and context:
# Path: pypet/pypetlogging.py
# class HasLogger(HasSlots):
# """Abstract super class that automatically adds a logger to a class.
#
# To add a logger to a sub-class of yours simply call ``myobj._set_logger(name)``.
# If ``name=None`` the logger is chosen as follows:
#
# ``self._logger = logging.getLogger(self.__class.__.__module__ + '.' + self.__class__.__name__)``
#
# The logger can be accessed via ``myobj._logger``.
#
# """
#
# __slots__ = ('_logger',)
#
# def __getstate__(self):
# """Called for pickling.
#
# Removes the logger to allow pickling and returns a copy of `__dict__`.
#
# """
# state_dict = super(HasLogger, self).__getstate__()
# if '_logger' in state_dict:
# # Pickling does not work with loggers objects,
# # so we just keep the logger's name:
# state_dict['_logger'] = self._logger.name
# return state_dict
#
# def __setstate__(self, statedict):
# """Called after loading a pickle dump.
#
# Restores `__dict__` from `statedict` and adds a new logger.
#
# """
# super(HasLogger, self).__setstate__(statedict)
# if '_logger' in statedict:
# # If we re-instantiate the component the
# # logger attribute only contains a name,
# # so we also need to re-create the logger:
# self._set_logger(statedict['_logger'])
#
# def _set_logger(self, name=None):
# """Adds a logger with a given `name`.
#
# If no name is given, name is constructed as
# `type(self).__name__`.
#
# """
# if name is None:
# cls = self.__class__
# name = '%s.%s' % (cls.__module__, cls.__name__)
# self._logger = logging.getLogger(name)
#
# Path: pypet/slots.py
# class HasSlots(object, metaclass=MetaSlotMachine):
# """Top-class that allows mixing of classes with and without slots.
#
# Takes care that instances can still be pickled with the lowest
# protocol. Moreover, provides a generic `__dir__` method that
# lists all slots.
#
# """
# __slots__ = ('__weakref__',)
#
# def __getstate__(self):
# if hasattr(self, '__dict__'):
# # We don't require that all sub-classes also define slots,
# # so they may provide a dictionary
# statedict = self.__dict__.copy()
# else:
# statedict = {}
# # Get all slots of potential parent classes
# for slot in self.__all_slots__:
# try:
# value = getattr(self, slot)
# statedict[slot] = value
# except AttributeError:
# pass
# # Pop slots that cannot or should not be pickled
# statedict.pop('__dict__', None)
# statedict.pop('__weakref__', None)
# return statedict
#
# def __setstate__(self, state):
# """Recalls state for items with slots"""
# for key in state:
# setattr(self, key, state[key])
#
# def __dir__(self):
# """Includes all slots in the `dir` method"""
# result = set()
# result.update(dir(self.__class__), self.__all_slots__)
# if hasattr(self, '__dict__'):
# result.update(self.__dict__.keys())
# return list(result)
which might include code, classes, or functions. Output only the next line. | class Annotations(HasSlots): |
Using the snippet: <|code_start|> def _collect_section(self, section):
"""Collects all settings within a section"""
kwargs = {}
try:
if self.parser.has_section(section):
options = self.parser.options(section)
for option in options:
str_val = self.parser.get(section, option)
val = ast.literal_eval(str_val)
kwargs[option] = val
return kwargs
except:
raise # You can set a break point here for debugging!
def _collect_config(self):
"""Collects all info from three sections"""
kwargs = {}
sections = ('storage_service', 'trajectory', 'environment')
for section in sections:
kwargs.update(self._collect_section(section))
return kwargs
def interpret(self):
"""Copies parsed arguments into the kwargs passed to the environment"""
if self.config_file:
new_kwargs = self._collect_config()
for key in new_kwargs:
# Already specified kwargs take precedence over the ini file
if key not in self.kwargs:
self.kwargs[key] = new_kwargs[key]
<|code_end|>
, determine the next line of code. You have imports:
import functools
import ast
import os
import configparser as cp
from pypet.pypetlogging import use_simple_logging
and context (class names, function names, or code) available:
# Path: pypet/pypetlogging.py
# def use_simple_logging(kwargs):
# """Checks if simple logging is requested"""
# return any([x in kwargs for x in ('log_folder', 'logger_names',
# 'log_levels', 'log_multiproc', 'log_level')])
. Output only the next line. | if not use_simple_logging(self.kwargs) and 'log_config' not in self.kwargs: |
Using the snippet: <|code_start|>__author__ = 'robert'
try:
except ImportError as exc:
#print('Import Error: %s' % str(exc))
brian2 = None
@unittest.skipIf(brian2 is None, 'Can only be run with brian!')
class TestAllBrian2Import(unittest.TestCase):
tags = 'unittest', 'brian2', 'import'
def test_import_star(self):
for class_name in pypet.brian2.__all__:
logstr = 'Evaluauting %s: %s' % (class_name, repr(eval(class_name)))
<|code_end|>
, determine the next line of code. You have imports:
import sys
import unittest
import brian2
import pypet.brian2
import inspect
from pypet.brian2 import *
from pypet.tests.testutils.ioutils import get_root_logger, parse_args, run_suite
and context (class names, function names, or code) available:
# Path: pypet/tests/testutils/ioutils.py
# def get_root_logger():
# """Returns root logger"""
# return logging.getLogger()
#
# def parse_args():
# """Parses arguments and returns a dictionary"""
# opt_list, _ = getopt.getopt(sys.argv[1:],'k',['folder=', 'suite='])
# opt_dict = {}
#
# for opt, arg in opt_list:
# if opt == '-k':
# opt_dict['remove'] = False
# errwrite('I will keep all files.')
#
# if opt == '--folder':
# opt_dict['folder'] = arg
# errwrite('I will put all data into folder `%s`.' % arg)
#
# if opt == '--suite':
# opt_dict['suite_no'] = arg
# errwrite('I will run suite `%s`.' % arg)
#
# sys.argv = [sys.argv[0]]
# return opt_dict
#
# def run_suite(remove=None, folder=None, suite=None):
# """Runs a particular test suite or simply unittest.main.
#
# Takes care that all temporary data in `folder` is removed if `remove=True`.
#
# """
# if remove is not None:
# testParams['remove'] = remove
#
# testParams['user_tempdir'] = folder
#
# prepare_log_config()
#
# # Just signal if make_temp_dir works
# make_temp_dir('tmp.txt', signal=True)
#
# success = False
# try:
# if suite is None:
# unittest.main(verbosity=2)
# else:
# runner = unittest.TextTestRunner(verbosity=2)
# result = runner.run(suite)
# success = result.wasSuccessful()
# finally:
# remove_data()
#
# if not success:
# # Exit with 1 if tests were not successful
# sys.exit(1)
. Output only the next line. | get_root_logger().info(logstr) |
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'robert'
try:
except ImportError as exc:
#print('Import Error: %s' % str(exc))
brian2 = None
@unittest.skipIf(brian2 is None, 'Can only be run with brian!')
class TestAllBrian2Import(unittest.TestCase):
tags = 'unittest', 'brian2', 'import'
def test_import_star(self):
for class_name in pypet.brian2.__all__:
logstr = 'Evaluauting %s: %s' % (class_name, repr(eval(class_name)))
get_root_logger().info(logstr)
def test_if_all_is_complete(self):
for item in pypet.brian2.__dict__.values():
if inspect.isclass(item) or inspect.isfunction(item):
self.assertTrue(item.__name__ in pypet.brian2.__all__)
if __name__ == '__main__':
<|code_end|>
, predict the next line using imports from the current file:
import sys
import unittest
import brian2
import pypet.brian2
import inspect
from pypet.brian2 import *
from pypet.tests.testutils.ioutils import get_root_logger, parse_args, run_suite
and context including class names, function names, and sometimes code from other files:
# Path: pypet/tests/testutils/ioutils.py
# def get_root_logger():
# """Returns root logger"""
# return logging.getLogger()
#
# def parse_args():
# """Parses arguments and returns a dictionary"""
# opt_list, _ = getopt.getopt(sys.argv[1:],'k',['folder=', 'suite='])
# opt_dict = {}
#
# for opt, arg in opt_list:
# if opt == '-k':
# opt_dict['remove'] = False
# errwrite('I will keep all files.')
#
# if opt == '--folder':
# opt_dict['folder'] = arg
# errwrite('I will put all data into folder `%s`.' % arg)
#
# if opt == '--suite':
# opt_dict['suite_no'] = arg
# errwrite('I will run suite `%s`.' % arg)
#
# sys.argv = [sys.argv[0]]
# return opt_dict
#
# def run_suite(remove=None, folder=None, suite=None):
# """Runs a particular test suite or simply unittest.main.
#
# Takes care that all temporary data in `folder` is removed if `remove=True`.
#
# """
# if remove is not None:
# testParams['remove'] = remove
#
# testParams['user_tempdir'] = folder
#
# prepare_log_config()
#
# # Just signal if make_temp_dir works
# make_temp_dir('tmp.txt', signal=True)
#
# success = False
# try:
# if suite is None:
# unittest.main(verbosity=2)
# else:
# runner = unittest.TextTestRunner(verbosity=2)
# result = runner.run(suite)
# success = result.wasSuccessful()
# finally:
# remove_data()
#
# if not success:
# # Exit with 1 if tests were not successful
# sys.exit(1)
. Output only the next line. | opt_args = parse_args() |
Predict the next line after this snippet: <|code_start|>__author__ = 'robert'
try:
except ImportError as exc:
#print('Import Error: %s' % str(exc))
brian2 = None
@unittest.skipIf(brian2 is None, 'Can only be run with brian!')
class TestAllBrian2Import(unittest.TestCase):
tags = 'unittest', 'brian2', 'import'
def test_import_star(self):
for class_name in pypet.brian2.__all__:
logstr = 'Evaluauting %s: %s' % (class_name, repr(eval(class_name)))
get_root_logger().info(logstr)
def test_if_all_is_complete(self):
for item in pypet.brian2.__dict__.values():
if inspect.isclass(item) or inspect.isfunction(item):
self.assertTrue(item.__name__ in pypet.brian2.__all__)
if __name__ == '__main__':
opt_args = parse_args()
<|code_end|>
using the current file's imports:
import sys
import unittest
import brian2
import pypet.brian2
import inspect
from pypet.brian2 import *
from pypet.tests.testutils.ioutils import get_root_logger, parse_args, run_suite
and any relevant context from other files:
# Path: pypet/tests/testutils/ioutils.py
# def get_root_logger():
# """Returns root logger"""
# return logging.getLogger()
#
# def parse_args():
# """Parses arguments and returns a dictionary"""
# opt_list, _ = getopt.getopt(sys.argv[1:],'k',['folder=', 'suite='])
# opt_dict = {}
#
# for opt, arg in opt_list:
# if opt == '-k':
# opt_dict['remove'] = False
# errwrite('I will keep all files.')
#
# if opt == '--folder':
# opt_dict['folder'] = arg
# errwrite('I will put all data into folder `%s`.' % arg)
#
# if opt == '--suite':
# opt_dict['suite_no'] = arg
# errwrite('I will run suite `%s`.' % arg)
#
# sys.argv = [sys.argv[0]]
# return opt_dict
#
# def run_suite(remove=None, folder=None, suite=None):
# """Runs a particular test suite or simply unittest.main.
#
# Takes care that all temporary data in `folder` is removed if `remove=True`.
#
# """
# if remove is not None:
# testParams['remove'] = remove
#
# testParams['user_tempdir'] = folder
#
# prepare_log_config()
#
# # Just signal if make_temp_dir works
# make_temp_dir('tmp.txt', signal=True)
#
# success = False
# try:
# if suite is None:
# unittest.main(verbosity=2)
# else:
# runner = unittest.TextTestRunner(verbosity=2)
# result = runner.run(suite)
# success = result.wasSuccessful()
# finally:
# remove_data()
#
# if not success:
# # Exit with 1 if tests were not successful
# sys.exit(1)
. Output only the next line. | run_suite(**opt_args) |
Given the code snippet: <|code_start|>def appendtime(table, length):
runtimes = []
for irun in range(length):
start = time.time()
row = table.row
row['test'] = 'testing'
row.append()
table.flush()
end = time.time()
runtime = end-start
runtimes.append(runtime)
return np.mean(runtimes)
def make_table(hdf5_file, length):
description = {'test' : pt.StringCol(42)}
table = hdf5_file.create_table(where='/', name='t%d' % length, description=description)
return table
def table_runtime(filename, length):
hdf5_file = pt.open_file(filename, mode='w')
table = make_table(hdf5_file, length)
appendtimes = appendtime(table, length)
hdf5_file.close()
return appendtimes
def compute_runtime():
<|code_end|>
, generate the next line using the imports in this file:
from pypet.tests.testutils.ioutils import make_temp_dir
import tables as pt
import tables.parameters
import time
import os
import numpy as np
import matplotlib.pyplot as plt
and context (functions, classes, or occasionally code) from other files:
# Path: pypet/tests/testutils/ioutils.py
# def make_temp_dir(filename, signal=False):
# """Creates a temporary folder and returns the joined filename"""
# try:
#
# if ((testParams['user_tempdir'] is not None and testParams['user_tempdir'] != '') and
# testParams['actual_tempdir'] == ''):
# testParams['actual_tempdir'] = testParams['user_tempdir']
#
# if not os.path.isdir(testParams['actual_tempdir']):
# os.makedirs(testParams['actual_tempdir'])
#
# return os.path.join(testParams['actual_tempdir'], filename)
# except OSError as exc:
# actual_tempdir = os.path.join(tempfile.gettempdir(), testParams['tempdir'])
#
# if signal:
# errwrite('I used `tempfile.gettempdir()` to create the temporary folder '
# '`%s`.' % actual_tempdir)
# testParams['actual_tempdir'] = actual_tempdir
# if not os.path.isdir(testParams['actual_tempdir']):
# try:
# os.makedirs(testParams['actual_tempdir'])
# except Exception:
# pass # race condition
#
# return os.path.join(actual_tempdir, filename)
# except:
# get_root_logger().error('Could not create a directory.')
# raise
. Output only the next line. | filename = os.path.join(make_temp_dir('tests'), 'iterrow.hdf5') |
Given snippet: <|code_start|>__author__ = 'Robert Meyer'
del test # To not run all tests if this file is executed with nosetests
class TestAllImport(unittest.TestCase):
tags = 'unittest', 'import'
def test_import_star(self):
for class_name in pypet.__all__:
if class_name == 'test':
continue
logstr = 'Evaulauting %s: %s' % (class_name, repr(eval(class_name)))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import unittest
import pypet
import logging
import inspect
from pypet import *
from pypet.tests.testutils.ioutils import get_root_logger, run_suite, parse_args
and context:
# Path: pypet/tests/testutils/ioutils.py
# def get_root_logger():
# """Returns root logger"""
# return logging.getLogger()
#
# def run_suite(remove=None, folder=None, suite=None):
# """Runs a particular test suite or simply unittest.main.
#
# Takes care that all temporary data in `folder` is removed if `remove=True`.
#
# """
# if remove is not None:
# testParams['remove'] = remove
#
# testParams['user_tempdir'] = folder
#
# prepare_log_config()
#
# # Just signal if make_temp_dir works
# make_temp_dir('tmp.txt', signal=True)
#
# success = False
# try:
# if suite is None:
# unittest.main(verbosity=2)
# else:
# runner = unittest.TextTestRunner(verbosity=2)
# result = runner.run(suite)
# success = result.wasSuccessful()
# finally:
# remove_data()
#
# if not success:
# # Exit with 1 if tests were not successful
# sys.exit(1)
#
# def parse_args():
# """Parses arguments and returns a dictionary"""
# opt_list, _ = getopt.getopt(sys.argv[1:],'k',['folder=', 'suite='])
# opt_dict = {}
#
# for opt, arg in opt_list:
# if opt == '-k':
# opt_dict['remove'] = False
# errwrite('I will keep all files.')
#
# if opt == '--folder':
# opt_dict['folder'] = arg
# errwrite('I will put all data into folder `%s`.' % arg)
#
# if opt == '--suite':
# opt_dict['suite_no'] = arg
# errwrite('I will run suite `%s`.' % arg)
#
# sys.argv = [sys.argv[0]]
# return opt_dict
which might include code, classes, or functions. Output only the next line. | get_root_logger().info(logstr) |
Using the snippet: <|code_start|>
class TestAllImport(unittest.TestCase):
tags = 'unittest', 'import'
def test_import_star(self):
for class_name in pypet.__all__:
if class_name == 'test':
continue
logstr = 'Evaulauting %s: %s' % (class_name, repr(eval(class_name)))
get_root_logger().info(logstr)
def test_if_all_is_complete(self):
for item in pypet.__dict__.values():
if inspect.isclass(item) or inspect.isfunction(item):
self.assertTrue(item.__name__ in pypet.__all__)
class TestRunningTests(unittest.TestCase):
tags = 'unittest', 'test', 'meta'
def test_run_one_test(self):
predicate = lambda class_name, test_name, tags:(test_name == 'test_import_star' and
class_name == 'TestAllImport')
pypet.test(predicate=predicate)
if __name__ == '__main__':
opt_args = parse_args()
<|code_end|>
, determine the next line of code. You have imports:
import sys
import unittest
import pypet
import logging
import inspect
from pypet import *
from pypet.tests.testutils.ioutils import get_root_logger, run_suite, parse_args
and context (class names, function names, or code) available:
# Path: pypet/tests/testutils/ioutils.py
# def get_root_logger():
# """Returns root logger"""
# return logging.getLogger()
#
# def run_suite(remove=None, folder=None, suite=None):
# """Runs a particular test suite or simply unittest.main.
#
# Takes care that all temporary data in `folder` is removed if `remove=True`.
#
# """
# if remove is not None:
# testParams['remove'] = remove
#
# testParams['user_tempdir'] = folder
#
# prepare_log_config()
#
# # Just signal if make_temp_dir works
# make_temp_dir('tmp.txt', signal=True)
#
# success = False
# try:
# if suite is None:
# unittest.main(verbosity=2)
# else:
# runner = unittest.TextTestRunner(verbosity=2)
# result = runner.run(suite)
# success = result.wasSuccessful()
# finally:
# remove_data()
#
# if not success:
# # Exit with 1 if tests were not successful
# sys.exit(1)
#
# def parse_args():
# """Parses arguments and returns a dictionary"""
# opt_list, _ = getopt.getopt(sys.argv[1:],'k',['folder=', 'suite='])
# opt_dict = {}
#
# for opt, arg in opt_list:
# if opt == '-k':
# opt_dict['remove'] = False
# errwrite('I will keep all files.')
#
# if opt == '--folder':
# opt_dict['folder'] = arg
# errwrite('I will put all data into folder `%s`.' % arg)
#
# if opt == '--suite':
# opt_dict['suite_no'] = arg
# errwrite('I will run suite `%s`.' % arg)
#
# sys.argv = [sys.argv[0]]
# return opt_dict
. Output only the next line. | run_suite(**opt_args) |
Given the code snippet: <|code_start|>
class TestAllImport(unittest.TestCase):
tags = 'unittest', 'import'
def test_import_star(self):
for class_name in pypet.__all__:
if class_name == 'test':
continue
logstr = 'Evaulauting %s: %s' % (class_name, repr(eval(class_name)))
get_root_logger().info(logstr)
def test_if_all_is_complete(self):
for item in pypet.__dict__.values():
if inspect.isclass(item) or inspect.isfunction(item):
self.assertTrue(item.__name__ in pypet.__all__)
class TestRunningTests(unittest.TestCase):
tags = 'unittest', 'test', 'meta'
def test_run_one_test(self):
predicate = lambda class_name, test_name, tags:(test_name == 'test_import_star' and
class_name == 'TestAllImport')
pypet.test(predicate=predicate)
if __name__ == '__main__':
<|code_end|>
, generate the next line using the imports in this file:
import sys
import unittest
import pypet
import logging
import inspect
from pypet import *
from pypet.tests.testutils.ioutils import get_root_logger, run_suite, parse_args
and context (functions, classes, or occasionally code) from other files:
# Path: pypet/tests/testutils/ioutils.py
# def get_root_logger():
# """Returns root logger"""
# return logging.getLogger()
#
# def run_suite(remove=None, folder=None, suite=None):
# """Runs a particular test suite or simply unittest.main.
#
# Takes care that all temporary data in `folder` is removed if `remove=True`.
#
# """
# if remove is not None:
# testParams['remove'] = remove
#
# testParams['user_tempdir'] = folder
#
# prepare_log_config()
#
# # Just signal if make_temp_dir works
# make_temp_dir('tmp.txt', signal=True)
#
# success = False
# try:
# if suite is None:
# unittest.main(verbosity=2)
# else:
# runner = unittest.TextTestRunner(verbosity=2)
# result = runner.run(suite)
# success = result.wasSuccessful()
# finally:
# remove_data()
#
# if not success:
# # Exit with 1 if tests were not successful
# sys.exit(1)
#
# def parse_args():
# """Parses arguments and returns a dictionary"""
# opt_list, _ = getopt.getopt(sys.argv[1:],'k',['folder=', 'suite='])
# opt_dict = {}
#
# for opt, arg in opt_list:
# if opt == '-k':
# opt_dict['remove'] = False
# errwrite('I will keep all files.')
#
# if opt == '--folder':
# opt_dict['folder'] = arg
# errwrite('I will put all data into folder `%s`.' % arg)
#
# if opt == '--suite':
# opt_dict['suite_no'] = arg
# errwrite('I will run suite `%s`.' % arg)
#
# sys.argv = [sys.argv[0]]
# return opt_dict
. Output only the next line. | opt_args = parse_args() |
Given the code snippet: <|code_start|>if ProcessCoverage:
multiprocessing.Process = ProcessCoverage
print('Added Monkey-Patch for multiprocessing and code-coverage')
pypetpath=os.path.abspath(os.getcwd())
sys.path.append(pypetpath)
print('Appended path `%s`' % pypetpath)
if __name__ == '__main__':
opt_dict = parse_args()
tests_include = set(('TestMPImmediatePostProcLock',
'MultiprocFrozenPoolSortQueueTest',
'MultiprocFrozenPoolSortPipeTest',
'MultiprocLinkNoPoolLockTest',
'MultiprocLinkNoPoolQueueTest',
'MultiprocLinkQueueTest',
'MultiprocPoolSortLocalTest',
'MultiprocSCOOPSortLocalTest',
'MultiprocFrozenSCOOPSortNetlockTest',
'MultiprocFrozenSCOOPSortNetqueueTest',
'Brain2NetworkTest',
'BrainNetworkTest',
'CapTest'))
pred = lambda class_name, test_name, tags: (class_name in tests_include or
'multiproc' not in tags)
suite = discover_tests(pred)
<|code_end|>
, generate the next line using the imports in this file:
import multiprocessing
import coverage as _coverage
import sys
import os
from coverage.collector import Collector
from coverage import coverage
from pypet.tests.testutils.ioutils import run_suite, discover_tests, TEST_IMPORT_ERROR, parse_args
and context (functions, classes, or occasionally code) from other files:
# Path: pypet/tests/testutils/ioutils.py
# def run_suite(remove=None, folder=None, suite=None):
# """Runs a particular test suite or simply unittest.main.
#
# Takes care that all temporary data in `folder` is removed if `remove=True`.
#
# """
# if remove is not None:
# testParams['remove'] = remove
#
# testParams['user_tempdir'] = folder
#
# prepare_log_config()
#
# # Just signal if make_temp_dir works
# make_temp_dir('tmp.txt', signal=True)
#
# success = False
# try:
# if suite is None:
# unittest.main(verbosity=2)
# else:
# runner = unittest.TextTestRunner(verbosity=2)
# result = runner.run(suite)
# success = result.wasSuccessful()
# finally:
# remove_data()
#
# if not success:
# # Exit with 1 if tests were not successful
# sys.exit(1)
#
# def discover_tests(predicate=None):
# """Builds a LambdaTestLoader and discovers tests according to `predicate`."""
# loader = LambdaTestDiscoverer(predicate)
# start_dir = os.path.dirname(os.path.abspath(__file__))
# start_dir = os.path.abspath(os.path.join(start_dir, '..'))
# suite = loader.discover(start_dir=start_dir, pattern='*test.py')
# return suite
#
# TEST_IMPORT_ERROR = 'ModuleImportFailure'
#
# def parse_args():
# """Parses arguments and returns a dictionary"""
# opt_list, _ = getopt.getopt(sys.argv[1:],'k',['folder=', 'suite='])
# opt_dict = {}
#
# for opt, arg in opt_list:
# if opt == '-k':
# opt_dict['remove'] = False
# errwrite('I will keep all files.')
#
# if opt == '--folder':
# opt_dict['folder'] = arg
# errwrite('I will put all data into folder `%s`.' % arg)
#
# if opt == '--suite':
# opt_dict['suite_no'] = arg
# errwrite('I will run suite `%s`.' % arg)
#
# sys.argv = [sys.argv[0]]
# return opt_dict
. Output only the next line. | run_suite(suite=suite, **opt_dict) |
Given snippet: <|code_start|>ProcessCoverage = coverage_multiprocessing_process()
if ProcessCoverage:
multiprocessing.Process = ProcessCoverage
print('Added Monkey-Patch for multiprocessing and code-coverage')
pypetpath=os.path.abspath(os.getcwd())
sys.path.append(pypetpath)
print('Appended path `%s`' % pypetpath)
if __name__ == '__main__':
opt_dict = parse_args()
tests_include = set(('TestMPImmediatePostProcLock',
'MultiprocFrozenPoolSortQueueTest',
'MultiprocFrozenPoolSortPipeTest',
'MultiprocLinkNoPoolLockTest',
'MultiprocLinkNoPoolQueueTest',
'MultiprocLinkQueueTest',
'MultiprocPoolSortLocalTest',
'MultiprocSCOOPSortLocalTest',
'MultiprocFrozenSCOOPSortNetlockTest',
'MultiprocFrozenSCOOPSortNetqueueTest',
'Brain2NetworkTest',
'BrainNetworkTest',
'CapTest'))
pred = lambda class_name, test_name, tags: (class_name in tests_include or
'multiproc' not in tags)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import multiprocessing
import coverage as _coverage
import sys
import os
from coverage.collector import Collector
from coverage import coverage
from pypet.tests.testutils.ioutils import run_suite, discover_tests, TEST_IMPORT_ERROR, parse_args
and context:
# Path: pypet/tests/testutils/ioutils.py
# def run_suite(remove=None, folder=None, suite=None):
# """Runs a particular test suite or simply unittest.main.
#
# Takes care that all temporary data in `folder` is removed if `remove=True`.
#
# """
# if remove is not None:
# testParams['remove'] = remove
#
# testParams['user_tempdir'] = folder
#
# prepare_log_config()
#
# # Just signal if make_temp_dir works
# make_temp_dir('tmp.txt', signal=True)
#
# success = False
# try:
# if suite is None:
# unittest.main(verbosity=2)
# else:
# runner = unittest.TextTestRunner(verbosity=2)
# result = runner.run(suite)
# success = result.wasSuccessful()
# finally:
# remove_data()
#
# if not success:
# # Exit with 1 if tests were not successful
# sys.exit(1)
#
# def discover_tests(predicate=None):
# """Builds a LambdaTestLoader and discovers tests according to `predicate`."""
# loader = LambdaTestDiscoverer(predicate)
# start_dir = os.path.dirname(os.path.abspath(__file__))
# start_dir = os.path.abspath(os.path.join(start_dir, '..'))
# suite = loader.discover(start_dir=start_dir, pattern='*test.py')
# return suite
#
# TEST_IMPORT_ERROR = 'ModuleImportFailure'
#
# def parse_args():
# """Parses arguments and returns a dictionary"""
# opt_list, _ = getopt.getopt(sys.argv[1:],'k',['folder=', 'suite='])
# opt_dict = {}
#
# for opt, arg in opt_list:
# if opt == '-k':
# opt_dict['remove'] = False
# errwrite('I will keep all files.')
#
# if opt == '--folder':
# opt_dict['folder'] = arg
# errwrite('I will put all data into folder `%s`.' % arg)
#
# if opt == '--suite':
# opt_dict['suite_no'] = arg
# errwrite('I will run suite `%s`.' % arg)
#
# sys.argv = [sys.argv[0]]
# return opt_dict
which might include code, classes, or functions. Output only the next line. | suite = discover_tests(pred) |
Given the code snippet: <|code_start|> # detect if coverage was running in forked process
if Collector._collectors:
original = multiprocessing.Process._bootstrap
class Process_WithCoverage(multiprocessing.Process):
def _bootstrap(self):
cov = coverage(data_suffix=True,
omit='*/pypet/tests/*,*/shareddata.py'.split(','))
cov.start()
try:
return original(self)
finally:
cov.stop()
cov.save()
return Process_WithCoverage
ProcessCoverage = coverage_multiprocessing_process()
if ProcessCoverage:
multiprocessing.Process = ProcessCoverage
print('Added Monkey-Patch for multiprocessing and code-coverage')
pypetpath=os.path.abspath(os.getcwd())
sys.path.append(pypetpath)
print('Appended path `%s`' % pypetpath)
if __name__ == '__main__':
<|code_end|>
, generate the next line using the imports in this file:
import multiprocessing
import coverage as _coverage
import sys
import os
from coverage.collector import Collector
from coverage import coverage
from pypet.tests.testutils.ioutils import run_suite, discover_tests, TEST_IMPORT_ERROR, parse_args
and context (functions, classes, or occasionally code) from other files:
# Path: pypet/tests/testutils/ioutils.py
# def run_suite(remove=None, folder=None, suite=None):
# """Runs a particular test suite or simply unittest.main.
#
# Takes care that all temporary data in `folder` is removed if `remove=True`.
#
# """
# if remove is not None:
# testParams['remove'] = remove
#
# testParams['user_tempdir'] = folder
#
# prepare_log_config()
#
# # Just signal if make_temp_dir works
# make_temp_dir('tmp.txt', signal=True)
#
# success = False
# try:
# if suite is None:
# unittest.main(verbosity=2)
# else:
# runner = unittest.TextTestRunner(verbosity=2)
# result = runner.run(suite)
# success = result.wasSuccessful()
# finally:
# remove_data()
#
# if not success:
# # Exit with 1 if tests were not successful
# sys.exit(1)
#
# def discover_tests(predicate=None):
# """Builds a LambdaTestLoader and discovers tests according to `predicate`."""
# loader = LambdaTestDiscoverer(predicate)
# start_dir = os.path.dirname(os.path.abspath(__file__))
# start_dir = os.path.abspath(os.path.join(start_dir, '..'))
# suite = loader.discover(start_dir=start_dir, pattern='*test.py')
# return suite
#
# TEST_IMPORT_ERROR = 'ModuleImportFailure'
#
# def parse_args():
# """Parses arguments and returns a dictionary"""
# opt_list, _ = getopt.getopt(sys.argv[1:],'k',['folder=', 'suite='])
# opt_dict = {}
#
# for opt, arg in opt_list:
# if opt == '-k':
# opt_dict['remove'] = False
# errwrite('I will keep all files.')
#
# if opt == '--folder':
# opt_dict['folder'] = arg
# errwrite('I will put all data into folder `%s`.' % arg)
#
# if opt == '--suite':
# opt_dict['suite_no'] = arg
# errwrite('I will run suite `%s`.' % arg)
#
# sys.argv = [sys.argv[0]]
# return opt_dict
. Output only the next line. | opt_dict = parse_args() |
Predict the next line for this snippet: <|code_start|> if len(field_shape) > 2:
raise ValueError('Forbidden field shape. The field array must be'
' of shape (Nvalues) or (Nvalues,Ndim). Received'
' {}'.format(field_shape))
node_field = False
elem_field = False
Nnodes = self.get_attribute('number_of_nodes', meshname)
Nelem = np.sum(self.get_attribute('Number_of_elements', meshname))
Nelem_bulk = np.sum(self.get_attribute('Number_of_bulk_elements',
meshname))
Nfield_values = field_shape[0]
if len(field_shape) == 2:
Field_dim = field_shape[1]
else:
Field_dim = 1
if Nfield_values == Nnodes:
node_field = True
field_type='Nodal_field'
elif Nfield_values == Nelem:
elem_field = True
field_type='Element_field'
elif (Nfield_values % Nelem_bulk) == 0:
elem_field = True
field_type = 'IP_field'
compatibility = node_field or elem_field
if not(compatibility):
raise ValueError('Field number of values ({}) is not conformant'
' with mesh number of nodes ({}) or number of'
' elements ({}).'
''.format(Nfield_values, Nnodes, Nelem))
<|code_end|>
with the help of current file imports:
import os
import subprocess
import shutil
import numpy as np
import tables
import lxml.builder
import BasicTools.Containers.UnstructuredMeshCreationTools as UMCT
import re
import BasicTools.Containers.ElementNames as EN
import BasicTools.Containers.ElementNames as EN
from lxml import etree
from pathlib import Path
from BasicTools.Containers.ConstantRectilinearMesh import (
ConstantRectilinearMesh)
from BasicTools.Containers.UnstructuredMesh import (UnstructuredMesh,
AllElements)
from BasicTools.Containers.MeshBase import MeshBase
from BasicTools.IO.XdmfTools import XdmfName,XdmfNumber
from pymicro.core.global_variables import (XDMF_FIELD_TYPE,
XDMF_IMAGE_GEOMETRY,
XDMF_IMAGE_TOPOLOGY)
from pymicro.core.global_variables import (SD_GROUP_TYPES, SD_GRID_GROUPS,
SD_IMAGE_GROUPS, SD_MESH_GROUPS)
from BasicTools.IO.UniversalReader import ReadMesh
and context from other files:
# Path: pymicro/core/global_variables.py
# XDMF_FIELD_TYPE = {1: 'Scalar', 2: 'Vector', 3: 'Vector', 6: 'Tensor6',
# 9: 'Tensor'}
#
# XDMF_IMAGE_GEOMETRY = {'3DImage': 'ORIGIN_DXDYDZ', '2DImage': 'ORIGIN_DXDY'}
#
# XDMF_IMAGE_TOPOLOGY = {'3DImage': '3DCoRectMesh', '2DImage': '2DCoRectMesh'}
#
# Path: pymicro/core/global_variables.py
# SD_GROUP_TYPES = ['Group', '2DImage', '3DImage', '2DMesh', '3DMesh']
#
# SD_GRID_GROUPS = ['2DImage', '3DImage', '2DMesh', '3DMesh', 'emptyImage',
# 'emptyMesh']
#
# SD_IMAGE_GROUPS = {2:'2DImage', 3:'3DImage', 0:'emptyImage', -1:'Image'}
#
# SD_MESH_GROUPS = {2:'2DMesh', 3:'3DMesh', 0:'emptyMesh', -1:'Mesh'}
, which may contain function names, class names, or code. Output only the next line. | if Field_dim not in XDMF_FIELD_TYPE: |
Using the snippet: <|code_start|> """Write grid geometry and topoly in xdmf tree/file."""
# add 1 to each dimension to get grid dimension (from cell number to
# point number --> XDMF indicates Grid points)
image_type = self._get_image_type(image_object)
# Get image dimension with reverted shape to compensate for Paraview
# X,Y,Z indexing convention
Dimension_tmp = image_object.GetDimensions()
Spacing_tmp = image_object.GetSpacing()
Origin_tmp = image_object.GetOrigin()
if len(Dimension_tmp) == 2:
Dimension_tmp = Dimension_tmp[[1,0]]
Spacing_tmp = Spacing_tmp[[1,0]]
Origin_tmp = Origin_tmp[[1,0]]
elif len(Dimension_tmp) == 3:
Dimension_tmp = Dimension_tmp[[2,1,0]]
Spacing_tmp = Spacing_tmp[[2,1,0]]
Origin_tmp = Origin_tmp[[2,1,0]]
Dimension = self._np_to_xdmf_str(Dimension_tmp)
Spacing = self._np_to_xdmf_str(Spacing_tmp)
Origin = self._np_to_xdmf_str(Origin_tmp)
Dimensionality = str(image_object.GetDimensionality())
self._verbose_print('Updating xdmf tree...', line_break=False)
# Creatge Grid element
image_xdmf = etree.Element(_tag='Grid', Name=imagename,
GridType='Uniform')
# Create Topology element
Topotype = XDMF_IMAGE_TOPOLOGY[image_type]
topology_xdmf = etree.Element(_tag='Topology', TopologyType=Topotype,
Dimensions=Dimension)
# Create Geometry element
<|code_end|>
, determine the next line of code. You have imports:
import os
import subprocess
import shutil
import numpy as np
import tables
import lxml.builder
import BasicTools.Containers.UnstructuredMeshCreationTools as UMCT
import re
import BasicTools.Containers.ElementNames as EN
import BasicTools.Containers.ElementNames as EN
from lxml import etree
from pathlib import Path
from BasicTools.Containers.ConstantRectilinearMesh import (
ConstantRectilinearMesh)
from BasicTools.Containers.UnstructuredMesh import (UnstructuredMesh,
AllElements)
from BasicTools.Containers.MeshBase import MeshBase
from BasicTools.IO.XdmfTools import XdmfName,XdmfNumber
from pymicro.core.global_variables import (XDMF_FIELD_TYPE,
XDMF_IMAGE_GEOMETRY,
XDMF_IMAGE_TOPOLOGY)
from pymicro.core.global_variables import (SD_GROUP_TYPES, SD_GRID_GROUPS,
SD_IMAGE_GROUPS, SD_MESH_GROUPS)
from BasicTools.IO.UniversalReader import ReadMesh
and context (class names, function names, or code) available:
# Path: pymicro/core/global_variables.py
# XDMF_FIELD_TYPE = {1: 'Scalar', 2: 'Vector', 3: 'Vector', 6: 'Tensor6',
# 9: 'Tensor'}
#
# XDMF_IMAGE_GEOMETRY = {'3DImage': 'ORIGIN_DXDYDZ', '2DImage': 'ORIGIN_DXDY'}
#
# XDMF_IMAGE_TOPOLOGY = {'3DImage': '3DCoRectMesh', '2DImage': '2DCoRectMesh'}
#
# Path: pymicro/core/global_variables.py
# SD_GROUP_TYPES = ['Group', '2DImage', '3DImage', '2DMesh', '3DMesh']
#
# SD_GRID_GROUPS = ['2DImage', '3DImage', '2DMesh', '3DMesh', 'emptyImage',
# 'emptyMesh']
#
# SD_IMAGE_GROUPS = {2:'2DImage', 3:'3DImage', 0:'emptyImage', -1:'Image'}
#
# SD_MESH_GROUPS = {2:'2DMesh', 3:'3DMesh', 0:'emptyMesh', -1:'Mesh'}
. Output only the next line. | Geotype = XDMF_IMAGE_GEOMETRY[image_type] |
Using the snippet: <|code_start|> mesh_group._v_pathname)
return
def _add_image_to_xdmf(self, imagename, image_object):
"""Write grid geometry and topoly in xdmf tree/file."""
# add 1 to each dimension to get grid dimension (from cell number to
# point number --> XDMF indicates Grid points)
image_type = self._get_image_type(image_object)
# Get image dimension with reverted shape to compensate for Paraview
# X,Y,Z indexing convention
Dimension_tmp = image_object.GetDimensions()
Spacing_tmp = image_object.GetSpacing()
Origin_tmp = image_object.GetOrigin()
if len(Dimension_tmp) == 2:
Dimension_tmp = Dimension_tmp[[1,0]]
Spacing_tmp = Spacing_tmp[[1,0]]
Origin_tmp = Origin_tmp[[1,0]]
elif len(Dimension_tmp) == 3:
Dimension_tmp = Dimension_tmp[[2,1,0]]
Spacing_tmp = Spacing_tmp[[2,1,0]]
Origin_tmp = Origin_tmp[[2,1,0]]
Dimension = self._np_to_xdmf_str(Dimension_tmp)
Spacing = self._np_to_xdmf_str(Spacing_tmp)
Origin = self._np_to_xdmf_str(Origin_tmp)
Dimensionality = str(image_object.GetDimensionality())
self._verbose_print('Updating xdmf tree...', line_break=False)
# Creatge Grid element
image_xdmf = etree.Element(_tag='Grid', Name=imagename,
GridType='Uniform')
# Create Topology element
<|code_end|>
, determine the next line of code. You have imports:
import os
import subprocess
import shutil
import numpy as np
import tables
import lxml.builder
import BasicTools.Containers.UnstructuredMeshCreationTools as UMCT
import re
import BasicTools.Containers.ElementNames as EN
import BasicTools.Containers.ElementNames as EN
from lxml import etree
from pathlib import Path
from BasicTools.Containers.ConstantRectilinearMesh import (
ConstantRectilinearMesh)
from BasicTools.Containers.UnstructuredMesh import (UnstructuredMesh,
AllElements)
from BasicTools.Containers.MeshBase import MeshBase
from BasicTools.IO.XdmfTools import XdmfName,XdmfNumber
from pymicro.core.global_variables import (XDMF_FIELD_TYPE,
XDMF_IMAGE_GEOMETRY,
XDMF_IMAGE_TOPOLOGY)
from pymicro.core.global_variables import (SD_GROUP_TYPES, SD_GRID_GROUPS,
SD_IMAGE_GROUPS, SD_MESH_GROUPS)
from BasicTools.IO.UniversalReader import ReadMesh
and context (class names, function names, or code) available:
# Path: pymicro/core/global_variables.py
# XDMF_FIELD_TYPE = {1: 'Scalar', 2: 'Vector', 3: 'Vector', 6: 'Tensor6',
# 9: 'Tensor'}
#
# XDMF_IMAGE_GEOMETRY = {'3DImage': 'ORIGIN_DXDYDZ', '2DImage': 'ORIGIN_DXDY'}
#
# XDMF_IMAGE_TOPOLOGY = {'3DImage': '3DCoRectMesh', '2DImage': '2DCoRectMesh'}
#
# Path: pymicro/core/global_variables.py
# SD_GROUP_TYPES = ['Group', '2DImage', '3DImage', '2DMesh', '3DMesh']
#
# SD_GRID_GROUPS = ['2DImage', '3DImage', '2DMesh', '3DMesh', 'emptyImage',
# 'emptyMesh']
#
# SD_IMAGE_GROUPS = {2:'2DImage', 3:'3DImage', 0:'emptyImage', -1:'Image'}
#
# SD_MESH_GROUPS = {2:'2DMesh', 3:'3DMesh', 0:'emptyMesh', -1:'Mesh'}
. Output only the next line. | Topotype = XDMF_IMAGE_TOPOLOGY[image_type] |
Next line prediction: <|code_start|> msg = ('Existing node {} will be overwritten to recreate '
'array/table'.format(array_path))
if not(empty):
self._verbose_print(msg)
attrs = self.get_dic_from_attributes(array_path)
self.remove_node(array_path, recursive=True)
return attrs
if replace:
msg = ('Existing node {} will be overwritten to recreate '
'array/table'.format(array_path))
if not(empty):
self._verbose_print(msg)
self.remove_node(array_path, recursive=True)
else:
msg = ('Array/table {} already exists. To overwrite, use '
'optional argument "replace=True"'
''.format(array_path))
raise tables.NodeError(msg)
return dict()
def _init_SD_group(self, groupname='', location='/',
group_type='Group', replace=False):
"""Create or fetch a SampleData Group and returns it."""
Group = None
# init flags
fetch_group = False
# sanity checks
if groupname == '':
raise ValueError('Cannot create Group. Groupname must be'
' specified')
<|code_end|>
. Use current file imports:
(import os
import subprocess
import shutil
import numpy as np
import tables
import lxml.builder
import BasicTools.Containers.UnstructuredMeshCreationTools as UMCT
import re
import BasicTools.Containers.ElementNames as EN
import BasicTools.Containers.ElementNames as EN
from lxml import etree
from pathlib import Path
from BasicTools.Containers.ConstantRectilinearMesh import (
ConstantRectilinearMesh)
from BasicTools.Containers.UnstructuredMesh import (UnstructuredMesh,
AllElements)
from BasicTools.Containers.MeshBase import MeshBase
from BasicTools.IO.XdmfTools import XdmfName,XdmfNumber
from pymicro.core.global_variables import (XDMF_FIELD_TYPE,
XDMF_IMAGE_GEOMETRY,
XDMF_IMAGE_TOPOLOGY)
from pymicro.core.global_variables import (SD_GROUP_TYPES, SD_GRID_GROUPS,
SD_IMAGE_GROUPS, SD_MESH_GROUPS)
from BasicTools.IO.UniversalReader import ReadMesh)
and context including class names, function names, or small code snippets from other files:
# Path: pymicro/core/global_variables.py
# XDMF_FIELD_TYPE = {1: 'Scalar', 2: 'Vector', 3: 'Vector', 6: 'Tensor6',
# 9: 'Tensor'}
#
# XDMF_IMAGE_GEOMETRY = {'3DImage': 'ORIGIN_DXDYDZ', '2DImage': 'ORIGIN_DXDY'}
#
# XDMF_IMAGE_TOPOLOGY = {'3DImage': '3DCoRectMesh', '2DImage': '2DCoRectMesh'}
#
# Path: pymicro/core/global_variables.py
# SD_GROUP_TYPES = ['Group', '2DImage', '3DImage', '2DMesh', '3DMesh']
#
# SD_GRID_GROUPS = ['2DImage', '3DImage', '2DMesh', '3DMesh', 'emptyImage',
# 'emptyMesh']
#
# SD_IMAGE_GROUPS = {2:'2DImage', 3:'3DImage', 0:'emptyImage', -1:'Image'}
#
# SD_MESH_GROUPS = {2:'2DMesh', 3:'3DMesh', 0:'emptyMesh', -1:'Mesh'}
. Output only the next line. | if group_type not in SD_GROUP_TYPES: |
Using the snippet: <|code_start|> Class = self._get_node_class(name2)
List = ['CARRAY', 'EARRAY', 'VLARRAY', 'ARRAY', 'TABLE']
return Class in List
def _is_table(self, name):
"""Find out if name or path references an array dataset."""
return self._get_node_class(name) == 'TABLE'
def _is_table_descr(self, obj):
"""Find out if name or path references an array dataset."""
is_descr=False
try:
is_descr = issubclass(obj, tables.IsDescription)
except TypeError:
is_descr=False
if is_descr:
return is_descr
try:
is_descr = (isinstance(obj, tables.IsDescription)
or isinstance(obj, np.dtype))
except TypeError:
is_descr=False
return is_descr
def _is_group(self, name):
"""Find out if name or path references a HDF5 Group."""
return self._get_node_class(name) == 'GROUP'
def _is_grid(self, name):
"""Find out if name or path references a image or mesh HDF5 Group."""
<|code_end|>
, determine the next line of code. You have imports:
import os
import subprocess
import shutil
import numpy as np
import tables
import lxml.builder
import BasicTools.Containers.UnstructuredMeshCreationTools as UMCT
import re
import BasicTools.Containers.ElementNames as EN
import BasicTools.Containers.ElementNames as EN
from lxml import etree
from pathlib import Path
from BasicTools.Containers.ConstantRectilinearMesh import (
ConstantRectilinearMesh)
from BasicTools.Containers.UnstructuredMesh import (UnstructuredMesh,
AllElements)
from BasicTools.Containers.MeshBase import MeshBase
from BasicTools.IO.XdmfTools import XdmfName,XdmfNumber
from pymicro.core.global_variables import (XDMF_FIELD_TYPE,
XDMF_IMAGE_GEOMETRY,
XDMF_IMAGE_TOPOLOGY)
from pymicro.core.global_variables import (SD_GROUP_TYPES, SD_GRID_GROUPS,
SD_IMAGE_GROUPS, SD_MESH_GROUPS)
from BasicTools.IO.UniversalReader import ReadMesh
and context (class names, function names, or code) available:
# Path: pymicro/core/global_variables.py
# XDMF_FIELD_TYPE = {1: 'Scalar', 2: 'Vector', 3: 'Vector', 6: 'Tensor6',
# 9: 'Tensor'}
#
# XDMF_IMAGE_GEOMETRY = {'3DImage': 'ORIGIN_DXDYDZ', '2DImage': 'ORIGIN_DXDY'}
#
# XDMF_IMAGE_TOPOLOGY = {'3DImage': '3DCoRectMesh', '2DImage': '2DCoRectMesh'}
#
# Path: pymicro/core/global_variables.py
# SD_GROUP_TYPES = ['Group', '2DImage', '3DImage', '2DMesh', '3DMesh']
#
# SD_GRID_GROUPS = ['2DImage', '3DImage', '2DMesh', '3DMesh', 'emptyImage',
# 'emptyMesh']
#
# SD_IMAGE_GROUPS = {2:'2DImage', 3:'3DImage', 0:'emptyImage', -1:'Image'}
#
# SD_MESH_GROUPS = {2:'2DMesh', 3:'3DMesh', 0:'emptyMesh', -1:'Mesh'}
. Output only the next line. | return self._get_group_type(name) in SD_GRID_GROUPS |
Given the code snippet: <|code_start|> max_path_level = max(value.count('/'), max_path_level)
for level in range(max_path_level):
self._verbose_print(f'Initializing level {level+1} of data model')
for key, value in content_paths.items():
if value.count('/') != level+1:
continue
head, tail = os.path.split(value)
# Find out if object is a description object
is_descr = self._is_table_descr(content_type[key])
if self.h5_dataset.__contains__(content_paths[key]):
if self._is_table(content_paths[key]):
msg = ('Updating table {}'.format(content_paths[key]))
self._verbose_print(msg)
self._update_table_columns(
tablename=content_paths[key],
Description=content_type[key])
if self._is_empty(content_paths[key]):
self._verbose_print('Warning: node {} specified in the'
' minimal data model for this class'
' is empty'
''.format(content_paths[key]))
continue
elif is_descr:
msg = ('Adding empty Table {}'.format(content_paths[key]))
self.add_table(location=head, name=tail, indexname=key,
description=content_type[key])
elif content_type[key] == 'Group':
msg = f'Adding empty Group {content_paths[key]}'
self.add_group(groupname=tail, location=head,
indexname=key, replace=False)
<|code_end|>
, generate the next line using the imports in this file:
import os
import subprocess
import shutil
import numpy as np
import tables
import lxml.builder
import BasicTools.Containers.UnstructuredMeshCreationTools as UMCT
import re
import BasicTools.Containers.ElementNames as EN
import BasicTools.Containers.ElementNames as EN
from lxml import etree
from pathlib import Path
from BasicTools.Containers.ConstantRectilinearMesh import (
ConstantRectilinearMesh)
from BasicTools.Containers.UnstructuredMesh import (UnstructuredMesh,
AllElements)
from BasicTools.Containers.MeshBase import MeshBase
from BasicTools.IO.XdmfTools import XdmfName,XdmfNumber
from pymicro.core.global_variables import (XDMF_FIELD_TYPE,
XDMF_IMAGE_GEOMETRY,
XDMF_IMAGE_TOPOLOGY)
from pymicro.core.global_variables import (SD_GROUP_TYPES, SD_GRID_GROUPS,
SD_IMAGE_GROUPS, SD_MESH_GROUPS)
from BasicTools.IO.UniversalReader import ReadMesh
and context (functions, classes, or occasionally code) from other files:
# Path: pymicro/core/global_variables.py
# XDMF_FIELD_TYPE = {1: 'Scalar', 2: 'Vector', 3: 'Vector', 6: 'Tensor6',
# 9: 'Tensor'}
#
# XDMF_IMAGE_GEOMETRY = {'3DImage': 'ORIGIN_DXDYDZ', '2DImage': 'ORIGIN_DXDY'}
#
# XDMF_IMAGE_TOPOLOGY = {'3DImage': '3DCoRectMesh', '2DImage': '2DCoRectMesh'}
#
# Path: pymicro/core/global_variables.py
# SD_GROUP_TYPES = ['Group', '2DImage', '3DImage', '2DMesh', '3DMesh']
#
# SD_GRID_GROUPS = ['2DImage', '3DImage', '2DMesh', '3DMesh', 'emptyImage',
# 'emptyMesh']
#
# SD_IMAGE_GROUPS = {2:'2DImage', 3:'3DImage', 0:'emptyImage', -1:'Image'}
#
# SD_MESH_GROUPS = {2:'2DMesh', 3:'3DMesh', 0:'emptyMesh', -1:'Mesh'}
. Output only the next line. | elif content_type[key] in SD_IMAGE_GROUPS.values(): |
Given the following code snippet before the placeholder: <|code_start|> for key, value in content_paths.items():
if value.count('/') != level+1:
continue
head, tail = os.path.split(value)
# Find out if object is a description object
is_descr = self._is_table_descr(content_type[key])
if self.h5_dataset.__contains__(content_paths[key]):
if self._is_table(content_paths[key]):
msg = ('Updating table {}'.format(content_paths[key]))
self._verbose_print(msg)
self._update_table_columns(
tablename=content_paths[key],
Description=content_type[key])
if self._is_empty(content_paths[key]):
self._verbose_print('Warning: node {} specified in the'
' minimal data model for this class'
' is empty'
''.format(content_paths[key]))
continue
elif is_descr:
msg = ('Adding empty Table {}'.format(content_paths[key]))
self.add_table(location=head, name=tail, indexname=key,
description=content_type[key])
elif content_type[key] == 'Group':
msg = f'Adding empty Group {content_paths[key]}'
self.add_group(groupname=tail, location=head,
indexname=key, replace=False)
elif content_type[key] in SD_IMAGE_GROUPS.values():
msg = f'Adding empty Image Group {content_paths[key]}'
self.add_image(imagename=tail, indexname=key, location=head)
<|code_end|>
, predict the next line using imports from the current file:
import os
import subprocess
import shutil
import numpy as np
import tables
import lxml.builder
import BasicTools.Containers.UnstructuredMeshCreationTools as UMCT
import re
import BasicTools.Containers.ElementNames as EN
import BasicTools.Containers.ElementNames as EN
from lxml import etree
from pathlib import Path
from BasicTools.Containers.ConstantRectilinearMesh import (
ConstantRectilinearMesh)
from BasicTools.Containers.UnstructuredMesh import (UnstructuredMesh,
AllElements)
from BasicTools.Containers.MeshBase import MeshBase
from BasicTools.IO.XdmfTools import XdmfName,XdmfNumber
from pymicro.core.global_variables import (XDMF_FIELD_TYPE,
XDMF_IMAGE_GEOMETRY,
XDMF_IMAGE_TOPOLOGY)
from pymicro.core.global_variables import (SD_GROUP_TYPES, SD_GRID_GROUPS,
SD_IMAGE_GROUPS, SD_MESH_GROUPS)
from BasicTools.IO.UniversalReader import ReadMesh
and context including class names, function names, and sometimes code from other files:
# Path: pymicro/core/global_variables.py
# XDMF_FIELD_TYPE = {1: 'Scalar', 2: 'Vector', 3: 'Vector', 6: 'Tensor6',
# 9: 'Tensor'}
#
# XDMF_IMAGE_GEOMETRY = {'3DImage': 'ORIGIN_DXDYDZ', '2DImage': 'ORIGIN_DXDY'}
#
# XDMF_IMAGE_TOPOLOGY = {'3DImage': '3DCoRectMesh', '2DImage': '2DCoRectMesh'}
#
# Path: pymicro/core/global_variables.py
# SD_GROUP_TYPES = ['Group', '2DImage', '3DImage', '2DMesh', '3DMesh']
#
# SD_GRID_GROUPS = ['2DImage', '3DImage', '2DMesh', '3DMesh', 'emptyImage',
# 'emptyMesh']
#
# SD_IMAGE_GROUPS = {2:'2DImage', 3:'3DImage', 0:'emptyImage', -1:'Image'}
#
# SD_MESH_GROUPS = {2:'2DMesh', 3:'3DMesh', 0:'emptyMesh', -1:'Mesh'}
. Output only the next line. | elif content_type[key] in SD_MESH_GROUPS.values(): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
'''Basic curve fitting example with a cosine function. The data is
also fitted with a custom function slightly different than the default
Cosine, which lead to the same result.'''
x = np.linspace(-3.0, 3.0, 31)
# generate some noisy data
np.random.seed(13)
y = np.cos(4 * x / np.pi - 0.5) + 0.05 * np.random.randn(len(x))
# custom function
def C(x, p):
return np.sin(np.pi * (x - p[0].value) / (2 * p[1].value)) * p[2].value
# perform fitting
<|code_end|>
. Use current file imports:
import numpy as np
import os
from matplotlib import pyplot as plt
from pymicro.xray.fitting import fit
from matplotlib import image
and context (classes, functions, or code) from other files:
# Path: pymicro/xray/fitting.py
# def fit(y, x=None, expression=None, nb_params=None, init=None):
# '''Static method to perform curve fitting directly.
#
# *Parameters*
#
# **y**: the data to match (a 1d numpy array)
#
# **x**: the corresponding x coordinates (optional, None by default)
#
# **expression**: can be either a string to select a predefined
# function or alternatively a user defined function with the signature
# f(x, p) (in this case you must specify the length of the parameters
# array p via setting nb_params).
#
# **nb_params**: the number of parameters of the user defined fitting
# function (only needed when a custom fitting function is provided,
# None by default)
#
# **init**: a sequence (the length must be equal to the number of
# parameters of the fitting function) used to initialise the fitting
# function.
#
# For instance, to fit some (x,y) data with a gaussian function, simply use:
# ::
#
# F = fit(y, x, expression='Gaussian')
#
# Alternatively you may specify you own function directly defined with Python, like:
# ::
#
# def myf(x, p):
# return p[0]*x + p[1]
#
# F = fit(y, x, expression=myf, nb_params=2)
# '''
# if expression == 'Gaussian':
# F = Gaussian()
# elif expression == 'Lorentzian':
# F = Lorentzian()
# elif expression == 'Cosine':
# F = Cosine()
# elif expression == 'Voigt':
# F = Voigt()
# else:
# F = FitFunction()
# if not nb_params:
# print('please specify the number of parameters for your fit function, aborting fit...')
# return None
# if not init:
# init = np.ones(nb_params)
# if not len(init) == nb_params:
# print(
# 'there are more parameters in the fit function than specified in the initialization sequence, aborting initialization...')
# init = np.ones(nb_params)
# for i in range(nb_params):
# F.add_parameter(init[i], 'p%d' % i)
# F.expression = expression
# F.fit(y, x)
# return F
. Output only the next line. | F = fit(y, x, expression=C, nb_params=3) |
Predict the next line for this snippet: <|code_start|> self.assertEqual(infos['y_dim'], 4)
self.assertEqual(infos['z_dim'], 5)
self.assertEqual(infos['data_type'], 'PACKED_BINARY')
bin_data = HST_read('test_bool_write.raw')
self.assertEqual(bin_data.dtype, np.uint8)
self.assertEqual(bin_data[0, 1, 2], True)
self.assertEqual(bin_data[0, 1, 1], False)
self.assertEqual(bin_data[1, 2, 3], True)
self.assertEqual(bin_data[2, 3, 4], True)
def test_write_bool_array(self):
bin_data = HST_read('test_bool_write_as_uint8.raw')
self.assertEqual(bin_data.dtype, np.uint8)
size = os.path.getsize('test_bool_write_as_uint8.raw')
self.assertEqual(size, 60)
def tearDown(self):
os.remove('temp_20x30x10_uint8.raw')
os.remove('temp_20x30x10_uint8.raw.info')
os.remove('test_bool_write_as_uint8.raw')
os.remove('test_bool_write_as_uint8.raw.info')
os.remove('test_bool_write.raw')
os.remove('test_bool_write.raw.info')
os.remove('temp.info')
class TiffTests(unittest.TestCase):
def setUp(self):
print('testing the Tifffile module')
self.data = (255 * np.random.rand(5, 301, 219)).astype(np.uint8)
<|code_end|>
with the help of current file imports:
import unittest
import numpy as np
import os
from pymicro.file.file_utils import *
from pymicro.external.tifffile import imsave, imread
from config import PYMICRO_EXAMPLES_DATA_DIR
and context from other files:
# Path: pymicro/external/tifffile.py
# def imsave(file, data, **kwargs):
# """Write image data to TIFF file.
#
# Refer to the TiffWriter class and member functions for documentation.
#
# Parameters
# ----------
# file : str or binary stream
# File name or writable binary stream, such as a open file or BytesIO.
# data : array_like
# Input image. The last dimensions are assumed to be image depth,
# height, width, and samples.
# kwargs : dict
# Parameters 'append', 'byteorder', 'bigtiff', 'software', and 'imagej',
# are passed to the TiffWriter class.
# Parameters 'photometric', 'planarconfig', 'resolution', 'compress',
# 'colormap', 'tile', 'description', 'datetime', 'metadata', 'contiguous'
# and 'extratags' are passed to the TiffWriter.save function.
#
# Examples
# --------
# >>> data = numpy.random.rand(2, 5, 3, 301, 219)
# >>> imsave('temp.tif', data, compress=6, metadata={'axes': 'TZCYX'})
#
# """
# tifargs = parse_kwargs(kwargs, 'append', 'bigtiff', 'byteorder',
# 'software', 'imagej')
#
# if 'bigtiff' not in tifargs and 'imagej' not in tifargs and (
# data.size*data.dtype.itemsize > 2000*2**20):
# tifargs['bigtiff'] = True
#
# with TiffWriter(file, **tifargs) as tif:
# tif.save(data, **kwargs)
#
# def imread(files, **kwargs):
# """Return image data from TIFF file(s) as numpy array.
#
# Refer to the TiffFile class and member functions for documentation.
#
# Parameters
# ----------
# files : str, binary stream, or sequence
# File name, seekable binary stream, glob pattern, or sequence of
# file names.
# kwargs : dict
# Parameters 'multifile', 'multifile_close', 'pages', 'fastij', and
# 'is_ome' are passed to the TiffFile class.
# The 'pattern' parameter is passed to the TiffSequence class.
# Other parameters are passed to the asarray functions.
# The first image series is returned if no arguments are provided.
#
# Examples
# --------
# >>> imsave('temp.tif', numpy.random.rand(3, 4, 301, 219))
# >>> im = imread('temp.tif', key=0)
# >>> im.shape
# (4, 301, 219)
# >>> ims = imread(['temp.tif', 'temp.tif'])
# >>> ims.shape
# (2, 3, 4, 301, 219)
#
# """
# kwargs_file = parse_kwargs(kwargs, 'multifile', 'multifile_close',
# 'pages', 'fastij', 'is_ome')
# kwargs_seq = parse_kwargs(kwargs, 'pattern')
#
# if isinstance(files, basestring) and any(i in files for i in '?*'):
# files = glob.glob(files)
# if not files:
# raise ValueError('no files found')
# if not hasattr(files, 'seek') and len(files) == 1:
# files = files[0]
#
# if isinstance(files, basestring) or hasattr(files, 'seek'):
# with TiffFile(files, **kwargs_file) as tif:
# return tif.asarray(**kwargs)
# else:
# with TiffSequence(files, **kwargs_seq) as imseq:
# return imseq.asarray(**kwargs)
#
# Path: config.py
# PYMICRO_EXAMPLES_DATA_DIR = os.path.join(PYMICRO_ROOT_DIR, 'examples', 'data')
, which may contain function names, class names, or code. Output only the next line. | imsave('temp.tif', self.data) |
Given the code snippet: <|code_start|> bin_data = HST_read('test_bool_write.raw')
self.assertEqual(bin_data.dtype, np.uint8)
self.assertEqual(bin_data[0, 1, 2], True)
self.assertEqual(bin_data[0, 1, 1], False)
self.assertEqual(bin_data[1, 2, 3], True)
self.assertEqual(bin_data[2, 3, 4], True)
def test_write_bool_array(self):
bin_data = HST_read('test_bool_write_as_uint8.raw')
self.assertEqual(bin_data.dtype, np.uint8)
size = os.path.getsize('test_bool_write_as_uint8.raw')
self.assertEqual(size, 60)
def tearDown(self):
os.remove('temp_20x30x10_uint8.raw')
os.remove('temp_20x30x10_uint8.raw.info')
os.remove('test_bool_write_as_uint8.raw')
os.remove('test_bool_write_as_uint8.raw.info')
os.remove('test_bool_write.raw')
os.remove('test_bool_write.raw.info')
os.remove('temp.info')
class TiffTests(unittest.TestCase):
def setUp(self):
print('testing the Tifffile module')
self.data = (255 * np.random.rand(5, 301, 219)).astype(np.uint8)
imsave('temp.tif', self.data)
def test_imread(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import numpy as np
import os
from pymicro.file.file_utils import *
from pymicro.external.tifffile import imsave, imread
from config import PYMICRO_EXAMPLES_DATA_DIR
and context (functions, classes, or occasionally code) from other files:
# Path: pymicro/external/tifffile.py
# def imsave(file, data, **kwargs):
# """Write image data to TIFF file.
#
# Refer to the TiffWriter class and member functions for documentation.
#
# Parameters
# ----------
# file : str or binary stream
# File name or writable binary stream, such as a open file or BytesIO.
# data : array_like
# Input image. The last dimensions are assumed to be image depth,
# height, width, and samples.
# kwargs : dict
# Parameters 'append', 'byteorder', 'bigtiff', 'software', and 'imagej',
# are passed to the TiffWriter class.
# Parameters 'photometric', 'planarconfig', 'resolution', 'compress',
# 'colormap', 'tile', 'description', 'datetime', 'metadata', 'contiguous'
# and 'extratags' are passed to the TiffWriter.save function.
#
# Examples
# --------
# >>> data = numpy.random.rand(2, 5, 3, 301, 219)
# >>> imsave('temp.tif', data, compress=6, metadata={'axes': 'TZCYX'})
#
# """
# tifargs = parse_kwargs(kwargs, 'append', 'bigtiff', 'byteorder',
# 'software', 'imagej')
#
# if 'bigtiff' not in tifargs and 'imagej' not in tifargs and (
# data.size*data.dtype.itemsize > 2000*2**20):
# tifargs['bigtiff'] = True
#
# with TiffWriter(file, **tifargs) as tif:
# tif.save(data, **kwargs)
#
# def imread(files, **kwargs):
# """Return image data from TIFF file(s) as numpy array.
#
# Refer to the TiffFile class and member functions for documentation.
#
# Parameters
# ----------
# files : str, binary stream, or sequence
# File name, seekable binary stream, glob pattern, or sequence of
# file names.
# kwargs : dict
# Parameters 'multifile', 'multifile_close', 'pages', 'fastij', and
# 'is_ome' are passed to the TiffFile class.
# The 'pattern' parameter is passed to the TiffSequence class.
# Other parameters are passed to the asarray functions.
# The first image series is returned if no arguments are provided.
#
# Examples
# --------
# >>> imsave('temp.tif', numpy.random.rand(3, 4, 301, 219))
# >>> im = imread('temp.tif', key=0)
# >>> im.shape
# (4, 301, 219)
# >>> ims = imread(['temp.tif', 'temp.tif'])
# >>> ims.shape
# (2, 3, 4, 301, 219)
#
# """
# kwargs_file = parse_kwargs(kwargs, 'multifile', 'multifile_close',
# 'pages', 'fastij', 'is_ome')
# kwargs_seq = parse_kwargs(kwargs, 'pattern')
#
# if isinstance(files, basestring) and any(i in files for i in '?*'):
# files = glob.glob(files)
# if not files:
# raise ValueError('no files found')
# if not hasattr(files, 'seek') and len(files) == 1:
# files = files[0]
#
# if isinstance(files, basestring) or hasattr(files, 'seek'):
# with TiffFile(files, **kwargs_file) as tif:
# return tif.asarray(**kwargs)
# else:
# with TiffSequence(files, **kwargs_seq) as imseq:
# return imseq.asarray(**kwargs)
#
# Path: config.py
# PYMICRO_EXAMPLES_DATA_DIR = os.path.join(PYMICRO_ROOT_DIR, 'examples', 'data')
. Output only the next line. | image = imread('temp.tif') |
Based on the snippet: <|code_start|>
class file_utils_Tests(unittest.TestCase):
def setUp(self):
print('testing the file_utils module')
self.data = (255 * np.random.rand(20, 30, 10)).astype(np.uint8)
HST_write(self.data, 'temp_20x30x10_uint8.raw')
data = np.zeros((3, 4, 5), dtype=bool)
data[0, 1, 2] = True
data[1, 2, 3] = True
data[2, 3, 4] = True
HST_write(data, 'test_bool_write.raw', pack_binary=True)
HST_write(data, 'test_bool_write_as_uint8.raw', pack_binary=False)
# craft a custom info file without the DATA_TYPE info
f = open('temp.info', 'w')
f.write('! PyHST_SLAVE VOLUME INFO FILE\n')
f.write('NUM_X = 953\n')
f.write('NUM_Y = 542\n')
f.write('NUM_Z = 104\n')
f.close()
def test_edf_info(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import numpy as np
import os
from pymicro.file.file_utils import *
from pymicro.external.tifffile import imsave, imread
from config import PYMICRO_EXAMPLES_DATA_DIR
and context (classes, functions, sometimes code) from other files:
# Path: pymicro/external/tifffile.py
# def imsave(file, data, **kwargs):
# """Write image data to TIFF file.
#
# Refer to the TiffWriter class and member functions for documentation.
#
# Parameters
# ----------
# file : str or binary stream
# File name or writable binary stream, such as a open file or BytesIO.
# data : array_like
# Input image. The last dimensions are assumed to be image depth,
# height, width, and samples.
# kwargs : dict
# Parameters 'append', 'byteorder', 'bigtiff', 'software', and 'imagej',
# are passed to the TiffWriter class.
# Parameters 'photometric', 'planarconfig', 'resolution', 'compress',
# 'colormap', 'tile', 'description', 'datetime', 'metadata', 'contiguous'
# and 'extratags' are passed to the TiffWriter.save function.
#
# Examples
# --------
# >>> data = numpy.random.rand(2, 5, 3, 301, 219)
# >>> imsave('temp.tif', data, compress=6, metadata={'axes': 'TZCYX'})
#
# """
# tifargs = parse_kwargs(kwargs, 'append', 'bigtiff', 'byteorder',
# 'software', 'imagej')
#
# if 'bigtiff' not in tifargs and 'imagej' not in tifargs and (
# data.size*data.dtype.itemsize > 2000*2**20):
# tifargs['bigtiff'] = True
#
# with TiffWriter(file, **tifargs) as tif:
# tif.save(data, **kwargs)
#
# def imread(files, **kwargs):
# """Return image data from TIFF file(s) as numpy array.
#
# Refer to the TiffFile class and member functions for documentation.
#
# Parameters
# ----------
# files : str, binary stream, or sequence
# File name, seekable binary stream, glob pattern, or sequence of
# file names.
# kwargs : dict
# Parameters 'multifile', 'multifile_close', 'pages', 'fastij', and
# 'is_ome' are passed to the TiffFile class.
# The 'pattern' parameter is passed to the TiffSequence class.
# Other parameters are passed to the asarray functions.
# The first image series is returned if no arguments are provided.
#
# Examples
# --------
# >>> imsave('temp.tif', numpy.random.rand(3, 4, 301, 219))
# >>> im = imread('temp.tif', key=0)
# >>> im.shape
# (4, 301, 219)
# >>> ims = imread(['temp.tif', 'temp.tif'])
# >>> ims.shape
# (2, 3, 4, 301, 219)
#
# """
# kwargs_file = parse_kwargs(kwargs, 'multifile', 'multifile_close',
# 'pages', 'fastij', 'is_ome')
# kwargs_seq = parse_kwargs(kwargs, 'pattern')
#
# if isinstance(files, basestring) and any(i in files for i in '?*'):
# files = glob.glob(files)
# if not files:
# raise ValueError('no files found')
# if not hasattr(files, 'seek') and len(files) == 1:
# files = files[0]
#
# if isinstance(files, basestring) or hasattr(files, 'seek'):
# with TiffFile(files, **kwargs_file) as tif:
# return tif.asarray(**kwargs)
# else:
# with TiffSequence(files, **kwargs_seq) as imseq:
# return imseq.asarray(**kwargs)
#
# Path: config.py
# PYMICRO_EXAMPLES_DATA_DIR = os.path.join(PYMICRO_ROOT_DIR, 'examples', 'data')
. Output only the next line. | infos = edf_info(os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'sam8_dct0_cen_full0000.edf')) |
Here is a snippet: <|code_start|>
class FittingTests(unittest.TestCase):
def setUp(self):
"""testing the fitting module:"""
def test_lin_reg(self):
"""Verify the linear regression, example from wikipedia."""
xi = np.array([1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83])
yi = np.array([52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46])
<|code_end|>
. Write the next line using the current file imports:
import unittest
import numpy as np
from pymicro.xray.fitting import lin_reg
and context from other files:
# Path: pymicro/xray/fitting.py
# def lin_reg(xi, yi):
# """Apply linear regression to a series of points.
#
# This function return the best linear fit in the least square sense.
# :param ndarray xi: a 1D array of the x coordinate.
# :param ndarray yi: a 1D array of the y coordinate.
# :return tuple: the linear intercept, slope and correlation coefficient.
# """
# n = len(xi)
# assert (n == len(yi))
# sx = np.sum(xi)
# sy = np.sum(yi)
# sxx = np.sum(xi ** 2)
# sxy = np.sum(xi * yi)
# syy = np.sum(yi ** 2)
# beta = (n * sxy - sx * sy) / (n * sxx - sx ** 2)
# alpha = 1. / n * sy - 1. / n * sx * beta
# r = (n * sxy - sx * sy) / np.sqrt((n * sxx - sx ** 2) * (n * syy - sy ** 2))
# return alpha, beta, r
, which may include functions, classes, or code. Output only the next line. | alpha, beta, r = lin_reg(xi, yi) |
Next line prediction: <|code_start|>
def density_from_Z(Z):
if not Z in elements:
print('unknown atomic number: %d' % Z)
return None
return elements[Z].density
def density_from_symbol(symbol):
for Z in elements:
if elements[Z].symbol == symbol:
return elements[Z].density
print('unknown symbol: %s' % symbol)
return None
def f_atom(q, Z):
"""Empirical function for the atomic form factor f.
This function implements the empirical function from the paper of Muhammad and Lee
to provide value of f for elements in the range Z <= 30.
doi:10.1371/journal.pone.0069608.t001
:param float q: value or series for the momentum transfer, unit is angstrom^-1
:param int Z: atomic number, must be lower than 30.
:return: the atomic form factor value or series corresponding to q.
"""
if Z > 30:
raise ValueError('only atoms with Z<=30 are supported, consider using tabulated data.')
a0 = 0.52978 # angstrom, Bohr radius
<|code_end|>
. Use current file imports:
(import os, numpy as np
from matplotlib import pyplot as plt
from skimage.transform import radon
from math import *
from config import PYMICRO_XRAY_DATA_DIR)
and context including class names, function names, or small code snippets from other files:
# Path: config.py
# PYMICRO_XRAY_DATA_DIR = os.path.join(PYMICRO_ROOT_DIR, 'pymicro', 'xray', 'data')
. Output only the next line. | params = np.genfromtxt(os.path.join(PYMICRO_XRAY_DATA_DIR, 'f_atom_params.txt'), names=True) |
Based on the snippet: <|code_start|>
mar = Mar165() # create a mar object
mar.ucen = 981 # position of the direct beam on the x axis
mar.vcen = 1060 # position of the direct beam on the y axis
mar.calib = 495. / 15. # identified on (111) ring of CeO2 powder
mar.correction = 'bg'
mar.compute_TwoTh_Psi_arrays()
# load background for correction
<|code_end|>
, predict the immediate next line with the help of imports:
import os, numpy as np
from pymicro.xray.detectors import Mar165
from pymicro.file.file_utils import HST_read
from matplotlib import pyplot as plt, cm
from matplotlib import image
and context (classes, functions, sometimes code) from other files:
# Path: pymicro/xray/detectors.py
# class Mar165(RegArrayDetector2d):
# '''Class to handle a rayonix marccd165.
#
# The image plate marccd 165 detector produces 16 bits unsigned (2048, 2048) square images.
# '''
#
# def __init__(self):
# RegArrayDetector2d.__init__(self, size=(2048, 2048), data_type=np.uint16)
# self.pixel_size = 0.08 # mm
#
# Path: pymicro/file/file_utils.py
# def HST_read(scan_name, zrange=None, data_type=np.uint8, verbose=False,
# header_size=0, autoparse_filename=False, dims=None, mmap=False, pack_binary=False):
# '''Read a volume file stored as a concatenated stack of binary images.
#
# The volume size must be specified by dims=(nx, ny, nz) unless an associated
# .info file is present in the same location to determine the volume
# size. The data type is unsigned short (8 bits) by default but can be set
# to any numpy type (32 bits float for example).
#
# The autoparse_filename can be activated to retreive image type and
# size:
# ::
#
# HST_read(myvol_100x200x50_uint16.raw, autoparse_filename=True)
#
# will read the 3d image as unsigned 16 bits with size 100 x 200 x 50.
#
# .. note::
#
# If you use this function to read a .edf file written by
# matlab in +y+x+z convention (column major order), you may want to
# use: np.swapaxes(HST_read('file.edf', ...), 0, 1)
#
# :param str scan_name: path to the binary file to read.
# :param zrange: range of slices to use.
# :param data_type: numpy data type to use.
# :param bool verbose: flag to activate verbose mode.
# :param int header_size: number of bytes to skeep before reading the payload.
# :param bool autoparse_filename: flag to parse the file name to retreive the dims and data_type automatically.
# :param tuple dims: a tuple containing the array dimensions.
# :param bool mmap: activate the memory mapping mode.
# :param bool pack_binary: this flag should be true when reading a file written with the binary packing mode.
# '''
# if autoparse_filename:
# s_type = scan_name[:-4].split('_')[-1]
# data_type = np.dtype(s_type)
# s_size = scan_name[:-4].split('_')[-2].split('x')
# dims = (int(s_size[0]), int(s_size[1]), int(s_size[2]))
# if verbose:
# print('auto parsing filename: data type is set to', data_type)
# if dims is None:
# infos = HST_info(scan_name + '.info')
# [nx, ny, nz] = [infos['x_dim'], infos['y_dim'], infos['z_dim']]
# if 'data_type' in infos:
# if infos['data_type'] == 'PACKED_BINARY':
# pack_binary = True
# data_type = np.uint8
# else:
# data_type = np.dtype(infos['data_type'].lower()) # overwrite defaults with .info file value
# else:
# (nx, ny, nz) = dims
# if zrange is None:
# zrange = range(0, nz)
# if verbose:
# print('data type is', data_type)
# print('volume size is %d x %d x %d' % (nx, ny, len(zrange)))
# if pack_binary:
# print('unpacking binary data from single bytes (8 values per byte)')
# if mmap:
# data = np.memmap(scan_name, dtype=data_type, mode='c', shape=(len(zrange), ny, nx))
# else:
# f = open(scan_name, 'rb')
# f.seek(header_size + np.dtype(data_type).itemsize * nx * ny * zrange[0])
# if verbose:
# print('reading volume... from byte %d' % f.tell())
# # read the payload
# payload = f.read(np.dtype(data_type).itemsize * len(zrange) * ny * nx)
# if pack_binary:
# data = np.unpackbits(np.fromstring(payload, data_type))[:len(zrange) * ny * nx]
# else:
# data = np.fromstring(payload, data_type)
# # convert the payload into actual 3D data
# data = np.reshape(data.astype(data_type), (len(zrange), ny, nx), order='C')
# f.close()
# # HP 10/2013 start using proper [x,y,z] data ordering
# data_xyz = data.transpose(2, 1, 0)
# return data_xyz
. Output only the next line. | mar.bg = HST_read('../data/c1_exptime_bgair_5.raw', data_type=np.uint16, dims=(2048, 2048, 1))[:, :, 0].astype( |
Given the code snippet: <|code_start|>
class XrayUtilsTests(unittest.TestCase):
def test_f_atom(self):
"""Verify the calculation of the atom form factor."""
for Z in range(1, 30):
# error is less than 3%
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from pymicro.xray.xray_utils import f_atom
and context (functions, classes, or occasionally code) from other files:
# Path: pymicro/xray/xray_utils.py
# def f_atom(q, Z):
# """Empirical function for the atomic form factor f.
#
# This function implements the empirical function from the paper of Muhammad and Lee
# to provide value of f for elements in the range Z <= 30.
# doi:10.1371/journal.pone.0069608.t001
#
# :param float q: value or series for the momentum transfer, unit is angstrom^-1
# :param int Z: atomic number, must be lower than 30.
# :return: the atomic form factor value or series corresponding to q.
# """
# if Z > 30:
# raise ValueError('only atoms with Z<=30 are supported, consider using tabulated data.')
# a0 = 0.52978 # angstrom, Bohr radius
# params = np.genfromtxt(os.path.join(PYMICRO_XRAY_DATA_DIR, 'f_atom_params.txt'), names=True)
# Z, r, a1, b1, a2, b2, a3, b3, _, _, _ = params[int(Z - 1)]
# print(Z, r, a1, b1, a2, b2, a3, b3)
# f = (a1 * Z) ** r / ((a1 * Z) ** r + b1 * (2 * pi * a0 * q) ** r) ** r + \
# (a2 * Z) ** r / ((2 * a2 * Z) ** r + b2 * (2 * pi * a0 * q) ** 2) ** 2 + \
# (a3 * Z) ** r / ((2 * a3 * Z) ** 2 + b3 * (2 * pi * a0 * q) ** 2) ** 2
# return f
. Output only the next line. | self.assertLess(abs(f_atom(0., Z) - Z) / Z, 0.03) |
Given the following code snippet before the placeholder: <|code_start|>
class VolUtilsTests(unittest.TestCase):
def setUp(self):
print('testing the vol_utils module')
self.mu, self.sigma = 0, 0.2 # mean and standard deviation
np.random.seed(42)
self.data = np.random.normal(self.mu, self.sigma, 3000)
def test_min_max_cumsum(self):
count, bins = np.histogram(self.data, 30, range=(-3 * self.sigma, 3 * self.sigma), density=True)
bin_centers = 0.5 * (bins[:-1] + bins[1:])
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import numpy as np
from pymicro.view.vol_utils import min_max_cumsum, auto_min_max
from scipy import misc
and context including class names, function names, and sometimes code from other files:
# Path: pymicro/view/vol_utils.py
# def min_max_cumsum(data, cut=0.001, verbose=False):
# """Compute the indices corresponding to the edge of a distribution.
#
# The min and max indices are calculated according to a cutoff value (0.001 by default) meaning 99.99%
# of the distribution lies within this range.
#
# """
# total = np.sum(data)
# p = np.cumsum(data)
# nb_bins = data.shape[0]
#
# mini = 0.0
# maxi = 0.0
# for i in range(nb_bins):
# if p[i] > total * cut:
# mini = i
# if verbose:
# print('min = %f (i=%d)' % (mini, i))
# break
# for i in range(nb_bins):
# if total - p[nb_bins - 1 - i] > total * cut:
# maxi = nb_bins - 1 - i
# if verbose:
# print('max = %f (i=%d)' % (maxi, i))
# break
# return mini, maxi
#
# def auto_min_max(data, cut=0.0002, nb_bins=256, verbose=False):
# """Compute the min and max values in a numpy data array.
#
# The min and max values are calculated based on the histogram of the
# array which is limited at both ends by the cut parameter (0.0002 by
# default). This means 99.98% of the values are within the [min, max]
# range.
#
# :param data: the data array to analyse.
# :param float cut: the cut off value to use on the histogram (0.0002 by default).
# :param int nb_bins: number of bins to use in the histogram (256 by default).
# :param bool verbose: activate verbose mode (False by default).
# :returns tuple (val_mini, val_maxi): a tuple containing the min and max values.
# """
# n, bins = np.histogram(data, bins=nb_bins, density=False)
# mini, maxi = min_max_cumsum(n, cut=cut, verbose=verbose)
# val_mini, val_maxi = bins[mini], bins[maxi]
# return val_mini, val_maxi
. Output only the next line. | mini, maxi = min_max_cumsum(count, 0.005, verbose=True) |
Predict the next line after this snippet: <|code_start|>
class VolUtilsTests(unittest.TestCase):
def setUp(self):
print('testing the vol_utils module')
self.mu, self.sigma = 0, 0.2 # mean and standard deviation
np.random.seed(42)
self.data = np.random.normal(self.mu, self.sigma, 3000)
def test_min_max_cumsum(self):
count, bins = np.histogram(self.data, 30, range=(-3 * self.sigma, 3 * self.sigma), density=True)
bin_centers = 0.5 * (bins[:-1] + bins[1:])
mini, maxi = min_max_cumsum(count, 0.005, verbose=True)
self.assertEqual(mini, 2)
self.assertEqual(maxi, 26)
def test_auto_min_max(self):
image = misc.ascent().astype(np.float32)
<|code_end|>
using the current file's imports:
import unittest
import numpy as np
from pymicro.view.vol_utils import min_max_cumsum, auto_min_max
from scipy import misc
and any relevant context from other files:
# Path: pymicro/view/vol_utils.py
# def min_max_cumsum(data, cut=0.001, verbose=False):
# """Compute the indices corresponding to the edge of a distribution.
#
# The min and max indices are calculated according to a cutoff value (0.001 by default) meaning 99.99%
# of the distribution lies within this range.
#
# """
# total = np.sum(data)
# p = np.cumsum(data)
# nb_bins = data.shape[0]
#
# mini = 0.0
# maxi = 0.0
# for i in range(nb_bins):
# if p[i] > total * cut:
# mini = i
# if verbose:
# print('min = %f (i=%d)' % (mini, i))
# break
# for i in range(nb_bins):
# if total - p[nb_bins - 1 - i] > total * cut:
# maxi = nb_bins - 1 - i
# if verbose:
# print('max = %f (i=%d)' % (maxi, i))
# break
# return mini, maxi
#
# def auto_min_max(data, cut=0.0002, nb_bins=256, verbose=False):
# """Compute the min and max values in a numpy data array.
#
# The min and max values are calculated based on the histogram of the
# array which is limited at both ends by the cut parameter (0.0002 by
# default). This means 99.98% of the values are within the [min, max]
# range.
#
# :param data: the data array to analyse.
# :param float cut: the cut off value to use on the histogram (0.0002 by default).
# :param int nb_bins: number of bins to use in the histogram (256 by default).
# :param bool verbose: activate verbose mode (False by default).
# :returns tuple (val_mini, val_maxi): a tuple containing the min and max values.
# """
# n, bins = np.histogram(data, bins=nb_bins, density=False)
# mini, maxi = min_max_cumsum(n, cut=cut, verbose=verbose)
# val_mini, val_maxi = bins[mini], bins[maxi]
# return val_mini, val_maxi
. Output only the next line. | mini, maxi = auto_min_max(image, cut=0.001, nb_bins=256, verbose=False) |
Based on the snippet: <|code_start|> [0.0, 0.0, 1.0]])
R = np.array([[cos(angle), -sin(angle), 0.0],
[sin(angle), cos(angle), 0.0],
[0.0, 0.0, 1.0]])
T = np.array([[1.0, 0.0, tx],
[0.0, 1.0, ty],
[0.0, 0.0, 1.0]])
A = np.dot(T, np.dot(S, R))
print('full affine transform:\n{:s}'.format(A))
# transform the points
tsr_points = np.empty_like(ref_points)
for i in range(n):
p = np.dot(A, [ref_points[i, 0], ref_points[i, 1], 1])
tsr_points[i, 0] = p[0]
tsr_points[i, 1] = p[1]
# tsr_points[i] = T[:2] + np.dot(np.dot(S[:2, :2], R[:2, :2]), ref_points[i])
print(tsr_points[i])
plt.plot(tsr_points[i, 0], tsr_points[i, 1], 's', color=colors[i], markersize=10, markeredgecolor='none',
label='transformed points' if i == 0 else '')
# overwrite reference points in light gray
plt.plot(ref_points[:, 0], ref_points[:, 1], 'o', color=my_gray, markersize=10, markeredgecolor='none',
label='reference points' if i == 0 else '')
# draw dashed lines between reference and transformed points
for i in range(n):
plt.plot([ref_points[i, 0], tsr_points[i, 0]], [ref_points[i, 1], tsr_points[i, 1]], '--', color=colors[i])
plt.legend(numpoints=1)
plt.savefig('pointset_registration_2.png', format='png')
# compute the affine transform from the point set
<|code_end|>
, predict the immediate next line with the help of imports:
from math import pi, cos, sin
from matplotlib import pyplot as plt, colors as mcol
from pymicro.view.vol_utils import compute_affine_transform
import numpy as np
import random
and context (classes, functions, sometimes code) from other files:
# Path: pymicro/view/vol_utils.py
# def compute_affine_transform(fixed, moving):
# """Compute the affine transform by point set registration.
#
# The affine transform is the composition of a translation and a linear map.
# The two ordered lists of points must be of the same length larger or equal to 3.
# The order of the points in the two list must match.
#
# The 2D affine transform :math:`\mathbf{A}` has 6 parameters (2 for the translation and 4 for the linear transform).
# The best estimate of :math:`\mathbf{A}` can be computed using at least 3 pairs of matching points. Adding more
# pair of points will improve the quality of the estimate. The matching pairs are usually obtained by selecting
# unique features in both images and measuring their coordinates.
#
# :param list fixed: a list of the reference points.
# :param list moving: a list of the moving points to register on the fixed point.
# :returns translation, linear_map: the computed translation and linear map affine transform.
#
# Thanks to Will Lenthe for helping with this code.
# """
# assert len(fixed) == len(moving)
# assert len(fixed) >= 3
# fixed_centroid = np.average(fixed, 0)
# moving_centroid = np.average(moving, 0)
# # offset every point by the center of mass of all the points in the set
# fixed_from_centroid = fixed - fixed_centroid
# moving_from_centroid = moving - moving_centroid
# covariance = moving_from_centroid.T.dot(fixed_from_centroid)
# variance = moving_from_centroid.T.dot(moving_from_centroid)
# # compute the full affine transform: translation + linear map
# linear_map = np.linalg.inv(variance).dot(covariance).T
# translation = fixed_centroid - linear_map.dot(moving_centroid)
# return translation, linear_map
. Output only the next line. | translation, transformation = compute_affine_transform(ref_points, tsr_points) |
Given snippet: <|code_start|> this block.
* if `strict` is set, maximum name lengths will be enforced
* `maxoutlength` is the maximum length for output lines
* `wraplength` is the ideal length to make output lines
* When set, `overwrite` allows the values of datanames to be changed (otherwise an error
is raised).
* `compat_mode` will allow deprecated behaviour of creating single-dataname loops using
the syntax `a[_dataname] = [1,2,3,4]`. This should now be done by calling `CreateLoop`
after setting the dataitem value.
"""
if strict: maxnamelength=75
else:
maxnamelength=-1
super(CifBlock,self).__init__(data=data,maxnamelength=maxnamelength,**kwargs)
self.dictionary = None #DDL dictionary referring to this block
self.compat_mode = compat_mode #old-style behaviour of setitem
def RemoveCifItem(self,itemname):
"""Remove `itemname` from the CifBlock"""
self.RemoveItem(itemname)
def __setitem__(self,key,value):
self.AddItem(key,value)
# for backwards compatibility make a single-element loop
if self.compat_mode:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from cStringIO import StringIO
from io import StringIO
from urllib import urlopen # for arbitrary opening
from urlparse import urlparse, urljoin
from urllib.request import urlopen
from urllib.parse import urlparse, urljoin
from . import StarFile
from .StarFile import StarList #put in global scope for exec statement
from .drel import drel_runtime #put in global scope for exec statement
from copy import copy #must be in global scope for exec statement
from .drel import drel_ast_yacc
from .drel import py_from_ast
from .drel import drel_ast_yacc
from .drel import py_from_ast
from . import TypeContentsParser as t
import re,sys
import numpy #put in global scope for exec statement
import traceback
import numpy
and context:
# Path: pymicro/external/StarFile.py
# class StarList(list):
# def __getitem__(self,args):
# if isinstance(args,(int,slice)):
# return super(StarList,self).__getitem__(args)
# elif isinstance(args,tuple) and len(args)>1: #extended comma notation
# return super(StarList,self).__getitem__(args[0]).__getitem__(args[1:])
# else:
# return super(StarList,self).__getitem__(args[0])
#
# def __str__(self):
# return "SL("+super(StarList,self).__str__() + ")"
which might include code, classes, or functions. Output only the next line. | if isinstance(value,(tuple,list)) and not isinstance(value,StarFile.StarList): |
Given snippet: <|code_start|> vtkAnimation.__init__(self, t)
self.camera = cam
self.zoom = zoom
self.timer_end = t + 10
def execute(self, iren, event):
do = vtkAnimation.pre_execute(self)
if not do: return
t1 = self.time_anim_starts
t2 = self.time_anim_ends
z = 1 + (self.zoom - 1) * (self.scene.timer_count - t1) / float(t2 - t1)
if self.verbose:
print('zooming to', z)
self.camera.Zoom(z)
vtkAnimation.post_execute(self, iren, event)
class vtkSetVisibility(vtkAnimation):
def __init__(self, t, actor, visible=1, max_opacity=1, gradually=False):
vtkAnimation.__init__(self, t)
self.actor = actor
self.visible = visible
self.gradually = gradually
self.max_opacity = max_opacity
def execute(self, iren, event):
do = vtkAnimation.pre_execute(self)
if not do: return
if not self.gradually:
self.actor.SetVisibility(self.visible)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import vtk
import os
import numpy as np
from pymicro.view.vtk_utils import set_opacity
from pymicro.crystal.microstructure import Orientation
and context:
# Path: pymicro/view/vtk_utils.py
# def set_opacity(assembly, opacity):
# collection = vtk.vtkPropCollection()
# assembly.GetActors(collection)
# for i in range(collection.GetNumberOfItems()):
# collection.GetItemAsObject(i).GetProperty().SetOpacity(opacity)
which might include code, classes, or functions. Output only the next line. | set_opacity(self.actor, 1) |
Next line prediction: <|code_start|>
data_dir = '../../examples/data'
scan_name = 'mousse_250x250x250_uint8'
scan_path = os.path.join(data_dir, scan_name + '.raw')
<|code_end|>
. Use current file imports:
(from pymicro.file.file_utils import HST_read
from matplotlib import pyplot as plt, cm
import os, numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: pymicro/file/file_utils.py
# def HST_read(scan_name, zrange=None, data_type=np.uint8, verbose=False,
# header_size=0, autoparse_filename=False, dims=None, mmap=False, pack_binary=False):
# '''Read a volume file stored as a concatenated stack of binary images.
#
# The volume size must be specified by dims=(nx, ny, nz) unless an associated
# .info file is present in the same location to determine the volume
# size. The data type is unsigned short (8 bits) by default but can be set
# to any numpy type (32 bits float for example).
#
# The autoparse_filename can be activated to retreive image type and
# size:
# ::
#
# HST_read(myvol_100x200x50_uint16.raw, autoparse_filename=True)
#
# will read the 3d image as unsigned 16 bits with size 100 x 200 x 50.
#
# .. note::
#
# If you use this function to read a .edf file written by
# matlab in +y+x+z convention (column major order), you may want to
# use: np.swapaxes(HST_read('file.edf', ...), 0, 1)
#
# :param str scan_name: path to the binary file to read.
# :param zrange: range of slices to use.
# :param data_type: numpy data type to use.
# :param bool verbose: flag to activate verbose mode.
# :param int header_size: number of bytes to skeep before reading the payload.
# :param bool autoparse_filename: flag to parse the file name to retreive the dims and data_type automatically.
# :param tuple dims: a tuple containing the array dimensions.
# :param bool mmap: activate the memory mapping mode.
# :param bool pack_binary: this flag should be true when reading a file written with the binary packing mode.
# '''
# if autoparse_filename:
# s_type = scan_name[:-4].split('_')[-1]
# data_type = np.dtype(s_type)
# s_size = scan_name[:-4].split('_')[-2].split('x')
# dims = (int(s_size[0]), int(s_size[1]), int(s_size[2]))
# if verbose:
# print('auto parsing filename: data type is set to', data_type)
# if dims is None:
# infos = HST_info(scan_name + '.info')
# [nx, ny, nz] = [infos['x_dim'], infos['y_dim'], infos['z_dim']]
# if 'data_type' in infos:
# if infos['data_type'] == 'PACKED_BINARY':
# pack_binary = True
# data_type = np.uint8
# else:
# data_type = np.dtype(infos['data_type'].lower()) # overwrite defaults with .info file value
# else:
# (nx, ny, nz) = dims
# if zrange is None:
# zrange = range(0, nz)
# if verbose:
# print('data type is', data_type)
# print('volume size is %d x %d x %d' % (nx, ny, len(zrange)))
# if pack_binary:
# print('unpacking binary data from single bytes (8 values per byte)')
# if mmap:
# data = np.memmap(scan_name, dtype=data_type, mode='c', shape=(len(zrange), ny, nx))
# else:
# f = open(scan_name, 'rb')
# f.seek(header_size + np.dtype(data_type).itemsize * nx * ny * zrange[0])
# if verbose:
# print('reading volume... from byte %d' % f.tell())
# # read the payload
# payload = f.read(np.dtype(data_type).itemsize * len(zrange) * ny * nx)
# if pack_binary:
# data = np.unpackbits(np.fromstring(payload, data_type))[:len(zrange) * ny * nx]
# else:
# data = np.fromstring(payload, data_type)
# # convert the payload into actual 3D data
# data = np.reshape(data.astype(data_type), (len(zrange), ny, nx), order='C')
# f.close()
# # HP 10/2013 start using proper [x,y,z] data ordering
# data_xyz = data.transpose(2, 1, 0)
# return data_xyz
. Output only the next line. | vol = HST_read(scan_path, autoparse_filename=True, zrange=range(100, 101)) |
Here is a snippet: <|code_start|>from __future__ import print_function
#import sys
#from os import listdir
#from os.path import isfile, join
logger = logging.getLogger('explore')
def explore(args):
"""Create mapping of sequences of two clusters
"""
logger.info("Reading sequences")
<|code_end|>
. Write the next line using the current file imports:
import os
import logging
from seqcluster.libs.read import load_data, get_sequences_from_cluster, map_to_precursors, get_precursors_from_cluster
and context from other files:
# Path: seqcluster/libs/read.py
# def load_data(in_file):
# """load json file from seqcluster cluster"""
# with open(in_file) as in_handle:
# return json.load(in_handle)
#
# def get_sequences_from_cluster(c1, c2, data):
# """get all sequences from on cluster"""
# seqs1 = data[c1]['seqs']
# seqs2 = data[c2]['seqs']
# seqs = list(set(seqs1 + seqs2))
# names = []
# for s in seqs:
# if s in seqs1 and s in seqs2:
# names.append("both")
# elif s in seqs1:
# names.append(c1)
# else:
# names.append(c2)
# return seqs, names
#
# def map_to_precursors(seqs, names, loci, out_file, args):
# """map sequences to precursors with razers3"""
# with make_temp_directory() as temp:
# pre_fasta = os.path.join(temp, "pre.fa")
# seqs_fasta = os.path.join(temp, "seqs.fa")
# out_sam = os.path.join(temp, "out.sam")
# pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
# out_precursor_file = out_file.replace("tsv", "fa")
# seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)
#
# # print(open(pre_fasta).read().split("\n")[1])
# if find_cmd("razers3"):
# cmd = "razers3 -dr 2 -i 80 -rr 90 -f -o {out_sam} {temp}/pre.fa {seqs_fasta}"
# run(cmd.format(**locals()))
# out_file = read_alignment(out_sam, loci, seqs, out_file)
# shutil.copy(pre_fasta, out_precursor_file)
# return out_file
#
# def get_precursors_from_cluster(c1, c2, data):
# loci1 = data[c1]['loci']
# loci2 = data[c2]['loci']
# return {c1:loci1, c2:loci2}
, which may include functions, classes, or code. Output only the next line. | data = load_data(args.json) |
Continue the code snippet: <|code_start|>from __future__ import print_function
#import sys
#from os import listdir
#from os.path import isfile, join
logger = logging.getLogger('explore')
def explore(args):
"""Create mapping of sequences of two clusters
"""
logger.info("Reading sequences")
data = load_data(args.json)
logger.info("Get sequences from json")
#get_sequences_from_cluster()
c1, c2 = args.names.split(",")
<|code_end|>
. Use current file imports:
import os
import logging
from seqcluster.libs.read import load_data, get_sequences_from_cluster, map_to_precursors, get_precursors_from_cluster
and context (classes, functions, or code) from other files:
# Path: seqcluster/libs/read.py
# def load_data(in_file):
# """load json file from seqcluster cluster"""
# with open(in_file) as in_handle:
# return json.load(in_handle)
#
# def get_sequences_from_cluster(c1, c2, data):
# """get all sequences from on cluster"""
# seqs1 = data[c1]['seqs']
# seqs2 = data[c2]['seqs']
# seqs = list(set(seqs1 + seqs2))
# names = []
# for s in seqs:
# if s in seqs1 and s in seqs2:
# names.append("both")
# elif s in seqs1:
# names.append(c1)
# else:
# names.append(c2)
# return seqs, names
#
# def map_to_precursors(seqs, names, loci, out_file, args):
# """map sequences to precursors with razers3"""
# with make_temp_directory() as temp:
# pre_fasta = os.path.join(temp, "pre.fa")
# seqs_fasta = os.path.join(temp, "seqs.fa")
# out_sam = os.path.join(temp, "out.sam")
# pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
# out_precursor_file = out_file.replace("tsv", "fa")
# seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)
#
# # print(open(pre_fasta).read().split("\n")[1])
# if find_cmd("razers3"):
# cmd = "razers3 -dr 2 -i 80 -rr 90 -f -o {out_sam} {temp}/pre.fa {seqs_fasta}"
# run(cmd.format(**locals()))
# out_file = read_alignment(out_sam, loci, seqs, out_file)
# shutil.copy(pre_fasta, out_precursor_file)
# return out_file
#
# def get_precursors_from_cluster(c1, c2, data):
# loci1 = data[c1]['loci']
# loci2 = data[c2]['loci']
# return {c1:loci1, c2:loci2}
. Output only the next line. | seqs, names = get_sequences_from_cluster(c1, c2, data[0]) |
Continue the code snippet: <|code_start|>from __future__ import print_function
#import sys
#from os import listdir
#from os.path import isfile, join
logger = logging.getLogger('explore')
def explore(args):
"""Create mapping of sequences of two clusters
"""
logger.info("Reading sequences")
data = load_data(args.json)
logger.info("Get sequences from json")
#get_sequences_from_cluster()
c1, c2 = args.names.split(",")
seqs, names = get_sequences_from_cluster(c1, c2, data[0])
loci = get_precursors_from_cluster(c1, c2, data[0])
logger.info("Map all sequences to all loci")
print("%s" % (loci))
<|code_end|>
. Use current file imports:
import os
import logging
from seqcluster.libs.read import load_data, get_sequences_from_cluster, map_to_precursors, get_precursors_from_cluster
and context (classes, functions, or code) from other files:
# Path: seqcluster/libs/read.py
# def load_data(in_file):
# """load json file from seqcluster cluster"""
# with open(in_file) as in_handle:
# return json.load(in_handle)
#
# def get_sequences_from_cluster(c1, c2, data):
# """get all sequences from on cluster"""
# seqs1 = data[c1]['seqs']
# seqs2 = data[c2]['seqs']
# seqs = list(set(seqs1 + seqs2))
# names = []
# for s in seqs:
# if s in seqs1 and s in seqs2:
# names.append("both")
# elif s in seqs1:
# names.append(c1)
# else:
# names.append(c2)
# return seqs, names
#
# def map_to_precursors(seqs, names, loci, out_file, args):
# """map sequences to precursors with razers3"""
# with make_temp_directory() as temp:
# pre_fasta = os.path.join(temp, "pre.fa")
# seqs_fasta = os.path.join(temp, "seqs.fa")
# out_sam = os.path.join(temp, "out.sam")
# pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
# out_precursor_file = out_file.replace("tsv", "fa")
# seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)
#
# # print(open(pre_fasta).read().split("\n")[1])
# if find_cmd("razers3"):
# cmd = "razers3 -dr 2 -i 80 -rr 90 -f -o {out_sam} {temp}/pre.fa {seqs_fasta}"
# run(cmd.format(**locals()))
# out_file = read_alignment(out_sam, loci, seqs, out_file)
# shutil.copy(pre_fasta, out_precursor_file)
# return out_file
#
# def get_precursors_from_cluster(c1, c2, data):
# loci1 = data[c1]['loci']
# loci2 = data[c2]['loci']
# return {c1:loci1, c2:loci2}
. Output only the next line. | map_to_precursors(seqs, names, loci, os.path.join(args.out, "map.tsv"), args) |
Predict the next line for this snippet: <|code_start|>from __future__ import print_function
#import sys
#from os import listdir
#from os.path import isfile, join
logger = logging.getLogger('explore')
def explore(args):
"""Create mapping of sequences of two clusters
"""
logger.info("Reading sequences")
data = load_data(args.json)
logger.info("Get sequences from json")
#get_sequences_from_cluster()
c1, c2 = args.names.split(",")
seqs, names = get_sequences_from_cluster(c1, c2, data[0])
<|code_end|>
with the help of current file imports:
import os
import logging
from seqcluster.libs.read import load_data, get_sequences_from_cluster, map_to_precursors, get_precursors_from_cluster
and context from other files:
# Path: seqcluster/libs/read.py
# def load_data(in_file):
# """load json file from seqcluster cluster"""
# with open(in_file) as in_handle:
# return json.load(in_handle)
#
# def get_sequences_from_cluster(c1, c2, data):
# """get all sequences from on cluster"""
# seqs1 = data[c1]['seqs']
# seqs2 = data[c2]['seqs']
# seqs = list(set(seqs1 + seqs2))
# names = []
# for s in seqs:
# if s in seqs1 and s in seqs2:
# names.append("both")
# elif s in seqs1:
# names.append(c1)
# else:
# names.append(c2)
# return seqs, names
#
# def map_to_precursors(seqs, names, loci, out_file, args):
# """map sequences to precursors with razers3"""
# with make_temp_directory() as temp:
# pre_fasta = os.path.join(temp, "pre.fa")
# seqs_fasta = os.path.join(temp, "seqs.fa")
# out_sam = os.path.join(temp, "out.sam")
# pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
# out_precursor_file = out_file.replace("tsv", "fa")
# seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)
#
# # print(open(pre_fasta).read().split("\n")[1])
# if find_cmd("razers3"):
# cmd = "razers3 -dr 2 -i 80 -rr 90 -f -o {out_sam} {temp}/pre.fa {seqs_fasta}"
# run(cmd.format(**locals()))
# out_file = read_alignment(out_sam, loci, seqs, out_file)
# shutil.copy(pre_fasta, out_precursor_file)
# return out_file
#
# def get_precursors_from_cluster(c1, c2, data):
# loci1 = data[c1]['loci']
# loci2 = data[c2]['loci']
# return {c1:loci1, c2:loci2}
, which may contain function names, class names, or code. Output only the next line. | loci = get_precursors_from_cluster(c1, c2, data[0]) |
Based on the snippet: <|code_start|>
logger = logging.getLogger('predictions')
def predictions(args):
"""
Create predictions of clusters
"""
logger.info(args)
logger.info("Reading sequences")
out_file = os.path.abspath(os.path.splitext(args.json)[0] + "_prediction.json")
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import logging
from seqcluster.libs.read import load_data, write_data
from seqcluster.function.predictions import is_tRNA, run_coral
from seqcluster.libs.utils import safe_dirs
and context (classes, functions, sometimes code) from other files:
# Path: seqcluster/libs/read.py
# def load_data(in_file):
# """load json file from seqcluster cluster"""
# with open(in_file) as in_handle:
# return json.load(in_handle)
#
# def write_data(data, out_file):
# """write json file from seqcluster cluster"""
# with open(out_file, 'w') as handle_out:
# handle_out.write(json.dumps([data], skipkeys=True, indent=2))
#
# Path: seqcluster/function/predictions.py
# def is_tRNA(clus_obj, out_dir, args):
# """
# Iterates through cluster precursors to predict sRNA types
# """
# ref = os.path.abspath(args.reference)
# utils.safe_dirs(out_dir)
# for nc in clus_obj[0]:
# c = clus_obj[0][nc]
# loci = c['loci']
# out_fa = "cluster_" + nc
# if loci[0][3] - loci[0][2] < 500:
# with make_temp_directory() as tmpdir:
# os.chdir(tmpdir)
# get_loci_fasta({loci[0][0]: [loci[0][0:5]]}, out_fa, ref)
# summary_file, str_file = _run_tRNA_scan(out_fa)
# if "predictions" not in c:
# c['predictions'] = {}
# c['predictions']['tRNA'] = _read_tRNA_scan(summary_file)
# score = _read_tRNA_scan(summary_file)
# logger.debug(score)
# shutil.move(summary_file, op.join(out_dir, summary_file))
# shutil.move(str_file, op.join(out_dir, str_file))
# else:
# c['errors'].add("precursor too long")
# clus_obj[0][nc] = c
#
# return clus_obj
#
# def run_coral(clus_obj, out_dir, args):
# """
# Run some CoRaL modules to predict small RNA function
# """
# if not args.bed:
# raise ValueError("This module needs the bed file output from cluster subcmd.")
# workdir = op.abspath(op.join(args.out, 'coral'))
# safe_dirs(workdir)
# bam_in = op.abspath(args.bam)
# bed_in = op.abspath(args.bed)
# reference = op.abspath(args.ref)
# with chdir(workdir):
# bam_clean = coral.prepare_bam(bam_in, bed_in)
# out_dir = op.join(workdir, "regions")
# safe_dirs(out_dir)
# prefix = "seqcluster"
# loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)
# coral.create_features(bam_clean, loci_file, reference, out_dir)
#
# Path: seqcluster/libs/utils.py
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
. Output only the next line. | data = load_data(args.json) |
Given the code snippet: <|code_start|>
logger = logging.getLogger('predictions')
def predictions(args):
"""
Create predictions of clusters
"""
logger.info(args)
logger.info("Reading sequences")
out_file = os.path.abspath(os.path.splitext(args.json)[0] + "_prediction.json")
data = load_data(args.json)
out_dir = os.path.abspath(safe_dirs(os.path.join(args.out, "predictions")))
logger.info("Make predictions")
data = is_tRNA(data, out_dir, args)
if args.coral:
logger.info("Make CoRaL predictions")
run_coral(data, out_dir, args)
<|code_end|>
, generate the next line using the imports in this file:
import os
import logging
from seqcluster.libs.read import load_data, write_data
from seqcluster.function.predictions import is_tRNA, run_coral
from seqcluster.libs.utils import safe_dirs
and context (functions, classes, or occasionally code) from other files:
# Path: seqcluster/libs/read.py
# def load_data(in_file):
# """load json file from seqcluster cluster"""
# with open(in_file) as in_handle:
# return json.load(in_handle)
#
# def write_data(data, out_file):
# """write json file from seqcluster cluster"""
# with open(out_file, 'w') as handle_out:
# handle_out.write(json.dumps([data], skipkeys=True, indent=2))
#
# Path: seqcluster/function/predictions.py
# def is_tRNA(clus_obj, out_dir, args):
# """
# Iterates through cluster precursors to predict sRNA types
# """
# ref = os.path.abspath(args.reference)
# utils.safe_dirs(out_dir)
# for nc in clus_obj[0]:
# c = clus_obj[0][nc]
# loci = c['loci']
# out_fa = "cluster_" + nc
# if loci[0][3] - loci[0][2] < 500:
# with make_temp_directory() as tmpdir:
# os.chdir(tmpdir)
# get_loci_fasta({loci[0][0]: [loci[0][0:5]]}, out_fa, ref)
# summary_file, str_file = _run_tRNA_scan(out_fa)
# if "predictions" not in c:
# c['predictions'] = {}
# c['predictions']['tRNA'] = _read_tRNA_scan(summary_file)
# score = _read_tRNA_scan(summary_file)
# logger.debug(score)
# shutil.move(summary_file, op.join(out_dir, summary_file))
# shutil.move(str_file, op.join(out_dir, str_file))
# else:
# c['errors'].add("precursor too long")
# clus_obj[0][nc] = c
#
# return clus_obj
#
# def run_coral(clus_obj, out_dir, args):
# """
# Run some CoRaL modules to predict small RNA function
# """
# if not args.bed:
# raise ValueError("This module needs the bed file output from cluster subcmd.")
# workdir = op.abspath(op.join(args.out, 'coral'))
# safe_dirs(workdir)
# bam_in = op.abspath(args.bam)
# bed_in = op.abspath(args.bed)
# reference = op.abspath(args.ref)
# with chdir(workdir):
# bam_clean = coral.prepare_bam(bam_in, bed_in)
# out_dir = op.join(workdir, "regions")
# safe_dirs(out_dir)
# prefix = "seqcluster"
# loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)
# coral.create_features(bam_clean, loci_file, reference, out_dir)
#
# Path: seqcluster/libs/utils.py
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
. Output only the next line. | write_data(data[0], out_file) |
Given snippet: <|code_start|>
logger = logging.getLogger('predictions')
def predictions(args):
"""
Create predictions of clusters
"""
logger.info(args)
logger.info("Reading sequences")
out_file = os.path.abspath(os.path.splitext(args.json)[0] + "_prediction.json")
data = load_data(args.json)
out_dir = os.path.abspath(safe_dirs(os.path.join(args.out, "predictions")))
logger.info("Make predictions")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import logging
from seqcluster.libs.read import load_data, write_data
from seqcluster.function.predictions import is_tRNA, run_coral
from seqcluster.libs.utils import safe_dirs
and context:
# Path: seqcluster/libs/read.py
# def load_data(in_file):
# """load json file from seqcluster cluster"""
# with open(in_file) as in_handle:
# return json.load(in_handle)
#
# def write_data(data, out_file):
# """write json file from seqcluster cluster"""
# with open(out_file, 'w') as handle_out:
# handle_out.write(json.dumps([data], skipkeys=True, indent=2))
#
# Path: seqcluster/function/predictions.py
# def is_tRNA(clus_obj, out_dir, args):
# """
# Iterates through cluster precursors to predict sRNA types
# """
# ref = os.path.abspath(args.reference)
# utils.safe_dirs(out_dir)
# for nc in clus_obj[0]:
# c = clus_obj[0][nc]
# loci = c['loci']
# out_fa = "cluster_" + nc
# if loci[0][3] - loci[0][2] < 500:
# with make_temp_directory() as tmpdir:
# os.chdir(tmpdir)
# get_loci_fasta({loci[0][0]: [loci[0][0:5]]}, out_fa, ref)
# summary_file, str_file = _run_tRNA_scan(out_fa)
# if "predictions" not in c:
# c['predictions'] = {}
# c['predictions']['tRNA'] = _read_tRNA_scan(summary_file)
# score = _read_tRNA_scan(summary_file)
# logger.debug(score)
# shutil.move(summary_file, op.join(out_dir, summary_file))
# shutil.move(str_file, op.join(out_dir, str_file))
# else:
# c['errors'].add("precursor too long")
# clus_obj[0][nc] = c
#
# return clus_obj
#
# def run_coral(clus_obj, out_dir, args):
# """
# Run some CoRaL modules to predict small RNA function
# """
# if not args.bed:
# raise ValueError("This module needs the bed file output from cluster subcmd.")
# workdir = op.abspath(op.join(args.out, 'coral'))
# safe_dirs(workdir)
# bam_in = op.abspath(args.bam)
# bed_in = op.abspath(args.bed)
# reference = op.abspath(args.ref)
# with chdir(workdir):
# bam_clean = coral.prepare_bam(bam_in, bed_in)
# out_dir = op.join(workdir, "regions")
# safe_dirs(out_dir)
# prefix = "seqcluster"
# loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)
# coral.create_features(bam_clean, loci_file, reference, out_dir)
#
# Path: seqcluster/libs/utils.py
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
which might include code, classes, or functions. Output only the next line. | data = is_tRNA(data, out_dir, args) |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger('predictions')
def predictions(args):
"""
Create predictions of clusters
"""
logger.info(args)
logger.info("Reading sequences")
out_file = os.path.abspath(os.path.splitext(args.json)[0] + "_prediction.json")
data = load_data(args.json)
out_dir = os.path.abspath(safe_dirs(os.path.join(args.out, "predictions")))
logger.info("Make predictions")
data = is_tRNA(data, out_dir, args)
if args.coral:
logger.info("Make CoRaL predictions")
<|code_end|>
using the current file's imports:
import os
import logging
from seqcluster.libs.read import load_data, write_data
from seqcluster.function.predictions import is_tRNA, run_coral
from seqcluster.libs.utils import safe_dirs
and any relevant context from other files:
# Path: seqcluster/libs/read.py
# def load_data(in_file):
# """load json file from seqcluster cluster"""
# with open(in_file) as in_handle:
# return json.load(in_handle)
#
# def write_data(data, out_file):
# """write json file from seqcluster cluster"""
# with open(out_file, 'w') as handle_out:
# handle_out.write(json.dumps([data], skipkeys=True, indent=2))
#
# Path: seqcluster/function/predictions.py
# def is_tRNA(clus_obj, out_dir, args):
# """
# Iterates through cluster precursors to predict sRNA types
# """
# ref = os.path.abspath(args.reference)
# utils.safe_dirs(out_dir)
# for nc in clus_obj[0]:
# c = clus_obj[0][nc]
# loci = c['loci']
# out_fa = "cluster_" + nc
# if loci[0][3] - loci[0][2] < 500:
# with make_temp_directory() as tmpdir:
# os.chdir(tmpdir)
# get_loci_fasta({loci[0][0]: [loci[0][0:5]]}, out_fa, ref)
# summary_file, str_file = _run_tRNA_scan(out_fa)
# if "predictions" not in c:
# c['predictions'] = {}
# c['predictions']['tRNA'] = _read_tRNA_scan(summary_file)
# score = _read_tRNA_scan(summary_file)
# logger.debug(score)
# shutil.move(summary_file, op.join(out_dir, summary_file))
# shutil.move(str_file, op.join(out_dir, str_file))
# else:
# c['errors'].add("precursor too long")
# clus_obj[0][nc] = c
#
# return clus_obj
#
# def run_coral(clus_obj, out_dir, args):
# """
# Run some CoRaL modules to predict small RNA function
# """
# if not args.bed:
# raise ValueError("This module needs the bed file output from cluster subcmd.")
# workdir = op.abspath(op.join(args.out, 'coral'))
# safe_dirs(workdir)
# bam_in = op.abspath(args.bam)
# bed_in = op.abspath(args.bed)
# reference = op.abspath(args.ref)
# with chdir(workdir):
# bam_clean = coral.prepare_bam(bam_in, bed_in)
# out_dir = op.join(workdir, "regions")
# safe_dirs(out_dir)
# prefix = "seqcluster"
# loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)
# coral.create_features(bam_clean, loci_file, reference, out_dir)
#
# Path: seqcluster/libs/utils.py
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
. Output only the next line. | run_coral(data, out_dir, args) |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger('predictions')
def predictions(args):
"""
Create predictions of clusters
"""
logger.info(args)
logger.info("Reading sequences")
out_file = os.path.abspath(os.path.splitext(args.json)[0] + "_prediction.json")
data = load_data(args.json)
<|code_end|>
with the help of current file imports:
import os
import logging
from seqcluster.libs.read import load_data, write_data
from seqcluster.function.predictions import is_tRNA, run_coral
from seqcluster.libs.utils import safe_dirs
and context from other files:
# Path: seqcluster/libs/read.py
# def load_data(in_file):
# """load json file from seqcluster cluster"""
# with open(in_file) as in_handle:
# return json.load(in_handle)
#
# def write_data(data, out_file):
# """write json file from seqcluster cluster"""
# with open(out_file, 'w') as handle_out:
# handle_out.write(json.dumps([data], skipkeys=True, indent=2))
#
# Path: seqcluster/function/predictions.py
# def is_tRNA(clus_obj, out_dir, args):
# """
# Iterates through cluster precursors to predict sRNA types
# """
# ref = os.path.abspath(args.reference)
# utils.safe_dirs(out_dir)
# for nc in clus_obj[0]:
# c = clus_obj[0][nc]
# loci = c['loci']
# out_fa = "cluster_" + nc
# if loci[0][3] - loci[0][2] < 500:
# with make_temp_directory() as tmpdir:
# os.chdir(tmpdir)
# get_loci_fasta({loci[0][0]: [loci[0][0:5]]}, out_fa, ref)
# summary_file, str_file = _run_tRNA_scan(out_fa)
# if "predictions" not in c:
# c['predictions'] = {}
# c['predictions']['tRNA'] = _read_tRNA_scan(summary_file)
# score = _read_tRNA_scan(summary_file)
# logger.debug(score)
# shutil.move(summary_file, op.join(out_dir, summary_file))
# shutil.move(str_file, op.join(out_dir, str_file))
# else:
# c['errors'].add("precursor too long")
# clus_obj[0][nc] = c
#
# return clus_obj
#
# def run_coral(clus_obj, out_dir, args):
# """
# Run some CoRaL modules to predict small RNA function
# """
# if not args.bed:
# raise ValueError("This module needs the bed file output from cluster subcmd.")
# workdir = op.abspath(op.join(args.out, 'coral'))
# safe_dirs(workdir)
# bam_in = op.abspath(args.bam)
# bed_in = op.abspath(args.bed)
# reference = op.abspath(args.ref)
# with chdir(workdir):
# bam_clean = coral.prepare_bam(bam_in, bed_in)
# out_dir = op.join(workdir, "regions")
# safe_dirs(out_dir)
# prefix = "seqcluster"
# loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)
# coral.create_features(bam_clean, loci_file, reference, out_dir)
#
# Path: seqcluster/libs/utils.py
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
, which may contain function names, class names, or code. Output only the next line. | out_dir = os.path.abspath(safe_dirs(os.path.join(args.out, "predictions"))) |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger('seqbuster')
def collapse_fastq(args):
"""collapse fasq files after adapter trimming
"""
try:
umi_fn = args.fastq
if _is_umi(args.fastq):
<|code_end|>
with the help of current file imports:
import os
import logging
from seqcluster.libs.fastq import collapse, splitext_plus, write_output, open_fastq
and context from other files:
# Path: seqcluster/libs/fastq.py
# def collapse(in_file):
# """collapse identical sequences and keep Q"""
# keep = Counter()
# with open_fastq(in_file) as handle:
# line = handle.readline()
# while line:
# if line.startswith("@"):
# if line.find("UMI") > -1:
# logger.info("Find UMI tags in read names, collapsing by UMI.")
# return collapse_umi(in_file)
# seq = handle.readline().strip()
# handle.readline()
# qual = handle.readline().strip()
# if seq in keep:
# keep[seq].update(qual)
# else:
# keep[seq] = quality(qual)
# if line.startswith(">"):
# seq = handle.readline().strip()
# if seq not in keep:
# keep[seq] = quality("".join(["I"] * len(seq)))
# else:
# keep[seq].update("".join(["I"] * len(seq)))
# line = handle.readline()
# logger.info("Sequences loaded: %s" % len(keep))
# return keep
#
# def splitext_plus(f):
# """Split on file extensions, allowing for zipped extensions.
# copy from bcbio
# """
# base, ext = os.path.splitext(f)
# if ext in [".gz", ".bz2", ".zip"]:
# base, ext2 = os.path.splitext(base)
# ext = ext2 + ext
# return base, ext
#
# def write_output(out_file, seqs, minimum=1, size=15):
# idx =0
# logger.info("Writing %s sequences to %s" % (len(seqs.keys()), out_file))
# with open(out_file, 'w') as handle:
# for s in seqs:
# idx += 1
# if isinstance(seqs[s], list):
# seq = seqs[s][0].get()
# qual = "".join(seqs[s][1].get())
# counts = seqs[s][0].times
# else:
# seq = s
# qual = "".join(seqs[s].get())
# counts = seqs[s].times
# if int(counts) >= minimum and len(seq) > size:
# handle.write(("@seq_{idx}_x{counts}\n{seq}\n+\n{qual}\n").format(**locals()))
# return out_file
#
# def open_fastq(in_file):
# """ open a fastq file, using gzip if it is gzipped
# from bcbio package
# """
# _, ext = os.path.splitext(in_file)
# if ext == ".gz":
# return gzip.open(in_file, 'rt')
# if ext in [".fastq", ".fq", ".fasta", ".fa"]:
# return open(in_file, 'r')
# return ValueError("File needs to be fastq|fasta|fq|fa [.gz]")
, which may contain function names, class names, or code. Output only the next line. | umis = collapse(args.fastq) |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger('seqbuster')
def collapse_fastq(args):
"""collapse fasq files after adapter trimming
"""
try:
umi_fn = args.fastq
if _is_umi(args.fastq):
umis = collapse(args.fastq)
<|code_end|>
with the help of current file imports:
import os
import logging
from seqcluster.libs.fastq import collapse, splitext_plus, write_output, open_fastq
and context from other files:
# Path: seqcluster/libs/fastq.py
# def collapse(in_file):
# """collapse identical sequences and keep Q"""
# keep = Counter()
# with open_fastq(in_file) as handle:
# line = handle.readline()
# while line:
# if line.startswith("@"):
# if line.find("UMI") > -1:
# logger.info("Find UMI tags in read names, collapsing by UMI.")
# return collapse_umi(in_file)
# seq = handle.readline().strip()
# handle.readline()
# qual = handle.readline().strip()
# if seq in keep:
# keep[seq].update(qual)
# else:
# keep[seq] = quality(qual)
# if line.startswith(">"):
# seq = handle.readline().strip()
# if seq not in keep:
# keep[seq] = quality("".join(["I"] * len(seq)))
# else:
# keep[seq].update("".join(["I"] * len(seq)))
# line = handle.readline()
# logger.info("Sequences loaded: %s" % len(keep))
# return keep
#
# def splitext_plus(f):
# """Split on file extensions, allowing for zipped extensions.
# copy from bcbio
# """
# base, ext = os.path.splitext(f)
# if ext in [".gz", ".bz2", ".zip"]:
# base, ext2 = os.path.splitext(base)
# ext = ext2 + ext
# return base, ext
#
# def write_output(out_file, seqs, minimum=1, size=15):
# idx =0
# logger.info("Writing %s sequences to %s" % (len(seqs.keys()), out_file))
# with open(out_file, 'w') as handle:
# for s in seqs:
# idx += 1
# if isinstance(seqs[s], list):
# seq = seqs[s][0].get()
# qual = "".join(seqs[s][1].get())
# counts = seqs[s][0].times
# else:
# seq = s
# qual = "".join(seqs[s].get())
# counts = seqs[s].times
# if int(counts) >= minimum and len(seq) > size:
# handle.write(("@seq_{idx}_x{counts}\n{seq}\n+\n{qual}\n").format(**locals()))
# return out_file
#
# def open_fastq(in_file):
# """ open a fastq file, using gzip if it is gzipped
# from bcbio package
# """
# _, ext = os.path.splitext(in_file)
# if ext == ".gz":
# return gzip.open(in_file, 'rt')
# if ext in [".fastq", ".fq", ".fasta", ".fa"]:
# return open(in_file, 'r')
# return ValueError("File needs to be fastq|fasta|fq|fa [.gz]")
, which may contain function names, class names, or code. Output only the next line. | umi_fn = os.path.join(args.out, splitext_plus(os.path.basename(args.fastq))[0] + "_umi_trimmed.fastq") |
Continue the code snippet: <|code_start|>
logger = logging.getLogger('seqbuster')
def collapse_fastq(args):
"""collapse fasq files after adapter trimming
"""
try:
umi_fn = args.fastq
if _is_umi(args.fastq):
umis = collapse(args.fastq)
umi_fn = os.path.join(args.out, splitext_plus(os.path.basename(args.fastq))[0] + "_umi_trimmed.fastq")
<|code_end|>
. Use current file imports:
import os
import logging
from seqcluster.libs.fastq import collapse, splitext_plus, write_output, open_fastq
and context (classes, functions, or code) from other files:
# Path: seqcluster/libs/fastq.py
# def collapse(in_file):
# """collapse identical sequences and keep Q"""
# keep = Counter()
# with open_fastq(in_file) as handle:
# line = handle.readline()
# while line:
# if line.startswith("@"):
# if line.find("UMI") > -1:
# logger.info("Find UMI tags in read names, collapsing by UMI.")
# return collapse_umi(in_file)
# seq = handle.readline().strip()
# handle.readline()
# qual = handle.readline().strip()
# if seq in keep:
# keep[seq].update(qual)
# else:
# keep[seq] = quality(qual)
# if line.startswith(">"):
# seq = handle.readline().strip()
# if seq not in keep:
# keep[seq] = quality("".join(["I"] * len(seq)))
# else:
# keep[seq].update("".join(["I"] * len(seq)))
# line = handle.readline()
# logger.info("Sequences loaded: %s" % len(keep))
# return keep
#
# def splitext_plus(f):
# """Split on file extensions, allowing for zipped extensions.
# copy from bcbio
# """
# base, ext = os.path.splitext(f)
# if ext in [".gz", ".bz2", ".zip"]:
# base, ext2 = os.path.splitext(base)
# ext = ext2 + ext
# return base, ext
#
# def write_output(out_file, seqs, minimum=1, size=15):
# idx =0
# logger.info("Writing %s sequences to %s" % (len(seqs.keys()), out_file))
# with open(out_file, 'w') as handle:
# for s in seqs:
# idx += 1
# if isinstance(seqs[s], list):
# seq = seqs[s][0].get()
# qual = "".join(seqs[s][1].get())
# counts = seqs[s][0].times
# else:
# seq = s
# qual = "".join(seqs[s].get())
# counts = seqs[s].times
# if int(counts) >= minimum and len(seq) > size:
# handle.write(("@seq_{idx}_x{counts}\n{seq}\n+\n{qual}\n").format(**locals()))
# return out_file
#
# def open_fastq(in_file):
# """ open a fastq file, using gzip if it is gzipped
# from bcbio package
# """
# _, ext = os.path.splitext(in_file)
# if ext == ".gz":
# return gzip.open(in_file, 'rt')
# if ext in [".fastq", ".fq", ".fasta", ".fa"]:
# return open(in_file, 'r')
# return ValueError("File needs to be fastq|fasta|fq|fa [.gz]")
. Output only the next line. | write_output(umi_fn, umis, args.minimum) |
Given the code snippet: <|code_start|>
logger = logging.getLogger('seqbuster')
def collapse_fastq(args):
"""collapse fasq files after adapter trimming
"""
try:
umi_fn = args.fastq
if _is_umi(args.fastq):
umis = collapse(args.fastq)
umi_fn = os.path.join(args.out, splitext_plus(os.path.basename(args.fastq))[0] + "_umi_trimmed.fastq")
write_output(umi_fn, umis, args.minimum)
seqs = collapse(umi_fn)
out_file = splitext_plus(os.path.basename(args.fastq))[0] + "_trimmed.fastq"
except IOError as e:
logger.error("I/O error({0}): {1}".format(e.errno, e.strerror))
raise "Can not read file"
out_file = os.path.join(args.out, out_file)
write_output(out_file, seqs, args.minimum)
return out_file
def _is_umi(fn):
<|code_end|>
, generate the next line using the imports in this file:
import os
import logging
from seqcluster.libs.fastq import collapse, splitext_plus, write_output, open_fastq
and context (functions, classes, or occasionally code) from other files:
# Path: seqcluster/libs/fastq.py
# def collapse(in_file):
# """collapse identical sequences and keep Q"""
# keep = Counter()
# with open_fastq(in_file) as handle:
# line = handle.readline()
# while line:
# if line.startswith("@"):
# if line.find("UMI") > -1:
# logger.info("Find UMI tags in read names, collapsing by UMI.")
# return collapse_umi(in_file)
# seq = handle.readline().strip()
# handle.readline()
# qual = handle.readline().strip()
# if seq in keep:
# keep[seq].update(qual)
# else:
# keep[seq] = quality(qual)
# if line.startswith(">"):
# seq = handle.readline().strip()
# if seq not in keep:
# keep[seq] = quality("".join(["I"] * len(seq)))
# else:
# keep[seq].update("".join(["I"] * len(seq)))
# line = handle.readline()
# logger.info("Sequences loaded: %s" % len(keep))
# return keep
#
# def splitext_plus(f):
# """Split on file extensions, allowing for zipped extensions.
# copy from bcbio
# """
# base, ext = os.path.splitext(f)
# if ext in [".gz", ".bz2", ".zip"]:
# base, ext2 = os.path.splitext(base)
# ext = ext2 + ext
# return base, ext
#
# def write_output(out_file, seqs, minimum=1, size=15):
# idx =0
# logger.info("Writing %s sequences to %s" % (len(seqs.keys()), out_file))
# with open(out_file, 'w') as handle:
# for s in seqs:
# idx += 1
# if isinstance(seqs[s], list):
# seq = seqs[s][0].get()
# qual = "".join(seqs[s][1].get())
# counts = seqs[s][0].times
# else:
# seq = s
# qual = "".join(seqs[s].get())
# counts = seqs[s].times
# if int(counts) >= minimum and len(seq) > size:
# handle.write(("@seq_{idx}_x{counts}\n{seq}\n+\n{qual}\n").format(**locals()))
# return out_file
#
# def open_fastq(in_file):
# """ open a fastq file, using gzip if it is gzipped
# from bcbio package
# """
# _, ext = os.path.splitext(in_file)
# if ext == ".gz":
# return gzip.open(in_file, 'rt')
# if ext in [".fastq", ".fq", ".fasta", ".fa"]:
# return open(in_file, 'r')
# return ValueError("File needs to be fastq|fasta|fq|fa [.gz]")
. Output only the next line. | with open_fastq(fn) as inh: |
Based on the snippet: <|code_start|> p = random.uniform(0, 0.1)
counts = int(p * total) + 1
seen += counts
name = "seq_%s_%s_%s_x%s" % (c, s, e, counts)
reads[name] = (seq[s:e], counts)
return reads
def _write_reads(reads, prefix):
"""
Write fasta file, ma file and real position
"""
out_ma = prefix + ".ma"
out_fasta = prefix + ".fasta"
out_real = prefix + ".txt"
with open(out_ma, 'w') as ma_handle:
print("id\tseq\tsample", file=ma_handle, end="")
with open(out_fasta, 'w') as fa_handle:
with open(out_real, 'w') as read_handle:
for idx, r in enumerate(reads):
info = r.split("_")
print("seq_%s\t%s\t%s" % (idx, reads[r][0], reads[r][1]), file=ma_handle, end="")
print(">seq_%s\n%s" % (idx, reads[r][0]), file=fa_handle, end="")
print("%s\t%s\t%s\t%s\t%s\t%s\t%s" % (idx, r, reads[r][0], reads[r][1], info[1], info[2], info[3]), file=read_handle, end="")
def _get_precursor(bed_file, reference, out_fa):
"""
get sequence precursor from position
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import random
from seqcluster.libs.read import get_fasta
and context (classes, functions, sometimes code) from other files:
# Path: seqcluster/libs/read.py
# def get_fasta(bed_file, ref, out_fa):
# """Run bedtools to get fasta from bed file"""
# cmd = "bedtools getfasta -s -fi {ref} -bed {bed_file} -fo {out_fa}"
# run(cmd.format(**locals()))
. Output only the next line. | get_fasta(bed_file, reference, out_fa) |
Given the following code snippet before the placeholder: <|code_start|>def anncluster(c, clus_obj, db, type_ann, feature_id="name"):
"""intersect transcription position with annotation files"""
id_sa, id_ea, id_id, id_idl, id_sta = 1, 2, 3, 4, 5
if type_ann == "bed":
id_sb = 7
id_eb = 8
id_stb = 11
id_tag = 9
ida = 0
clus_id = clus_obj.clus
loci_id = clus_obj.loci
db = os.path.splitext(db)[0]
logger.debug("Type:%s\n" % type_ann)
for cols in c.features():
if type_ann == "gtf":
cb, sb, eb, stb, db, tag = read_gtf_line(cols[6:], feature_id)
else:
sb = int(cols[id_sb])
eb = int(cols[id_eb])
stb = cols[id_stb]
tag = cols[id_tag]
id = int(cols[id_id])
idl = int(cols[id_idl])
if (id in clus_id):
clus = clus_id[id]
sa = int(cols[id_sa])
ea = int(cols[id_ea])
ida += 1
lento5, lento3, strd = _position_in_feature([sa, ea, cols[id_sta]], [sb, eb, stb])
if db in loci_id[idl].db_ann:
<|code_end|>
, predict the next line using imports from the current file:
import seqcluster.libs.logger as mylog
import os
from seqcluster.libs.classes import annotation, dbannotation
and context including class names, function names, and sometimes code from other files:
# Path: seqcluster/libs/classes.py
# class annotation:
# """
# Object with information about annotation: database, name of the feature, strand,
# distance to 5' end, distance to 3' end
# """
# def __init__(self,db,name,strand,to5,to3):
# self.db = db
# self.name = name
# self.strand = strand
# self.to5 = to5
# self.to3 = to3
#
# class dbannotation:
# """
# Object with information about annotation: containg one dict that
# store all features for each database type
# """
# def __init__(self,na):
# self.ann = {}
# def add_db_ann(self,ida,ndba):
# self.ann[ida] = ndba
. Output only the next line. | ann = annotation(db, tag, strd, lento5, lento3) |
Given the following code snippet before the placeholder: <|code_start|> id_stb = 11
id_tag = 9
ida = 0
clus_id = clus_obj.clus
loci_id = clus_obj.loci
db = os.path.splitext(db)[0]
logger.debug("Type:%s\n" % type_ann)
for cols in c.features():
if type_ann == "gtf":
cb, sb, eb, stb, db, tag = read_gtf_line(cols[6:], feature_id)
else:
sb = int(cols[id_sb])
eb = int(cols[id_eb])
stb = cols[id_stb]
tag = cols[id_tag]
id = int(cols[id_id])
idl = int(cols[id_idl])
if (id in clus_id):
clus = clus_id[id]
sa = int(cols[id_sa])
ea = int(cols[id_ea])
ida += 1
lento5, lento3, strd = _position_in_feature([sa, ea, cols[id_sta]], [sb, eb, stb])
if db in loci_id[idl].db_ann:
ann = annotation(db, tag, strd, lento5, lento3)
tdb = loci_id[idl].db_ann[db]
tdb.add_db_ann(ida, ann)
loci_id[idl].add_db(db, tdb)
else:
ann = annotation(db, tag, strd, lento5, lento3)
<|code_end|>
, predict the next line using imports from the current file:
import seqcluster.libs.logger as mylog
import os
from seqcluster.libs.classes import annotation, dbannotation
and context including class names, function names, and sometimes code from other files:
# Path: seqcluster/libs/classes.py
# class annotation:
# """
# Object with information about annotation: database, name of the feature, strand,
# distance to 5' end, distance to 3' end
# """
# def __init__(self,db,name,strand,to5,to3):
# self.db = db
# self.name = name
# self.strand = strand
# self.to5 = to5
# self.to3 = to3
#
# class dbannotation:
# """
# Object with information about annotation: containg one dict that
# store all features for each database type
# """
# def __init__(self,na):
# self.ann = {}
# def add_db_ann(self,ida,ndba):
# self.ann[ida] = ndba
. Output only the next line. | tdb = dbannotation(1) |
Given the following code snippet before the placeholder: <|code_start|>"""prepare data for CoRaL"""
from __future__ import print_function
min_trimmed_read_len = 14
max_trimmed_read_len = 50
seg_threshold = 2
seg_maxgap = 44
seg_minrun = min_trimmed_read_len
antisense_min_reads = 0
def prepare_bam(bam_in, precursors):
"""
Clean BAM file to keep only position inside the bigger cluster
"""
# use pybedtools to keep valid positions
# intersect option with -b bigger_cluster_loci
a = pybedtools.BedTool(bam_in)
b = pybedtools.BedTool(precursors)
c = a.intersect(b, u=True)
<|code_end|>
, predict the next line using imports from the current file:
import os.path as op
import pybedtools
from collections import Counter
from seqcluster.libs import utils
from seqcluster.libs.do import run, find_cmd
from seqcluster.function.rnafold import calculate_structure
and context including class names, function names, and sometimes code from other files:
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
#
# def find_cmd(cmd):
# try:
# return subprocess.check_output(["which", cmd]).strip()
# except subprocess.CalledProcessError:
# return None
#
# Path: seqcluster/function/rnafold.py
# def calculate_structure(loci_file):
# structure_file = os.path.splitext(loci_file)[0] + "-fold.tsv"
# loci_bed = pybedtools.BedTool(loci_file)
# # getfasta with reference fasta
# # for line: get fasta -> run_rnafold -> add value to out_file
# return structure_file
. Output only the next line. | out_file = utils.splitext_plus(op.basename(bam_in))[0] + "_clean.bam" |
Here is a snippet: <|code_start|> cols[3] = _select_anno(cols[3]) + "_" + cols[4]
cols[4] = "0"
print("\t".join(cols), file=out_handle, end="")
return new_bed
def _fix_score_column(cov_file):
"""
Move counts to score columns in bed file
"""
new_cov = utils.splitext_plus(cov_file)[0] + '_fix.cov'
with open(cov_file) as in_handle:
with open(new_cov, 'w') as out_handle:
for line in in_handle:
cols = line.strip().split("\t")
cols[4] = cols[6]
print("\t".join(cols[0:6]), file=out_handle, end="")
return new_cov
def detect_regions(bam_in, bed_file, out_dir, prefix):
"""
Detect regions using first CoRaL module
"""
bed_file = _reorder_columns(bed_file)
counts_reads_cmd = ("coverageBed -s -counts -b {bam_in} "
"-a {bed_file} | sort -k4,4 "
"> {out_dir}/loci.cov")
# with tx_tmpdir() as temp_dir:
with utils.chdir(out_dir):
<|code_end|>
. Write the next line using the current file imports:
import os.path as op
import pybedtools
from collections import Counter
from seqcluster.libs import utils
from seqcluster.libs.do import run, find_cmd
from seqcluster.function.rnafold import calculate_structure
and context from other files:
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
#
# def find_cmd(cmd):
# try:
# return subprocess.check_output(["which", cmd]).strip()
# except subprocess.CalledProcessError:
# return None
#
# Path: seqcluster/function/rnafold.py
# def calculate_structure(loci_file):
# structure_file = os.path.splitext(loci_file)[0] + "-fold.tsv"
# loci_bed = pybedtools.BedTool(loci_file)
# # getfasta with reference fasta
# # for line: get fasta -> run_rnafold -> add value to out_file
# return structure_file
, which may include functions, classes, or code. Output only the next line. | run(counts_reads_cmd.format(min_trimmed_read_len=min_trimmed_read_len, max_trimmed_read_len=max_trimmed_read_len, **locals()), "Run counts_reads") |
Given snippet: <|code_start|> "{max_len} ")
index_genomic_cmd = ("index_genomic_lenvectors "
"{lenvec} ")
genomic_lenvec = op.join(out_dir, 'genomic_lenvec')
feat_len_file = op.join(out_dir, 'feat_lengths.txt')
compute_locus_cmd = ("compute_locus_lenvectors "
"{loci_file} "
"{genomic_lenvec} "
"{min_len} "
"{max_len} "
"> {feat_len_file}")
cov_S_file = op.join(out_dir, 'loci.cov_anti')
coverage_anti_cmd = ("coverageBed -S -counts -b "
"{bam_in} -a {loci_file} "
"> {cov_S_file}")
feat_posentropy = op.join(out_dir, 'feat_posentropy.txt')
entropy_cmd = ("compute_locus_entropy.rb "
"{counts_reads} "
"> {feat_posentropy}")
with utils.chdir(out_dir):
run(compute_genomic_cmd.format(min_len=min_trimmed_read_len, max_len=max_trimmed_read_len, **locals()), "Run compute_genomic")
run(index_genomic_cmd.format(lenvec=lenvec_plus), "Run index in plus")
run(index_genomic_cmd.format(lenvec=lenvec_minus), "Run index in minus")
run(compute_locus_cmd.format(min_len=min_trimmed_read_len, max_len=max_trimmed_read_len, **locals()), "Run compute locus")
run(coverage_anti_cmd.format(**locals()), "Run coverage antisense")
feat_antisense = _order_antisense_column(cov_S_file, min_trimmed_read_len)
counts_reads = _reads_per_position(bam_in, loci_file, out_dir)
run(entropy_cmd.format(**locals()), "Run entropy")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os.path as op
import pybedtools
from collections import Counter
from seqcluster.libs import utils
from seqcluster.libs.do import run, find_cmd
from seqcluster.function.rnafold import calculate_structure
and context:
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
#
# def find_cmd(cmd):
# try:
# return subprocess.check_output(["which", cmd]).strip()
# except subprocess.CalledProcessError:
# return None
#
# Path: seqcluster/function/rnafold.py
# def calculate_structure(loci_file):
# structure_file = os.path.splitext(loci_file)[0] + "-fold.tsv"
# loci_bed = pybedtools.BedTool(loci_file)
# # getfasta with reference fasta
# # for line: get fasta -> run_rnafold -> add value to out_file
# return structure_file
which might include code, classes, or functions. Output only the next line. | rnafold = calculate_structure(loci_file, reference) |
Here is a snippet: <|code_start|>def _read_fasta_files(f, args):
""" read fasta files of each sample and generate a seq_obj
with the information of each unique sequence in each sample
:param f: file containing the path for each fasta file and
the name of the sample. Two column format with `tab` as field
separator
:returns: * :code:`seq_l`: is a list of seq_obj objects, containing
the information of each sequence
* :code:`sample_l`: is a list with the name of the samples
(column two of the config file)
"""
seq_l = {}
sample_l = []
idx = 1
for line1 in f:
line1 = line1.strip()
cols = line1.split("\t")
with open(cols[0], 'r') as fasta:
sample_l.append(cols[1])
for line in fasta:
if line.startswith(">"):
idx += 1
counts = int(re.search("x([0-9]+)", line.strip()).group(1))
else:
seq = line.strip()
seq = seq[0:int(args.maxl)] if len(seq) > int(args.maxl) else seq
if counts > int(args.minc) and len(seq) > int(args.minl):
if seq not in seq_l:
<|code_end|>
. Write the next line using the current file imports:
import os
import os.path as op
import traceback
import re
import logging
from seqcluster.libs.classes import sequence_unique
from seqcluster.libs.classes import quality
from seqcluster.libs.fastq import is_fastq, open_fastq
and context from other files:
# Path: seqcluster/libs/classes.py
# class sequence_unique:
# """
# Object to store the sequence information like: **counts**, **sequence**, **id**
# """
# def __init__(self, idx, seq):
# self.idx = idx
# self.seq = seq
# self.group = {}
# self.quality = ""
# self.total = 0
# def add_exp(self,gr,exp):
# """Function to add the counts for each sample
#
# :param gr: name of the sample
# :param exp: counts of sample **gr**
#
# :returns: dict with key,values equally to name,counts.
# """
# self.group[gr] = exp
# self.total = sum(self.group.values())
#
# Path: seqcluster/libs/classes.py
# class quality:
#
# def __init__(self, q):
# self.qual = [ord(value) for value in q]
# self.times = 1
#
# def update(self, q, counts = 1):
# now = self.qual
# q = [ord(value) for value in q]
# self.qual = [x + y for x, y in zip(now, q)]
# self.times += counts
#
# def get(self):
# average = np.array(self.qual)/self.times
# return [str(unichr(int(char))) for char in average]
#
# Path: seqcluster/libs/fastq.py
# def is_fastq(in_file):
# """copy from bcbio package"""
# fastq_ends = [".txt", ".fq", ".fastq"]
# zip_ends = [".gzip", ".gz"]
# base, first_ext = os.path.splitext(in_file)
# second_ext = os.path.splitext(base)[1]
# if first_ext in fastq_ends:
# return True
# elif (second_ext, first_ext) in product(fastq_ends, zip_ends):
# return True
# else:
# return False
#
# def open_fastq(in_file):
# """ open a fastq file, using gzip if it is gzipped
# from bcbio package
# """
# _, ext = os.path.splitext(in_file)
# if ext == ".gz":
# return gzip.open(in_file, 'rt')
# if ext in [".fastq", ".fq", ".fasta", ".fa"]:
# return open(in_file, 'r')
# return ValueError("File needs to be fastq|fasta|fq|fa [.gz]")
, which may include functions, classes, or code. Output only the next line. | seq_l[seq] = sequence_unique(idx, seq) |
Next line prediction: <|code_start|> for line1 in f:
line1 = line1.strip()
cols = line1.split("\t")
# if not is_fastq(cols[0]):
# raise ValueError("file is not fastq: %s" % cols[0])
with open_fastq(cols[0]) as handle:
sample_l.append(cols[1])
total = added = 0
line = handle.readline()
while line:
if line.startswith("@") or line.startswith(">"):
seq = handle.readline().strip()
if not p.match(seq):
continue
idx += 1
total += 1
keep = {}
counts = int(re.search("x([0-9]+)", line.strip()).group(1))
if is_fastq(cols[0]):
handle.readline().strip()
qual = handle.readline().strip()
else:
qual = "I" * len(seq)
qual = qual[0:int(args.maxl)] if len(qual) > int(args.maxl) else qual
seq = seq[0:int(args.maxl)] if len(seq) > int(args.maxl) else seq
if counts > int(args.minc) and len(seq) > int(args.minl):
added += 1
if seq in keep:
keep[seq].update(qual)
else:
<|code_end|>
. Use current file imports:
(import os
import os.path as op
import traceback
import re
import logging
from seqcluster.libs.classes import sequence_unique
from seqcluster.libs.classes import quality
from seqcluster.libs.fastq import is_fastq, open_fastq)
and context including class names, function names, or small code snippets from other files:
# Path: seqcluster/libs/classes.py
# class sequence_unique:
# """
# Object to store the sequence information like: **counts**, **sequence**, **id**
# """
# def __init__(self, idx, seq):
# self.idx = idx
# self.seq = seq
# self.group = {}
# self.quality = ""
# self.total = 0
# def add_exp(self,gr,exp):
# """Function to add the counts for each sample
#
# :param gr: name of the sample
# :param exp: counts of sample **gr**
#
# :returns: dict with key,values equally to name,counts.
# """
# self.group[gr] = exp
# self.total = sum(self.group.values())
#
# Path: seqcluster/libs/classes.py
# class quality:
#
# def __init__(self, q):
# self.qual = [ord(value) for value in q]
# self.times = 1
#
# def update(self, q, counts = 1):
# now = self.qual
# q = [ord(value) for value in q]
# self.qual = [x + y for x, y in zip(now, q)]
# self.times += counts
#
# def get(self):
# average = np.array(self.qual)/self.times
# return [str(unichr(int(char))) for char in average]
#
# Path: seqcluster/libs/fastq.py
# def is_fastq(in_file):
# """copy from bcbio package"""
# fastq_ends = [".txt", ".fq", ".fastq"]
# zip_ends = [".gzip", ".gz"]
# base, first_ext = os.path.splitext(in_file)
# second_ext = os.path.splitext(base)[1]
# if first_ext in fastq_ends:
# return True
# elif (second_ext, first_ext) in product(fastq_ends, zip_ends):
# return True
# else:
# return False
#
# def open_fastq(in_file):
# """ open a fastq file, using gzip if it is gzipped
# from bcbio package
# """
# _, ext = os.path.splitext(in_file)
# if ext == ".gz":
# return gzip.open(in_file, 'rt')
# if ext in [".fastq", ".fq", ".fasta", ".fa"]:
# return open(in_file, 'r')
# return ValueError("File needs to be fastq|fasta|fq|fa [.gz]")
. Output only the next line. | keep[seq] = quality(qual) |
Predict the next line after this snippet: <|code_start|> separator
:returns: * :code:`seq_l`: is a list of seq_obj objects, containing
the information of each sequence
* :code:`sample_l`: is a list with the name of the samples
(column two of the config file)
"""
seq_l = {}
sample_l = []
idx = 1
p = re.compile("^[ATCGNU]+$")
with open(op.join(args.out, "stats_prepare.tsv"), 'w') as out_handle:
for line1 in f:
line1 = line1.strip()
cols = line1.split("\t")
# if not is_fastq(cols[0]):
# raise ValueError("file is not fastq: %s" % cols[0])
with open_fastq(cols[0]) as handle:
sample_l.append(cols[1])
total = added = 0
line = handle.readline()
while line:
if line.startswith("@") or line.startswith(">"):
seq = handle.readline().strip()
if not p.match(seq):
continue
idx += 1
total += 1
keep = {}
counts = int(re.search("x([0-9]+)", line.strip()).group(1))
<|code_end|>
using the current file's imports:
import os
import os.path as op
import traceback
import re
import logging
from seqcluster.libs.classes import sequence_unique
from seqcluster.libs.classes import quality
from seqcluster.libs.fastq import is_fastq, open_fastq
and any relevant context from other files:
# Path: seqcluster/libs/classes.py
# class sequence_unique:
# """
# Object to store the sequence information like: **counts**, **sequence**, **id**
# """
# def __init__(self, idx, seq):
# self.idx = idx
# self.seq = seq
# self.group = {}
# self.quality = ""
# self.total = 0
# def add_exp(self,gr,exp):
# """Function to add the counts for each sample
#
# :param gr: name of the sample
# :param exp: counts of sample **gr**
#
# :returns: dict with key,values equally to name,counts.
# """
# self.group[gr] = exp
# self.total = sum(self.group.values())
#
# Path: seqcluster/libs/classes.py
# class quality:
#
# def __init__(self, q):
# self.qual = [ord(value) for value in q]
# self.times = 1
#
# def update(self, q, counts = 1):
# now = self.qual
# q = [ord(value) for value in q]
# self.qual = [x + y for x, y in zip(now, q)]
# self.times += counts
#
# def get(self):
# average = np.array(self.qual)/self.times
# return [str(unichr(int(char))) for char in average]
#
# Path: seqcluster/libs/fastq.py
# def is_fastq(in_file):
# """copy from bcbio package"""
# fastq_ends = [".txt", ".fq", ".fastq"]
# zip_ends = [".gzip", ".gz"]
# base, first_ext = os.path.splitext(in_file)
# second_ext = os.path.splitext(base)[1]
# if first_ext in fastq_ends:
# return True
# elif (second_ext, first_ext) in product(fastq_ends, zip_ends):
# return True
# else:
# return False
#
# def open_fastq(in_file):
# """ open a fastq file, using gzip if it is gzipped
# from bcbio package
# """
# _, ext = os.path.splitext(in_file)
# if ext == ".gz":
# return gzip.open(in_file, 'rt')
# if ext in [".fastq", ".fq", ".fasta", ".fa"]:
# return open(in_file, 'r')
# return ValueError("File needs to be fastq|fasta|fq|fa [.gz]")
. Output only the next line. | if is_fastq(cols[0]): |
Next line prediction: <|code_start|> if counts > int(args.minc) and len(seq) > int(args.minl):
if seq not in seq_l:
seq_l[seq] = sequence_unique(idx, seq)
seq_l[seq].add_exp(cols[1], counts)
return seq_l, sample_l
def _read_fastq_files(f, args):
""" read fasta files of each sample and generate a seq_obj
with the information of each unique sequence in each sample
:param f: file containing the path for each fasta file and
the name of the sample. Two column format with `tab` as field
separator
:returns: * :code:`seq_l`: is a list of seq_obj objects, containing
the information of each sequence
* :code:`sample_l`: is a list with the name of the samples
(column two of the config file)
"""
seq_l = {}
sample_l = []
idx = 1
p = re.compile("^[ATCGNU]+$")
with open(op.join(args.out, "stats_prepare.tsv"), 'w') as out_handle:
for line1 in f:
line1 = line1.strip()
cols = line1.split("\t")
# if not is_fastq(cols[0]):
# raise ValueError("file is not fastq: %s" % cols[0])
<|code_end|>
. Use current file imports:
(import os
import os.path as op
import traceback
import re
import logging
from seqcluster.libs.classes import sequence_unique
from seqcluster.libs.classes import quality
from seqcluster.libs.fastq import is_fastq, open_fastq)
and context including class names, function names, or small code snippets from other files:
# Path: seqcluster/libs/classes.py
# class sequence_unique:
# """
# Object to store the sequence information like: **counts**, **sequence**, **id**
# """
# def __init__(self, idx, seq):
# self.idx = idx
# self.seq = seq
# self.group = {}
# self.quality = ""
# self.total = 0
# def add_exp(self,gr,exp):
# """Function to add the counts for each sample
#
# :param gr: name of the sample
# :param exp: counts of sample **gr**
#
# :returns: dict with key,values equally to name,counts.
# """
# self.group[gr] = exp
# self.total = sum(self.group.values())
#
# Path: seqcluster/libs/classes.py
# class quality:
#
# def __init__(self, q):
# self.qual = [ord(value) for value in q]
# self.times = 1
#
# def update(self, q, counts = 1):
# now = self.qual
# q = [ord(value) for value in q]
# self.qual = [x + y for x, y in zip(now, q)]
# self.times += counts
#
# def get(self):
# average = np.array(self.qual)/self.times
# return [str(unichr(int(char))) for char in average]
#
# Path: seqcluster/libs/fastq.py
# def is_fastq(in_file):
# """copy from bcbio package"""
# fastq_ends = [".txt", ".fq", ".fastq"]
# zip_ends = [".gzip", ".gz"]
# base, first_ext = os.path.splitext(in_file)
# second_ext = os.path.splitext(base)[1]
# if first_ext in fastq_ends:
# return True
# elif (second_ext, first_ext) in product(fastq_ends, zip_ends):
# return True
# else:
# return False
#
# def open_fastq(in_file):
# """ open a fastq file, using gzip if it is gzipped
# from bcbio package
# """
# _, ext = os.path.splitext(in_file)
# if ext == ".gz":
# return gzip.open(in_file, 'rt')
# if ext in [".fastq", ".fq", ".fasta", ".fa"]:
# return open(in_file, 'r')
# return ValueError("File needs to be fastq|fasta|fq|fa [.gz]")
. Output only the next line. | with open_fastq(cols[0]) as handle: |
Based on the snippet: <|code_start|> data_loci.insert(0, best_loci)
return data_loci
def peak_calling(clus_obj):
"""
Run peak calling inside each cluster
"""
new_cluster = {}
for cid in clus_obj.clus:
cluster = clus_obj.clus[cid]
cluster.update()
logger.debug("peak calling for %s" % cid)
bigger = cluster.locimaxid
# fn to get longer > 30 < 100 precursor
# iterate by them mapping reads, detect peak, descart, start_again
# give quantification of 'matures'
if bigger in clus_obj.loci:
s, e = min(clus_obj.loci[bigger].counts.keys()), max(clus_obj.loci[bigger].counts.keys())
scale = min(s, e)
logger.debug("bigger %s at %s-%s" % (bigger, s, e))
dt = np.array([0] * (e - s + 12))
for pos in clus_obj.loci[bigger].counts:
ss = int(pos) - scale + 5
dt[ss] += clus_obj.loci[bigger].counts[pos]
x = np.array(range(0, len(dt)))
logger.debug("x %s and y %s" % (x, dt))
# tab = pd.DataFrame({'x': x, 'y': dt})
# tab.to_csv( str(cid) + "peaks.csv", mode='w', header=False, index=False)
if len(x) > 35 + 12:
<|code_end|>
, predict the immediate next line with the help of imports:
from operator import itemgetter
from seqcluster.libs import pysen
from seqcluster.libs.classes import *
import numpy as np
import seqcluster.libs.logger as mylog
and context (classes, functions, sometimes code) from other files:
# Path: seqcluster/libs/pysen.py
# def pysenMMean (x, y):
. Output only the next line. | peaks = pysen.pysenMMean(x, dt) |
Predict the next line for this snippet: <|code_start|>"""Implementation of open source tools to predict small RNA functions"""
# import seqcluster.libs.logger as mylog
logger = mylog.getLogger(__name__)
def run_coral(clus_obj, out_dir, args):
"""
Run some CoRaL modules to predict small RNA function
"""
if not args.bed:
raise ValueError("This module needs the bed file output from cluster subcmd.")
workdir = op.abspath(op.join(args.out, 'coral'))
safe_dirs(workdir)
bam_in = op.abspath(args.bam)
bed_in = op.abspath(args.bed)
reference = op.abspath(args.ref)
<|code_end|>
with the help of current file imports:
from os import path as op
from seqcluster.libs.utils import chdir, safe_dirs
from seqcluster.libs import utils, logger as mylog
from seqcluster.libs.read import get_loci_fasta, make_temp_directory
from seqcluster.libs.do import run
from seqcluster.function import coral
import os
import shutil
and context from other files:
# Path: seqcluster/libs/utils.py
# @contextlib.contextmanager
# def chdir(p):
# cur_dir = os.getcwd()
# os.chdir(p)
# try:
# yield
# finally:
# os.chdir(cur_dir)
#
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
#
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/logger.py
# def getLogger(name):
# def set_format(frmt, frmt_col=None, datefmt=None):
# def initialize_logger(output_dir, debug, level=False):
# def note(self, message, *args, **kws):
# NOTE = 15
# COLOR_FORMAT = "%(log_color)s%(asctime)s%(levelname)s-%(name)s(%(lineno)d)%(reset)s: %(message)s"
# COLOR_FORMAT_INFO = "%(log_color)s%(asctime)s %(levelname)s%(reset)s: %(message)s"
# DATE_FRT = '%m/%d/%Y %I:%M:%S %p'
# FORMAT = "%(levelname)s-%(name)s(%(lineno)d): %(message)s"
# FORMAT_INFO = "%(levelname)s %(message)s"
#
# Path: seqcluster/libs/read.py
# def get_loci_fasta(loci, out_fa, ref):
# """get fasta from precursor"""
# if not find_cmd("bedtools"):
# raise ValueError("Not bedtools installed")
# with make_temp_directory() as temp:
# bed_file = os.path.join(temp, "file.bed")
# for nc, loci in loci.iteritems():
# for l in loci:
# with open(bed_file, 'w') as bed_handle:
# logger.debug("get_fasta: loci %s" % l)
# nc, c, s, e, st = l
# print("{0}\t{1}\t{2}\t{3}\t{3}\t{4}".format(c, s, e, nc, st), file=bed_handle)
# get_fasta(bed_file, ref, out_fa)
# return out_fa
#
# @contextlib.contextmanager
# def make_temp_directory(remove=True):
# temp_dir = tempfile.mkdtemp()
# yield temp_dir
# shutil.rmtree(temp_dir)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
#
# Path: seqcluster/function/coral.py
# def prepare_bam(bam_in, precursors):
# def _select_anno(annotation):
# def _reorder_columns(bed_file):
# def _fix_score_column(cov_file):
# def detect_regions(bam_in, bed_file, out_dir, prefix):
# def _order_antisense_column(cov_file, min_reads):
# def _reads_per_position(bam_in, loci_file, out_dir):
# def create_features(bam_in, loci_file, reference, out_dir):
# def prepare_ann_file(args):
# def download_hsa_file(args):
, which may contain function names, class names, or code. Output only the next line. | with chdir(workdir): |
Given snippet: <|code_start|>"""Implementation of open source tools to predict small RNA functions"""
# import seqcluster.libs.logger as mylog
logger = mylog.getLogger(__name__)
def run_coral(clus_obj, out_dir, args):
"""
Run some CoRaL modules to predict small RNA function
"""
if not args.bed:
raise ValueError("This module needs the bed file output from cluster subcmd.")
workdir = op.abspath(op.join(args.out, 'coral'))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from os import path as op
from seqcluster.libs.utils import chdir, safe_dirs
from seqcluster.libs import utils, logger as mylog
from seqcluster.libs.read import get_loci_fasta, make_temp_directory
from seqcluster.libs.do import run
from seqcluster.function import coral
import os
import shutil
and context:
# Path: seqcluster/libs/utils.py
# @contextlib.contextmanager
# def chdir(p):
# cur_dir = os.getcwd()
# os.chdir(p)
# try:
# yield
# finally:
# os.chdir(cur_dir)
#
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
#
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/logger.py
# def getLogger(name):
# def set_format(frmt, frmt_col=None, datefmt=None):
# def initialize_logger(output_dir, debug, level=False):
# def note(self, message, *args, **kws):
# NOTE = 15
# COLOR_FORMAT = "%(log_color)s%(asctime)s%(levelname)s-%(name)s(%(lineno)d)%(reset)s: %(message)s"
# COLOR_FORMAT_INFO = "%(log_color)s%(asctime)s %(levelname)s%(reset)s: %(message)s"
# DATE_FRT = '%m/%d/%Y %I:%M:%S %p'
# FORMAT = "%(levelname)s-%(name)s(%(lineno)d): %(message)s"
# FORMAT_INFO = "%(levelname)s %(message)s"
#
# Path: seqcluster/libs/read.py
# def get_loci_fasta(loci, out_fa, ref):
# """get fasta from precursor"""
# if not find_cmd("bedtools"):
# raise ValueError("Not bedtools installed")
# with make_temp_directory() as temp:
# bed_file = os.path.join(temp, "file.bed")
# for nc, loci in loci.iteritems():
# for l in loci:
# with open(bed_file, 'w') as bed_handle:
# logger.debug("get_fasta: loci %s" % l)
# nc, c, s, e, st = l
# print("{0}\t{1}\t{2}\t{3}\t{3}\t{4}".format(c, s, e, nc, st), file=bed_handle)
# get_fasta(bed_file, ref, out_fa)
# return out_fa
#
# @contextlib.contextmanager
# def make_temp_directory(remove=True):
# temp_dir = tempfile.mkdtemp()
# yield temp_dir
# shutil.rmtree(temp_dir)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
#
# Path: seqcluster/function/coral.py
# def prepare_bam(bam_in, precursors):
# def _select_anno(annotation):
# def _reorder_columns(bed_file):
# def _fix_score_column(cov_file):
# def detect_regions(bam_in, bed_file, out_dir, prefix):
# def _order_antisense_column(cov_file, min_reads):
# def _reads_per_position(bam_in, loci_file, out_dir):
# def create_features(bam_in, loci_file, reference, out_dir):
# def prepare_ann_file(args):
# def download_hsa_file(args):
which might include code, classes, or functions. Output only the next line. | safe_dirs(workdir) |
Here is a snippet: <|code_start|> """
if not args.bed:
raise ValueError("This module needs the bed file output from cluster subcmd.")
workdir = op.abspath(op.join(args.out, 'coral'))
safe_dirs(workdir)
bam_in = op.abspath(args.bam)
bed_in = op.abspath(args.bed)
reference = op.abspath(args.ref)
with chdir(workdir):
bam_clean = coral.prepare_bam(bam_in, bed_in)
out_dir = op.join(workdir, "regions")
safe_dirs(out_dir)
prefix = "seqcluster"
loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)
coral.create_features(bam_clean, loci_file, reference, out_dir)
def is_tRNA(clus_obj, out_dir, args):
"""
Iterates through cluster precursors to predict sRNA types
"""
ref = os.path.abspath(args.reference)
utils.safe_dirs(out_dir)
for nc in clus_obj[0]:
c = clus_obj[0][nc]
loci = c['loci']
out_fa = "cluster_" + nc
if loci[0][3] - loci[0][2] < 500:
with make_temp_directory() as tmpdir:
os.chdir(tmpdir)
<|code_end|>
. Write the next line using the current file imports:
from os import path as op
from seqcluster.libs.utils import chdir, safe_dirs
from seqcluster.libs import utils, logger as mylog
from seqcluster.libs.read import get_loci_fasta, make_temp_directory
from seqcluster.libs.do import run
from seqcluster.function import coral
import os
import shutil
and context from other files:
# Path: seqcluster/libs/utils.py
# @contextlib.contextmanager
# def chdir(p):
# cur_dir = os.getcwd()
# os.chdir(p)
# try:
# yield
# finally:
# os.chdir(cur_dir)
#
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
#
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/logger.py
# def getLogger(name):
# def set_format(frmt, frmt_col=None, datefmt=None):
# def initialize_logger(output_dir, debug, level=False):
# def note(self, message, *args, **kws):
# NOTE = 15
# COLOR_FORMAT = "%(log_color)s%(asctime)s%(levelname)s-%(name)s(%(lineno)d)%(reset)s: %(message)s"
# COLOR_FORMAT_INFO = "%(log_color)s%(asctime)s %(levelname)s%(reset)s: %(message)s"
# DATE_FRT = '%m/%d/%Y %I:%M:%S %p'
# FORMAT = "%(levelname)s-%(name)s(%(lineno)d): %(message)s"
# FORMAT_INFO = "%(levelname)s %(message)s"
#
# Path: seqcluster/libs/read.py
# def get_loci_fasta(loci, out_fa, ref):
# """get fasta from precursor"""
# if not find_cmd("bedtools"):
# raise ValueError("Not bedtools installed")
# with make_temp_directory() as temp:
# bed_file = os.path.join(temp, "file.bed")
# for nc, loci in loci.iteritems():
# for l in loci:
# with open(bed_file, 'w') as bed_handle:
# logger.debug("get_fasta: loci %s" % l)
# nc, c, s, e, st = l
# print("{0}\t{1}\t{2}\t{3}\t{3}\t{4}".format(c, s, e, nc, st), file=bed_handle)
# get_fasta(bed_file, ref, out_fa)
# return out_fa
#
# @contextlib.contextmanager
# def make_temp_directory(remove=True):
# temp_dir = tempfile.mkdtemp()
# yield temp_dir
# shutil.rmtree(temp_dir)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
#
# Path: seqcluster/function/coral.py
# def prepare_bam(bam_in, precursors):
# def _select_anno(annotation):
# def _reorder_columns(bed_file):
# def _fix_score_column(cov_file):
# def detect_regions(bam_in, bed_file, out_dir, prefix):
# def _order_antisense_column(cov_file, min_reads):
# def _reads_per_position(bam_in, loci_file, out_dir):
# def create_features(bam_in, loci_file, reference, out_dir):
# def prepare_ann_file(args):
# def download_hsa_file(args):
, which may include functions, classes, or code. Output only the next line. | get_loci_fasta({loci[0][0]: [loci[0][0:5]]}, out_fa, ref) |
Given the following code snippet before the placeholder: <|code_start|> """
Run some CoRaL modules to predict small RNA function
"""
if not args.bed:
raise ValueError("This module needs the bed file output from cluster subcmd.")
workdir = op.abspath(op.join(args.out, 'coral'))
safe_dirs(workdir)
bam_in = op.abspath(args.bam)
bed_in = op.abspath(args.bed)
reference = op.abspath(args.ref)
with chdir(workdir):
bam_clean = coral.prepare_bam(bam_in, bed_in)
out_dir = op.join(workdir, "regions")
safe_dirs(out_dir)
prefix = "seqcluster"
loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)
coral.create_features(bam_clean, loci_file, reference, out_dir)
def is_tRNA(clus_obj, out_dir, args):
"""
Iterates through cluster precursors to predict sRNA types
"""
ref = os.path.abspath(args.reference)
utils.safe_dirs(out_dir)
for nc in clus_obj[0]:
c = clus_obj[0][nc]
loci = c['loci']
out_fa = "cluster_" + nc
if loci[0][3] - loci[0][2] < 500:
<|code_end|>
, predict the next line using imports from the current file:
from os import path as op
from seqcluster.libs.utils import chdir, safe_dirs
from seqcluster.libs import utils, logger as mylog
from seqcluster.libs.read import get_loci_fasta, make_temp_directory
from seqcluster.libs.do import run
from seqcluster.function import coral
import os
import shutil
and context including class names, function names, and sometimes code from other files:
# Path: seqcluster/libs/utils.py
# @contextlib.contextmanager
# def chdir(p):
# cur_dir = os.getcwd()
# os.chdir(p)
# try:
# yield
# finally:
# os.chdir(cur_dir)
#
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
#
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/logger.py
# def getLogger(name):
# def set_format(frmt, frmt_col=None, datefmt=None):
# def initialize_logger(output_dir, debug, level=False):
# def note(self, message, *args, **kws):
# NOTE = 15
# COLOR_FORMAT = "%(log_color)s%(asctime)s%(levelname)s-%(name)s(%(lineno)d)%(reset)s: %(message)s"
# COLOR_FORMAT_INFO = "%(log_color)s%(asctime)s %(levelname)s%(reset)s: %(message)s"
# DATE_FRT = '%m/%d/%Y %I:%M:%S %p'
# FORMAT = "%(levelname)s-%(name)s(%(lineno)d): %(message)s"
# FORMAT_INFO = "%(levelname)s %(message)s"
#
# Path: seqcluster/libs/read.py
# def get_loci_fasta(loci, out_fa, ref):
# """get fasta from precursor"""
# if not find_cmd("bedtools"):
# raise ValueError("Not bedtools installed")
# with make_temp_directory() as temp:
# bed_file = os.path.join(temp, "file.bed")
# for nc, loci in loci.iteritems():
# for l in loci:
# with open(bed_file, 'w') as bed_handle:
# logger.debug("get_fasta: loci %s" % l)
# nc, c, s, e, st = l
# print("{0}\t{1}\t{2}\t{3}\t{3}\t{4}".format(c, s, e, nc, st), file=bed_handle)
# get_fasta(bed_file, ref, out_fa)
# return out_fa
#
# @contextlib.contextmanager
# def make_temp_directory(remove=True):
# temp_dir = tempfile.mkdtemp()
# yield temp_dir
# shutil.rmtree(temp_dir)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
#
# Path: seqcluster/function/coral.py
# def prepare_bam(bam_in, precursors):
# def _select_anno(annotation):
# def _reorder_columns(bed_file):
# def _fix_score_column(cov_file):
# def detect_regions(bam_in, bed_file, out_dir, prefix):
# def _order_antisense_column(cov_file, min_reads):
# def _reads_per_position(bam_in, loci_file, out_dir):
# def create_features(bam_in, loci_file, reference, out_dir):
# def prepare_ann_file(args):
# def download_hsa_file(args):
. Output only the next line. | with make_temp_directory() as tmpdir: |
Given the code snippet: <|code_start|> else:
c['errors'].add("precursor too long")
clus_obj[0][nc] = c
return clus_obj
def _read_tRNA_scan(summary_file):
"""
Parse output from tRNA_Scan
"""
score = 0
if os.path.getsize(summary_file) == 0:
return 0
with open(summary_file) as in_handle:
# header = in_handle.next().strip().split()
for line in in_handle:
if not line.startswith("--"):
pre = line.strip().split()
score = pre[-1]
return score
def _run_tRNA_scan(fasta_file):
"""
Run tRNA-scan-SE to predict tRNA
"""
out_file = fasta_file + "_trnascan"
se_file = fasta_file + "_second_str"
cmd = "tRNAscan-SE -q -o {out_file} -f {se_file} {fasta_file}"
<|code_end|>
, generate the next line using the imports in this file:
from os import path as op
from seqcluster.libs.utils import chdir, safe_dirs
from seqcluster.libs import utils, logger as mylog
from seqcluster.libs.read import get_loci_fasta, make_temp_directory
from seqcluster.libs.do import run
from seqcluster.function import coral
import os
import shutil
and context (functions, classes, or occasionally code) from other files:
# Path: seqcluster/libs/utils.py
# @contextlib.contextmanager
# def chdir(p):
# cur_dir = os.getcwd()
# os.chdir(p)
# try:
# yield
# finally:
# os.chdir(cur_dir)
#
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
#
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/logger.py
# def getLogger(name):
# def set_format(frmt, frmt_col=None, datefmt=None):
# def initialize_logger(output_dir, debug, level=False):
# def note(self, message, *args, **kws):
# NOTE = 15
# COLOR_FORMAT = "%(log_color)s%(asctime)s%(levelname)s-%(name)s(%(lineno)d)%(reset)s: %(message)s"
# COLOR_FORMAT_INFO = "%(log_color)s%(asctime)s %(levelname)s%(reset)s: %(message)s"
# DATE_FRT = '%m/%d/%Y %I:%M:%S %p'
# FORMAT = "%(levelname)s-%(name)s(%(lineno)d): %(message)s"
# FORMAT_INFO = "%(levelname)s %(message)s"
#
# Path: seqcluster/libs/read.py
# def get_loci_fasta(loci, out_fa, ref):
# """get fasta from precursor"""
# if not find_cmd("bedtools"):
# raise ValueError("Not bedtools installed")
# with make_temp_directory() as temp:
# bed_file = os.path.join(temp, "file.bed")
# for nc, loci in loci.iteritems():
# for l in loci:
# with open(bed_file, 'w') as bed_handle:
# logger.debug("get_fasta: loci %s" % l)
# nc, c, s, e, st = l
# print("{0}\t{1}\t{2}\t{3}\t{3}\t{4}".format(c, s, e, nc, st), file=bed_handle)
# get_fasta(bed_file, ref, out_fa)
# return out_fa
#
# @contextlib.contextmanager
# def make_temp_directory(remove=True):
# temp_dir = tempfile.mkdtemp()
# yield temp_dir
# shutil.rmtree(temp_dir)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
#
# Path: seqcluster/function/coral.py
# def prepare_bam(bam_in, precursors):
# def _select_anno(annotation):
# def _reorder_columns(bed_file):
# def _fix_score_column(cov_file):
# def detect_regions(bam_in, bed_file, out_dir, prefix):
# def _order_antisense_column(cov_file, min_reads):
# def _reads_per_position(bam_in, loci_file, out_dir):
# def create_features(bam_in, loci_file, reference, out_dir):
# def prepare_ann_file(args):
# def download_hsa_file(args):
. Output only the next line. | run(cmd.format(**locals())) |
Given snippet: <|code_start|>"""Implementation of open source tools to predict small RNA functions"""
# import seqcluster.libs.logger as mylog
logger = mylog.getLogger(__name__)
def run_coral(clus_obj, out_dir, args):
"""
Run some CoRaL modules to predict small RNA function
"""
if not args.bed:
raise ValueError("This module needs the bed file output from cluster subcmd.")
workdir = op.abspath(op.join(args.out, 'coral'))
safe_dirs(workdir)
bam_in = op.abspath(args.bam)
bed_in = op.abspath(args.bed)
reference = op.abspath(args.ref)
with chdir(workdir):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from os import path as op
from seqcluster.libs.utils import chdir, safe_dirs
from seqcluster.libs import utils, logger as mylog
from seqcluster.libs.read import get_loci_fasta, make_temp_directory
from seqcluster.libs.do import run
from seqcluster.function import coral
import os
import shutil
and context:
# Path: seqcluster/libs/utils.py
# @contextlib.contextmanager
# def chdir(p):
# cur_dir = os.getcwd()
# os.chdir(p)
# try:
# yield
# finally:
# os.chdir(cur_dir)
#
# def safe_dirs(dirs):
# if not os.path.exists(dirs):
# os.makedirs(dirs)
# return dirs
#
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/logger.py
# def getLogger(name):
# def set_format(frmt, frmt_col=None, datefmt=None):
# def initialize_logger(output_dir, debug, level=False):
# def note(self, message, *args, **kws):
# NOTE = 15
# COLOR_FORMAT = "%(log_color)s%(asctime)s%(levelname)s-%(name)s(%(lineno)d)%(reset)s: %(message)s"
# COLOR_FORMAT_INFO = "%(log_color)s%(asctime)s %(levelname)s%(reset)s: %(message)s"
# DATE_FRT = '%m/%d/%Y %I:%M:%S %p'
# FORMAT = "%(levelname)s-%(name)s(%(lineno)d): %(message)s"
# FORMAT_INFO = "%(levelname)s %(message)s"
#
# Path: seqcluster/libs/read.py
# def get_loci_fasta(loci, out_fa, ref):
# """get fasta from precursor"""
# if not find_cmd("bedtools"):
# raise ValueError("Not bedtools installed")
# with make_temp_directory() as temp:
# bed_file = os.path.join(temp, "file.bed")
# for nc, loci in loci.iteritems():
# for l in loci:
# with open(bed_file, 'w') as bed_handle:
# logger.debug("get_fasta: loci %s" % l)
# nc, c, s, e, st = l
# print("{0}\t{1}\t{2}\t{3}\t{3}\t{4}".format(c, s, e, nc, st), file=bed_handle)
# get_fasta(bed_file, ref, out_fa)
# return out_fa
#
# @contextlib.contextmanager
# def make_temp_directory(remove=True):
# temp_dir = tempfile.mkdtemp()
# yield temp_dir
# shutil.rmtree(temp_dir)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
#
# Path: seqcluster/function/coral.py
# def prepare_bam(bam_in, precursors):
# def _select_anno(annotation):
# def _reorder_columns(bed_file):
# def _fix_score_column(cov_file):
# def detect_regions(bam_in, bed_file, out_dir, prefix):
# def _order_antisense_column(cov_file, min_reads):
# def _reads_per_position(bam_in, loci_file, out_dir):
# def create_features(bam_in, loci_file, reference, out_dir):
# def prepare_ann_file(args):
# def download_hsa_file(args):
which might include code, classes, or functions. Output only the next line. | bam_clean = coral.prepare_bam(bam_in, bed_in) |
Given the following code snippet before the placeholder: <|code_start|> # logger.debug("num cluster %s" % len(clus_obj.keys()))
logger.info("%s clusters merged" % len(metacluster))
return metacluster, seen
def peak_calling(clus_obj):
"""
Run peak calling inside each cluster
"""
new_cluster = {}
for cid in clus_obj.clus:
cluster = clus_obj.clus[cid]
cluster.update()
logger.debug("peak calling for %s" % cid)
bigger = cluster.locimaxid
if bigger in clus_obj.loci:
s, e = min(clus_obj.loci[bigger].counts.keys()), max(clus_obj.loci[bigger].counts.keys())
scale = s
if clus_obj.loci[bigger].strand == "-":
scale = e
logger.debug("bigger %s at %s-%s" % (bigger, s, e))
dt = np.array([0] * (abs(e - s) + 12))
for pos in clus_obj.loci[bigger].counts:
ss = abs(int(pos) - scale) + 5
dt[ss] += clus_obj.loci[bigger].counts[pos]
x = np.array(range(0, len(dt)))
logger.debug("x %s and y %s" % (x, dt))
# tab = pd.DataFrame({'x': x, 'y': dt})
# tab.to_csv( str(cid) + "peaks.csv", mode='w', header=False, index=False)
if len(x) > 35 + 12:
<|code_end|>
, predict the next line using imports from the current file:
import os.path as op
import pysam
import pybedtools
import numpy as np
import seqcluster.libs.logger as mylog
from progressbar import ProgressBar
from seqcluster.libs import pysen
from seqcluster.libs.utils import file_exists
from seqcluster.libs.classes import *
from seqcluster.detect.metacluster import _get_seqs_from_cluster
from seqcluster.libs.do import run
and context including class names, function names, and sometimes code from other files:
# Path: seqcluster/libs/pysen.py
# def pysenMMean (x, y):
#
# Path: seqcluster/libs/utils.py
# def file_exists(fname):
# """Check if a file exists and is non-empty.
# """
# try:
# return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
# except OSError:
# return False
#
# Path: seqcluster/detect/metacluster.py
# def _get_seqs_from_cluster(seqs, seen):
# """
# Returns the sequences that are already part of the cluster
#
# :param seqs: list of sequences ids
# :param clus_id: dict of sequences ids that are part of a cluster
#
# :returns:
# * :code:`already_in`list of cluster id that contained some of the sequences
# * :code:`not_in`list of sequences that don't belong to any cluster yet
# """
# already_in = set()
# not_in = []
#
# already_in = [e for e in map(seen.get, seqs)]
# # if isinstance(already_in, list):
# already_in = filter(None, already_in)
# not_in = set(seqs) - set(seen.keys())
# return list(set(already_in)), list(not_in)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
. Output only the next line. | peaks = list(np.array(pysen.pysenMMean(x, dt)) - 5) |
Predict the next line for this snippet: <|code_start|>
logger = mylog.getLogger(__name__)
def detect_complexity(bam_in, genome, out):
"""
genome coverage of small RNA
"""
if not genome:
logger.info("No genome given. skipping.")
return None
out_file = op.join(out, op.basename(bam_in) + "_cov.tsv")
<|code_end|>
with the help of current file imports:
import os.path as op
import pysam
import pybedtools
import numpy as np
import seqcluster.libs.logger as mylog
from progressbar import ProgressBar
from seqcluster.libs import pysen
from seqcluster.libs.utils import file_exists
from seqcluster.libs.classes import *
from seqcluster.detect.metacluster import _get_seqs_from_cluster
from seqcluster.libs.do import run
and context from other files:
# Path: seqcluster/libs/pysen.py
# def pysenMMean (x, y):
#
# Path: seqcluster/libs/utils.py
# def file_exists(fname):
# """Check if a file exists and is non-empty.
# """
# try:
# return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
# except OSError:
# return False
#
# Path: seqcluster/detect/metacluster.py
# def _get_seqs_from_cluster(seqs, seen):
# """
# Returns the sequences that are already part of the cluster
#
# :param seqs: list of sequences ids
# :param clus_id: dict of sequences ids that are part of a cluster
#
# :returns:
# * :code:`already_in`list of cluster id that contained some of the sequences
# * :code:`not_in`list of sequences that don't belong to any cluster yet
# """
# already_in = set()
# not_in = []
#
# already_in = [e for e in map(seen.get, seqs)]
# # if isinstance(already_in, list):
# already_in = filter(None, already_in)
# not_in = set(seqs) - set(seen.keys())
# return list(set(already_in)), list(not_in)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
, which may contain function names, class names, or code. Output only the next line. | if file_exists(out_file): |
Based on the snippet: <|code_start|> metacluster[meta_idx] = metacluster[meta_idx].union(clusters2merge)
_update(clusters2merge, meta_idx, seen)
# metacluster[seen_metacluster] = 0
del metacluster[seen_metacluster]
logger.info("%s metaclusters from %s sequences" % (len(metacluster), c_index))
return metacluster, seen
def _find_families_deprecated(clus_obj, min_seqs):
"""
Mask under same id all clusters that share sequences
:param clus_obj: cluster object coming from detect_cluster
:param min_seqs: int cutoff to keep the cluster or not. 10 as default
:return: updated clus_obj and dict with seq_id: cluster_id
"""
logger.info("Creating meta-clusters based on shared sequences.")
seen = defaultdict()
metacluster = defaultdict(list)
c_index = clus_obj.keys()
meta_idx = 0
p = ProgressBar(maxval=len(c_index), redirect_stdout=True).start()
for itern, c in enumerate(c_index):
p.update(itern)
clus = clus_obj[c]
if len(clus.idmembers.keys()) < min_seqs:
del clus_obj[c]
continue
logger.debug("reading cluster %s" % c)
logger.debug("loci2seq %s" % clus.loci2seq)
<|code_end|>
, predict the immediate next line with the help of imports:
import os.path as op
import pysam
import pybedtools
import numpy as np
import seqcluster.libs.logger as mylog
from progressbar import ProgressBar
from seqcluster.libs import pysen
from seqcluster.libs.utils import file_exists
from seqcluster.libs.classes import *
from seqcluster.detect.metacluster import _get_seqs_from_cluster
from seqcluster.libs.do import run
and context (classes, functions, sometimes code) from other files:
# Path: seqcluster/libs/pysen.py
# def pysenMMean (x, y):
#
# Path: seqcluster/libs/utils.py
# def file_exists(fname):
# """Check if a file exists and is non-empty.
# """
# try:
# return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
# except OSError:
# return False
#
# Path: seqcluster/detect/metacluster.py
# def _get_seqs_from_cluster(seqs, seen):
# """
# Returns the sequences that are already part of the cluster
#
# :param seqs: list of sequences ids
# :param clus_id: dict of sequences ids that are part of a cluster
#
# :returns:
# * :code:`already_in`list of cluster id that contained some of the sequences
# * :code:`not_in`list of sequences that don't belong to any cluster yet
# """
# already_in = set()
# not_in = []
#
# already_in = [e for e in map(seen.get, seqs)]
# # if isinstance(already_in, list):
# already_in = filter(None, already_in)
# not_in = set(seqs) - set(seen.keys())
# return list(set(already_in)), list(not_in)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
. Output only the next line. | already_in, not_in = _get_seqs_from_cluster(clus.idmembers.keys(), seen) |
Given the following code snippet before the placeholder: <|code_start|> """
genome coverage of small RNA
"""
if not genome:
logger.info("No genome given. skipping.")
return None
out_file = op.join(out, op.basename(bam_in) + "_cov.tsv")
if file_exists(out_file):
return None
fai = genome + ".fai"
cov = pybedtools.BedTool(bam_in).genome_coverage(max=1)
cov.saveas(out_file)
total = 0
for region in cov:
if region[0] == "genome" and int(region[1]) != 0:
total += float(region[4])
logger.info("Total genome with sequences: %s " % total)
def clean_bam_file(bam_in, mask=None):
"""
Remove from alignment reads with low counts and highly # of hits
"""
seq_obj = defaultdict(int)
if mask:
mask_file = op.splitext(bam_in)[0] + "_mask.bam"
if not file_exists(mask_file):
pybedtools.BedTool(bam_in).intersect(b=mask, v=True).saveas(mask_file)
bam_in = mask_file
out_file = op.splitext(bam_in)[0] + "_rmlw.bam"
# bam.index(bam_in, {'algorithm':{}})
<|code_end|>
, predict the next line using imports from the current file:
import os.path as op
import pysam
import pybedtools
import numpy as np
import seqcluster.libs.logger as mylog
from progressbar import ProgressBar
from seqcluster.libs import pysen
from seqcluster.libs.utils import file_exists
from seqcluster.libs.classes import *
from seqcluster.detect.metacluster import _get_seqs_from_cluster
from seqcluster.libs.do import run
and context including class names, function names, and sometimes code from other files:
# Path: seqcluster/libs/pysen.py
# def pysenMMean (x, y):
#
# Path: seqcluster/libs/utils.py
# def file_exists(fname):
# """Check if a file exists and is non-empty.
# """
# try:
# return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
# except OSError:
# return False
#
# Path: seqcluster/detect/metacluster.py
# def _get_seqs_from_cluster(seqs, seen):
# """
# Returns the sequences that are already part of the cluster
#
# :param seqs: list of sequences ids
# :param clus_id: dict of sequences ids that are part of a cluster
#
# :returns:
# * :code:`already_in`list of cluster id that contained some of the sequences
# * :code:`not_in`list of sequences that don't belong to any cluster yet
# """
# already_in = set()
# not_in = []
#
# already_in = [e for e in map(seen.get, seqs)]
# # if isinstance(already_in, list):
# already_in = filter(None, already_in)
# not_in = set(seqs) - set(seen.keys())
# return list(set(already_in)), list(not_in)
#
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
. Output only the next line. | run("samtools index %s" % bam_in) |
Next line prediction: <|code_start|> for itern, idmc in enumerate(current):
bar.update(itern)
logger.debug("_reduceloci: cluster %s" % idmc)
c = copy.deepcopy(list(current[idmc]))
n_loci = len(c)
if n_loci < 100:
filtered, n_cluster = _iter_loci(c, clus_obj.clus, (clus_obj.loci, clus_obj.seq), filtered, n_cluster)
else:
large += 1
n_cluster += 1
_write_cluster(c, clus_obj.clus, clus_obj.loci, n_cluster, path)
filtered[n_cluster] = _add_complete_cluster(n_cluster, c, clus_obj.clus)
clus_obj.clus = filtered
seqs = 0
for idc in filtered:
seqs += len(filtered[idc].idmembers)
logger.info("Seqs in clusters %s" % (seqs))
logger.info("Clusters too long to be analyzed: %s" % large)
logger.info("Number of clusters removed because low number of reads: %s" % REMOVED)
logger.info("Number of clusters with conflicts: %s" % CONFLICT)
return clus_obj
def _write_cluster(metacluster, cluster, loci, idx, path):
"""
For complex meta-clusters, write all the loci for further debug
"""
out_file = op.join(path, 'log', str(idx) + '.bed')
<|code_end|>
. Use current file imports:
(from collections import defaultdict
from progressbar import ProgressBar
from seqcluster.libs import utils
from seqcluster.libs import parameters
from seqcluster.libs.classes import *
from seqcluster.libs.mystats import up_threshold
from seqcluster.libs.bayes import decide_by_bayes
import operator
import os
import os.path as op
import copy
import math
import seqcluster.libs.logger as mylog)
and context including class names, function names, or small code snippets from other files:
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/parameters.py
#
# Path: seqcluster/libs/mystats.py
# def up_threshold(x, s, p):
# """function to decide if similarity is
# below cutoff"""
# if 1.0 * x/s >= p:
# return True
# elif stat.binom_test(x, s, p) > 0.01:
# return True
# return False
#
# Path: seqcluster/libs/bayes.py
# def decide_by_bayes(list_c, s2p):
# # for each cluster get seq ~ loci edges
# loci_obj, seq_obj = s2p
# seqs_in_c = _dict_seq_locus(list_c, loci_obj, seq_obj)
# for s in seqs_in_c:
# total = sum(seqs_in_c[s].values())
# norm_values = 1.0 * np.array(seqs_in_c[s].values()) / total
# prob = _bayes(dict(zip(seqs_in_c[s].keys(), norm_values)))
# for clus in prob:
# list_c[clus].idmembers[s] = prob.loci[clus]["position"]
# # print "%s %s %s" % (s, clus, list_c[clus].idmembers[s])
# return list_c
. Output only the next line. | with utils.safe_run(out_file): |
Predict the next line for this snippet: <|code_start|>def _calculate_similarity(c):
"""Get a similarity matrix of % of shared sequence
:param c: cluster object
:return ma: similarity matrix
"""
ma = {}
for idc in c:
set1 = _get_seqs(c[idc])
[ma.update({(idc, idc2): _common(set1, _get_seqs(c[idc2]), idc, idc2)}) for idc2 in c if idc != idc2 and (idc2, idc) not in ma]
# logger.debug("_calculate_similarity_ %s" % ma)
return ma
def _get_seqs(list_idl):
"""get all sequences in a cluster knowing loci"""
seqs = set()
for idl in list_idl.loci2seq:
# logger.debug("_get_seqs_: loci %s" % idl)
[seqs.add(s) for s in list_idl.loci2seq[idl]]
# logger.debug("_get_seqs_: %s" % len(seqs))
return seqs
def _common(s1, s2, i1, i2):
"""calculate the common % percentage of sequences"""
c = len(set(s1).intersection(s2))
t = min(len(s1), len(s2))
pct = 1.0 * c / t * t
<|code_end|>
with the help of current file imports:
from collections import defaultdict
from progressbar import ProgressBar
from seqcluster.libs import utils
from seqcluster.libs import parameters
from seqcluster.libs.classes import *
from seqcluster.libs.mystats import up_threshold
from seqcluster.libs.bayes import decide_by_bayes
import operator
import os
import os.path as op
import copy
import math
import seqcluster.libs.logger as mylog
and context from other files:
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/parameters.py
#
# Path: seqcluster/libs/mystats.py
# def up_threshold(x, s, p):
# """function to decide if similarity is
# below cutoff"""
# if 1.0 * x/s >= p:
# return True
# elif stat.binom_test(x, s, p) > 0.01:
# return True
# return False
#
# Path: seqcluster/libs/bayes.py
# def decide_by_bayes(list_c, s2p):
# # for each cluster get seq ~ loci edges
# loci_obj, seq_obj = s2p
# seqs_in_c = _dict_seq_locus(list_c, loci_obj, seq_obj)
# for s in seqs_in_c:
# total = sum(seqs_in_c[s].values())
# norm_values = 1.0 * np.array(seqs_in_c[s].values()) / total
# prob = _bayes(dict(zip(seqs_in_c[s].keys(), norm_values)))
# for clus in prob:
# list_c[clus].idmembers[s] = prob.loci[clus]["position"]
# # print "%s %s %s" % (s, clus, list_c[clus].idmembers[s])
# return list_c
, which may contain function names, class names, or code. Output only the next line. | is_gt = up_threshold(pct, t * 1.0, parameters.similar) |
Given the following code snippet before the placeholder: <|code_start|>def _calculate_similarity(c):
"""Get a similarity matrix of % of shared sequence
:param c: cluster object
:return ma: similarity matrix
"""
ma = {}
for idc in c:
set1 = _get_seqs(c[idc])
[ma.update({(idc, idc2): _common(set1, _get_seqs(c[idc2]), idc, idc2)}) for idc2 in c if idc != idc2 and (idc2, idc) not in ma]
# logger.debug("_calculate_similarity_ %s" % ma)
return ma
def _get_seqs(list_idl):
"""get all sequences in a cluster knowing loci"""
seqs = set()
for idl in list_idl.loci2seq:
# logger.debug("_get_seqs_: loci %s" % idl)
[seqs.add(s) for s in list_idl.loci2seq[idl]]
# logger.debug("_get_seqs_: %s" % len(seqs))
return seqs
def _common(s1, s2, i1, i2):
"""calculate the common % percentage of sequences"""
c = len(set(s1).intersection(s2))
t = min(len(s1), len(s2))
pct = 1.0 * c / t * t
<|code_end|>
, predict the next line using imports from the current file:
from collections import defaultdict
from progressbar import ProgressBar
from seqcluster.libs import utils
from seqcluster.libs import parameters
from seqcluster.libs.classes import *
from seqcluster.libs.mystats import up_threshold
from seqcluster.libs.bayes import decide_by_bayes
import operator
import os
import os.path as op
import copy
import math
import seqcluster.libs.logger as mylog
and context including class names, function names, and sometimes code from other files:
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/parameters.py
#
# Path: seqcluster/libs/mystats.py
# def up_threshold(x, s, p):
# """function to decide if similarity is
# below cutoff"""
# if 1.0 * x/s >= p:
# return True
# elif stat.binom_test(x, s, p) > 0.01:
# return True
# return False
#
# Path: seqcluster/libs/bayes.py
# def decide_by_bayes(list_c, s2p):
# # for each cluster get seq ~ loci edges
# loci_obj, seq_obj = s2p
# seqs_in_c = _dict_seq_locus(list_c, loci_obj, seq_obj)
# for s in seqs_in_c:
# total = sum(seqs_in_c[s].values())
# norm_values = 1.0 * np.array(seqs_in_c[s].values()) / total
# prob = _bayes(dict(zip(seqs_in_c[s].keys(), norm_values)))
# for clus in prob:
# list_c[clus].idmembers[s] = prob.loci[clus]["position"]
# # print "%s %s %s" % (s, clus, list_c[clus].idmembers[s])
# return list_c
. Output only the next line. | is_gt = up_threshold(pct, t * 1.0, parameters.similar) |
Next line prediction: <|code_start|> logger.debug("_merge_similar: total clus %s" %
len(internal_cluster.keys()))
return internal_cluster
def _merge_cluster(old, new):
"""merge one cluster to another"""
logger.debug("_merge_cluster: %s to %s" % (old.id, new.id))
logger.debug("_merge_cluster: add idls %s" % old.loci2seq.keys())
for idl in old.loci2seq:
# if idl in new.loci2seq:
# new.loci2seq[idl] = list(set(new.loci2seq[idl] + old.loci2seq[idl]))
# new.loci2seq[idl] = old.loci2seq[idl]
new.add_id_member(old.loci2seq[idl], idl)
return new
def _solve_conflict(list_c, s2p, n_cluster):
"""
Make sure sequences are counts once.
Resolve by most-vote or exclussion
:params list_c: dict of objects cluster
:param s2p: dict of [loci].coverage = # num of seqs
:param n_cluster: number of clusters
return dict: new set of clusters
"""
logger.debug("_solve_conflict: count once")
if parameters.decision_cluster == "bayes":
<|code_end|>
. Use current file imports:
(from collections import defaultdict
from progressbar import ProgressBar
from seqcluster.libs import utils
from seqcluster.libs import parameters
from seqcluster.libs.classes import *
from seqcluster.libs.mystats import up_threshold
from seqcluster.libs.bayes import decide_by_bayes
import operator
import os
import os.path as op
import copy
import math
import seqcluster.libs.logger as mylog)
and context including class names, function names, or small code snippets from other files:
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
#
# Path: seqcluster/libs/parameters.py
#
# Path: seqcluster/libs/mystats.py
# def up_threshold(x, s, p):
# """function to decide if similarity is
# below cutoff"""
# if 1.0 * x/s >= p:
# return True
# elif stat.binom_test(x, s, p) > 0.01:
# return True
# return False
#
# Path: seqcluster/libs/bayes.py
# def decide_by_bayes(list_c, s2p):
# # for each cluster get seq ~ loci edges
# loci_obj, seq_obj = s2p
# seqs_in_c = _dict_seq_locus(list_c, loci_obj, seq_obj)
# for s in seqs_in_c:
# total = sum(seqs_in_c[s].values())
# norm_values = 1.0 * np.array(seqs_in_c[s].values()) / total
# prob = _bayes(dict(zip(seqs_in_c[s].keys(), norm_values)))
# for clus in prob:
# list_c[clus].idmembers[s] = prob.loci[clus]["position"]
# # print "%s %s %s" % (s, clus, list_c[clus].idmembers[s])
# return list_c
. Output only the next line. | return decide_by_bayes(list_c, s2p) |
Given the code snippet: <|code_start|>
class TestPreparedata(TestCase):
@attr(collapse=True)
def test_preparedata(self):
out_dir = "test/test_out_prepare"
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.mkdir(out_dir)
arg = namedtuple('args', 'minl maxl minc out')
args = arg(15, 40, 1, out_dir)
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from collections import namedtuple
from seqcluster.prepare_data import _read_fastq_files, _create_matrix_uniq_seq
from nose.plugins.attrib import attr
from seqcluster.libs.fastq import collapse, write_output
import os
import shutil
import inspect
import seqcluster
and context (functions, classes, or occasionally code) from other files:
# Path: seqcluster/prepare_data.py
# def _read_fastq_files(f, args):
# """ read fasta files of each sample and generate a seq_obj
# with the information of each unique sequence in each sample
#
# :param f: file containing the path for each fasta file and
# the name of the sample. Two column format with `tab` as field
# separator
#
# :returns: * :code:`seq_l`: is a list of seq_obj objects, containing
# the information of each sequence
# * :code:`sample_l`: is a list with the name of the samples
# (column two of the config file)
# """
# seq_l = {}
# sample_l = []
# idx = 1
# p = re.compile("^[ATCGNU]+$")
# with open(op.join(args.out, "stats_prepare.tsv"), 'w') as out_handle:
# for line1 in f:
# line1 = line1.strip()
# cols = line1.split("\t")
# # if not is_fastq(cols[0]):
# # raise ValueError("file is not fastq: %s" % cols[0])
# with open_fastq(cols[0]) as handle:
# sample_l.append(cols[1])
# total = added = 0
# line = handle.readline()
# while line:
# if line.startswith("@") or line.startswith(">"):
# seq = handle.readline().strip()
# if not p.match(seq):
# continue
# idx += 1
# total += 1
# keep = {}
# counts = int(re.search("x([0-9]+)", line.strip()).group(1))
# if is_fastq(cols[0]):
# handle.readline().strip()
# qual = handle.readline().strip()
# else:
# qual = "I" * len(seq)
# qual = qual[0:int(args.maxl)] if len(qual) > int(args.maxl) else qual
# seq = seq[0:int(args.maxl)] if len(seq) > int(args.maxl) else seq
# if counts > int(args.minc) and len(seq) > int(args.minl):
# added += 1
# if seq in keep:
# keep[seq].update(qual)
# else:
# keep[seq] = quality(qual)
# if seq not in seq_l:
# seq_l[seq] = sequence_unique(idx, seq)
# seq_l[seq].add_exp(cols[1], counts)
# seq_l[seq].quality = keep[seq].get()
# line=handle.readline()
# print("total\t%s\t%s" % (idx, cols[1]), file=out_handle, end="")
# print("added\t%s\t%s" % (len(seq_l), cols[1]), file=out_handle, end="")
# logger.info("%s: Total read %s ; Total added %s" % (cols[1], idx, len(seq_l)))
# return seq_l, sample_l
#
# def _create_matrix_uniq_seq(sample_l, seq_l, maout, out, min_shared):
# """ create matrix counts for each different sequence in all the fasta files
#
# :param sample_l: :code:`list_s` is the output of :code:`_read_fasta_files`
# :param seq_l: :code:`seq_s` is the output of :code:`_read_fasta_files`
# :param maout: is a file handler to write the matrix count information
# :param out: is a file handle to write the fasta file with unique sequences
#
# :returns: Null
# """
# skip = 0
# if int(min_shared) > len(sample_l):
# min_shared = len(sample_l)
# maout.write("id\tseq")
# for g in sample_l:
# maout.write("\t%s" % g)
# for s in seq_l.keys():
# seen = sum([1 for g in seq_l[s].group if seq_l[s].group[g] > 0])
# if seen < int(min_shared):
# skip += 1
# continue
# maout.write("\nseq_%s\t%s" % (seq_l[s].idx, seq_l[s].seq))
# for g in sample_l:
# if g in seq_l[s].group:
# maout.write("\t%s" % seq_l[s].group[g])
# else:
# maout.write("\t0")
# qual = "".join(seq_l[s].quality)
# out.write("@seq_%s\n%s\n+\n%s\n" % (seq_l[s].idx, seq_l[s].seq, qual))
# out.close()
# maout.close()
# logger.info("Total skipped due to --min-shared parameter (%s) : %s" % (min_shared, skip))
. Output only the next line. | seq_l, list_s = _read_fastq_files(open("data/examples/collapse/config"), args) |
Next line prediction: <|code_start|>
class TestPreparedata(TestCase):
@attr(collapse=True)
def test_preparedata(self):
out_dir = "test/test_out_prepare"
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.mkdir(out_dir)
arg = namedtuple('args', 'minl maxl minc out')
args = arg(15, 40, 1, out_dir)
seq_l, list_s = _read_fastq_files(open("data/examples/collapse/config"), args)
ma_out = open(os.path.join(out_dir, "seqs.ma"), 'w')
seq_out = open(os.path.join(out_dir, "seqs.fa"), 'w')
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from collections import namedtuple
from seqcluster.prepare_data import _read_fastq_files, _create_matrix_uniq_seq
from nose.plugins.attrib import attr
from seqcluster.libs.fastq import collapse, write_output
import os
import shutil
import inspect
import seqcluster)
and context including class names, function names, or small code snippets from other files:
# Path: seqcluster/prepare_data.py
# def _read_fastq_files(f, args):
# """ read fasta files of each sample and generate a seq_obj
# with the information of each unique sequence in each sample
#
# :param f: file containing the path for each fasta file and
# the name of the sample. Two column format with `tab` as field
# separator
#
# :returns: * :code:`seq_l`: is a list of seq_obj objects, containing
# the information of each sequence
# * :code:`sample_l`: is a list with the name of the samples
# (column two of the config file)
# """
# seq_l = {}
# sample_l = []
# idx = 1
# p = re.compile("^[ATCGNU]+$")
# with open(op.join(args.out, "stats_prepare.tsv"), 'w') as out_handle:
# for line1 in f:
# line1 = line1.strip()
# cols = line1.split("\t")
# # if not is_fastq(cols[0]):
# # raise ValueError("file is not fastq: %s" % cols[0])
# with open_fastq(cols[0]) as handle:
# sample_l.append(cols[1])
# total = added = 0
# line = handle.readline()
# while line:
# if line.startswith("@") or line.startswith(">"):
# seq = handle.readline().strip()
# if not p.match(seq):
# continue
# idx += 1
# total += 1
# keep = {}
# counts = int(re.search("x([0-9]+)", line.strip()).group(1))
# if is_fastq(cols[0]):
# handle.readline().strip()
# qual = handle.readline().strip()
# else:
# qual = "I" * len(seq)
# qual = qual[0:int(args.maxl)] if len(qual) > int(args.maxl) else qual
# seq = seq[0:int(args.maxl)] if len(seq) > int(args.maxl) else seq
# if counts > int(args.minc) and len(seq) > int(args.minl):
# added += 1
# if seq in keep:
# keep[seq].update(qual)
# else:
# keep[seq] = quality(qual)
# if seq not in seq_l:
# seq_l[seq] = sequence_unique(idx, seq)
# seq_l[seq].add_exp(cols[1], counts)
# seq_l[seq].quality = keep[seq].get()
# line=handle.readline()
# print("total\t%s\t%s" % (idx, cols[1]), file=out_handle, end="")
# print("added\t%s\t%s" % (len(seq_l), cols[1]), file=out_handle, end="")
# logger.info("%s: Total read %s ; Total added %s" % (cols[1], idx, len(seq_l)))
# return seq_l, sample_l
#
# def _create_matrix_uniq_seq(sample_l, seq_l, maout, out, min_shared):
# """ create matrix counts for each different sequence in all the fasta files
#
# :param sample_l: :code:`list_s` is the output of :code:`_read_fasta_files`
# :param seq_l: :code:`seq_s` is the output of :code:`_read_fasta_files`
# :param maout: is a file handler to write the matrix count information
# :param out: is a file handle to write the fasta file with unique sequences
#
# :returns: Null
# """
# skip = 0
# if int(min_shared) > len(sample_l):
# min_shared = len(sample_l)
# maout.write("id\tseq")
# for g in sample_l:
# maout.write("\t%s" % g)
# for s in seq_l.keys():
# seen = sum([1 for g in seq_l[s].group if seq_l[s].group[g] > 0])
# if seen < int(min_shared):
# skip += 1
# continue
# maout.write("\nseq_%s\t%s" % (seq_l[s].idx, seq_l[s].seq))
# for g in sample_l:
# if g in seq_l[s].group:
# maout.write("\t%s" % seq_l[s].group[g])
# else:
# maout.write("\t0")
# qual = "".join(seq_l[s].quality)
# out.write("@seq_%s\n%s\n+\n%s\n" % (seq_l[s].idx, seq_l[s].seq, qual))
# out.close()
# maout.close()
# logger.info("Total skipped due to --min-shared parameter (%s) : %s" % (min_shared, skip))
. Output only the next line. | _create_matrix_uniq_seq(list_s, seq_l, ma_out, seq_out, 1) |
Based on the snippet: <|code_start|> line = line.strip()
cols = line.split("\t")
name = int(cols[0].replace("seq_", ""))
seq = cols[1]
exp = {}
for i in range(len(samples)):
exp[samples[i]] = int(cols[i+2])
total[samples[i]] += int(cols[i+2])
ratio.append(np.array(list(exp.values())) / np.mean(list(exp.values())))
index = index+1
if name in seq_obj:
seq_obj[name].set_freq(exp)
seq_obj[name].set_seq(seq)
# new_s = sequence(seq, exp, index)
# seq_l[name] = new_s
df = pd.DataFrame(ratio)
df = df[(df.T != 0).all()]
size_factor = dict(zip(samples, df.median(axis=0)))
seq_obj = _normalize_seqs(seq_obj, size_factor)
return seq_obj, total, index
def parse_ma_file_raw(in_file):
"""
read seqs.ma file and create dict with
sequence object
"""
name = ""
index = 1
total = defaultdict(int)
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import defaultdict
from seqcluster.libs.classes import sequence
from seqcluster.libs.tool import _normalize_seqs
import pybedtools
import numpy as np
import pandas as pd
import seqcluster.libs.logger as mylog
and context (classes, functions, sometimes code) from other files:
# Path: seqcluster/libs/classes.py
# class sequence:
# """
# Object with information about sequences, counts, size, position, id and score
# """
# def __init__(self, seq_id, seq=None, freq=None):
# # self.seq = seq
# # self.freq = copy.deepcopy(freq)
# # self.norm_freq = copy.deepcopy(freq)
# self.pos = {}
# self.id = seq_id
# self.align = 0
# self.score = 0
# self.factor = {}
#
# def set_seq(self, seq):
# self.seq = seq
# self.len = len(seq)
#
# def set_freq(self, freq):
# self.freq = copy.deepcopy(freq)
# self.norm_freq = copy.deepcopy(freq)
#
# def add_pos(self, pos_id, pos):
# self.pos[pos_id] = pos
#
# def total(self):
# return sum(self.freq.values())
#
# Path: seqcluster/libs/tool.py
# def _normalize_seqs(s, t):
# """Normalize to DESeq2"""
# for ids in s:
# obj = s[ids]
# [obj.norm_freq.update({sample: 1.0 * obj.freq[sample] / t[sample]}) for sample in obj.norm_freq]
# s[ids] = obj
# return s
. Output only the next line. | seq_obj = defaultdict(sequence) |
Predict the next line for this snippet: <|code_start|> read seqs.ma file and create dict with
sequence object
"""
name = ""
index = 1
total = defaultdict(int)
ratio = list()
with open(in_file) as handle_in:
line = handle_in.readline().strip()
cols = line.split("\t")
samples = cols[2:]
for line in handle_in:
line = line.strip()
cols = line.split("\t")
name = int(cols[0].replace("seq_", ""))
seq = cols[1]
exp = {}
for i in range(len(samples)):
exp[samples[i]] = int(cols[i+2])
total[samples[i]] += int(cols[i+2])
ratio.append(np.array(list(exp.values())) / np.mean(list(exp.values())))
index = index+1
if name in seq_obj:
seq_obj[name].set_freq(exp)
seq_obj[name].set_seq(seq)
# new_s = sequence(seq, exp, index)
# seq_l[name] = new_s
df = pd.DataFrame(ratio)
df = df[(df.T != 0).all()]
size_factor = dict(zip(samples, df.median(axis=0)))
<|code_end|>
with the help of current file imports:
from collections import defaultdict
from seqcluster.libs.classes import sequence
from seqcluster.libs.tool import _normalize_seqs
import pybedtools
import numpy as np
import pandas as pd
import seqcluster.libs.logger as mylog
and context from other files:
# Path: seqcluster/libs/classes.py
# class sequence:
# """
# Object with information about sequences, counts, size, position, id and score
# """
# def __init__(self, seq_id, seq=None, freq=None):
# # self.seq = seq
# # self.freq = copy.deepcopy(freq)
# # self.norm_freq = copy.deepcopy(freq)
# self.pos = {}
# self.id = seq_id
# self.align = 0
# self.score = 0
# self.factor = {}
#
# def set_seq(self, seq):
# self.seq = seq
# self.len = len(seq)
#
# def set_freq(self, freq):
# self.freq = copy.deepcopy(freq)
# self.norm_freq = copy.deepcopy(freq)
#
# def add_pos(self, pos_id, pos):
# self.pos[pos_id] = pos
#
# def total(self):
# return sum(self.freq.values())
#
# Path: seqcluster/libs/tool.py
# def _normalize_seqs(s, t):
# """Normalize to DESeq2"""
# for ids in s:
# obj = s[ids]
# [obj.norm_freq.update({sample: 1.0 * obj.freq[sample] / t[sample]}) for sample in obj.norm_freq]
# s[ids] = obj
# return s
, which may contain function names, class names, or code. Output only the next line. | seq_obj = _normalize_seqs(seq_obj, size_factor) |
Using the snippet: <|code_start|>"""
sam2bed.py
Created by Aaron Quinlan on 2009-08-27.
Copyright (c) 2009 Aaron R. Quinlan. All rights reserved.
"""
def processSAM(line):
"""
Load a SAM file and convert each line to BED format.
"""
samLine = splitLine(line.strip())
return makeBED(samLine)
def makeBED(samFields):
samFlag = int(samFields.flag)
# Only create a BED entry if the read was aligned
if (not (samFlag & 0x0004)) and samFields.pos:
name = samFields.qname
seq = name.split("-")[1]
chrom = samFields.rname
start = str(int(samFields.pos))
end = str(int(samFields.pos) + len(seq) - 1)
strand = getStrand(samFlag)
# Write out the BED entry
<|code_end|>
, determine the next line of code. You have imports:
from seqcluster.libs.classes import bedaligned
and context (class names, function names, or code) available:
# Path: seqcluster/libs/classes.py
# class bedaligned:
# """
# Object that has the bed format attributes
# """
# def __init__(self,l):
# l = l.strip()
# cols = l.split("\t")
# self.chr = cols[0]
# self.start = cols[1]
# self.end = cols[2]
# self.name = cols[3]
# self.att = cols[4]
# self.strand = cols[5]
. Output only the next line. | return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" % (chrom, start, end, name, strand)) |
Here is a snippet: <|code_start|>
def get_fasta(bed_file, ref, out_fa):
"""Run bedtools to get fasta from bed file"""
cmd = "bedtools getfasta -s -fi {ref} -bed {bed_file} -fo {out_fa}"
run(cmd.format(**locals()))
def get_loci_fasta(loci, out_fa, ref):
"""get fasta from precursor"""
if not find_cmd("bedtools"):
raise ValueError("Not bedtools installed")
with make_temp_directory() as temp:
bed_file = os.path.join(temp, "file.bed")
for nc, loci in loci.iteritems():
for l in loci:
with open(bed_file, 'w') as bed_handle:
logger.debug("get_fasta: loci %s" % l)
nc, c, s, e, st = l
print("{0}\t{1}\t{2}\t{3}\t{3}\t{4}".format(c, s, e, nc, st), file=bed_handle)
get_fasta(bed_file, ref, out_fa)
return out_fa
def read_alignment(out_sam, loci, seqs, out_file):
"""read which seqs map to which loci and
return a tab separated file"""
hits = defaultdict(list)
with open(out_file, "w") as out_handle:
samfile = pysam.Samfile(out_sam, "r")
for a in samfile.fetch():
if not a.is_unmapped:
nm = int([t[1] for t in a.tags if t[0] == "NM"][0])
<|code_end|>
. Write the next line using the current file imports:
from collections import defaultdict
from seqcluster.libs.sam2bed import makeBED
from seqcluster.libs.do import find_cmd, run
from Bio import pairwise2
from Bio.Seq import Seq
import json, itertools
import tempfile, os, contextlib, shutil
import operator
import logging
import pysam
import pybedtools
and context from other files:
# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
# samFlag = int(samFields.flag)
# # Only create a BED entry if the read was aligned
# if (not (samFlag & 0x0004)) and samFields.pos:
# name = samFields.qname
# seq = name.split("-")[1]
# chrom = samFields.rname
# start = str(int(samFields.pos))
# end = str(int(samFields.pos) + len(seq) - 1)
# strand = getStrand(samFlag)
# # Write out the BED entry
# return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" % (chrom, start, end, name, strand))
# else:
# return False
#
# Path: seqcluster/libs/do.py
# def find_cmd(cmd):
# try:
# return subprocess.check_output(["which", cmd]).strip()
# except subprocess.CalledProcessError:
# return None
#
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
, which may include functions, classes, or code. Output only the next line. | a = makeBED(a) |
Given the following code snippet before the placeholder: <|code_start|> """get all sequences from on cluster"""
seqs1 = data[c1]['seqs']
seqs2 = data[c2]['seqs']
seqs = list(set(seqs1 + seqs2))
names = []
for s in seqs:
if s in seqs1 and s in seqs2:
names.append("both")
elif s in seqs1:
names.append(c1)
else:
names.append(c2)
return seqs, names
def get_precursors_from_cluster(c1, c2, data):
loci1 = data[c1]['loci']
loci2 = data[c2]['loci']
return {c1:loci1, c2:loci2}
def map_to_precursors(seqs, names, loci, out_file, args):
"""map sequences to precursors with razers3"""
with make_temp_directory() as temp:
pre_fasta = os.path.join(temp, "pre.fa")
seqs_fasta = os.path.join(temp, "seqs.fa")
out_sam = os.path.join(temp, "out.sam")
pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
out_precursor_file = out_file.replace("tsv", "fa")
seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)
# print(open(pre_fasta).read().split("\n")[1])
<|code_end|>
, predict the next line using imports from the current file:
from collections import defaultdict
from seqcluster.libs.sam2bed import makeBED
from seqcluster.libs.do import find_cmd, run
from Bio import pairwise2
from Bio.Seq import Seq
import json, itertools
import tempfile, os, contextlib, shutil
import operator
import logging
import pysam
import pybedtools
and context including class names, function names, and sometimes code from other files:
# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
# samFlag = int(samFields.flag)
# # Only create a BED entry if the read was aligned
# if (not (samFlag & 0x0004)) and samFields.pos:
# name = samFields.qname
# seq = name.split("-")[1]
# chrom = samFields.rname
# start = str(int(samFields.pos))
# end = str(int(samFields.pos) + len(seq) - 1)
# strand = getStrand(samFlag)
# # Write out the BED entry
# return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" % (chrom, start, end, name, strand))
# else:
# return False
#
# Path: seqcluster/libs/do.py
# def find_cmd(cmd):
# try:
# return subprocess.check_output(["which", cmd]).strip()
# except subprocess.CalledProcessError:
# return None
#
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
. Output only the next line. | if find_cmd("razers3"): |
Predict the next line after this snippet: <|code_start|> seqs2 = data[c2]['seqs']
seqs = list(set(seqs1 + seqs2))
names = []
for s in seqs:
if s in seqs1 and s in seqs2:
names.append("both")
elif s in seqs1:
names.append(c1)
else:
names.append(c2)
return seqs, names
def get_precursors_from_cluster(c1, c2, data):
loci1 = data[c1]['loci']
loci2 = data[c2]['loci']
return {c1:loci1, c2:loci2}
def map_to_precursors(seqs, names, loci, out_file, args):
"""map sequences to precursors with razers3"""
with make_temp_directory() as temp:
pre_fasta = os.path.join(temp, "pre.fa")
seqs_fasta = os.path.join(temp, "seqs.fa")
out_sam = os.path.join(temp, "out.sam")
pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
out_precursor_file = out_file.replace("tsv", "fa")
seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)
# print(open(pre_fasta).read().split("\n")[1])
if find_cmd("razers3"):
cmd = "razers3 -dr 2 -i 80 -rr 90 -f -o {out_sam} {temp}/pre.fa {seqs_fasta}"
<|code_end|>
using the current file's imports:
from collections import defaultdict
from seqcluster.libs.sam2bed import makeBED
from seqcluster.libs.do import find_cmd, run
from Bio import pairwise2
from Bio.Seq import Seq
import json, itertools
import tempfile, os, contextlib, shutil
import operator
import logging
import pysam
import pybedtools
and any relevant context from other files:
# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
# samFlag = int(samFields.flag)
# # Only create a BED entry if the read was aligned
# if (not (samFlag & 0x0004)) and samFields.pos:
# name = samFields.qname
# seq = name.split("-")[1]
# chrom = samFields.rname
# start = str(int(samFields.pos))
# end = str(int(samFields.pos) + len(seq) - 1)
# strand = getStrand(samFlag)
# # Write out the BED entry
# return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" % (chrom, start, end, name, strand))
# else:
# return False
#
# Path: seqcluster/libs/do.py
# def find_cmd(cmd):
# try:
# return subprocess.check_output(["which", cmd]).strip()
# except subprocess.CalledProcessError:
# return None
#
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# """Run the provided command, logging details and checking for errors.
# """
# try:
# logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
# _do_run(cmd, checks, log_stdout)
# except:
# if log_error:
# logger.info("error at command")
# raise
. Output only the next line. | run(cmd.format(**locals())) |
Given the code snippet: <|code_start|>from __future__ import print_function
logger = logging.getLogger('seqbuster')
def collapse(in_file):
"""collapse identical sequences and keep Q"""
keep = Counter()
with open_fastq(in_file) as handle:
line = handle.readline()
while line:
if line.startswith("@"):
if line.find("UMI") > -1:
logger.info("Find UMI tags in read names, collapsing by UMI.")
return collapse_umi(in_file)
seq = handle.readline().strip()
handle.readline()
qual = handle.readline().strip()
if seq in keep:
keep[seq].update(qual)
else:
<|code_end|>
, generate the next line using the imports in this file:
import os
import gzip
import re
import logging
from collections import Counter, defaultdict
from seqcluster.libs.classes import quality, umi
from itertools import product
and context (functions, classes, or occasionally code) from other files:
# Path: seqcluster/libs/classes.py
# class quality:
#
# def __init__(self, q):
# self.qual = [ord(value) for value in q]
# self.times = 1
#
# def update(self, q, counts = 1):
# now = self.qual
# q = [ord(value) for value in q]
# self.qual = [x + y for x, y in zip(now, q)]
# self.times += counts
#
# def get(self):
# average = np.array(self.qual)/self.times
# return [str(unichr(int(char))) for char in average]
#
# class umi:
#
# def __init__(self, seq):
# self.seq = defaultdict(list)
# self.times = 0
# self.update(seq)
#
# def update(self, seq, counts = 1):
# for pos, nt in enumerate(seq):
# self.seq[pos].append(nt)
# self.times += counts
#
# def get(self):
# seq = ""
# for pos in sorted(self.seq.keys()):
# lst = self.seq[pos]
# seq += max(lst, key=lst.count)
# return seq
. Output only the next line. | keep[seq] = quality(qual) |
Continue the code snippet: <|code_start|> keep[seq].update(qual)
else:
keep[seq] = quality(qual)
if line.startswith(">"):
seq = handle.readline().strip()
if seq not in keep:
keep[seq] = quality("".join(["I"] * len(seq)))
else:
keep[seq].update("".join(["I"] * len(seq)))
line = handle.readline()
logger.info("Sequences loaded: %s" % len(keep))
return keep
def collapse_umi(in_file):
"""collapse reads using UMI tags"""
keep = defaultdict(dict)
with open_fastq(in_file) as handle:
line = handle.readline();
while line:
if line.startswith("@"):
m = re.search('UMI_([ATGC]*)', line.strip())
umis = m.group(0)
seq = handle.readline().strip()
handle.readline()
qual = handle.readline().strip()
if (umis, seq) in keep:
keep[(umis, seq)][1].update(qual)
keep[(umis, seq)][0].update(seq)
else:
<|code_end|>
. Use current file imports:
import os
import gzip
import re
import logging
from collections import Counter, defaultdict
from seqcluster.libs.classes import quality, umi
from itertools import product
and context (classes, functions, or code) from other files:
# Path: seqcluster/libs/classes.py
# class quality:
#
# def __init__(self, q):
# self.qual = [ord(value) for value in q]
# self.times = 1
#
# def update(self, q, counts = 1):
# now = self.qual
# q = [ord(value) for value in q]
# self.qual = [x + y for x, y in zip(now, q)]
# self.times += counts
#
# def get(self):
# average = np.array(self.qual)/self.times
# return [str(unichr(int(char))) for char in average]
#
# class umi:
#
# def __init__(self, seq):
# self.seq = defaultdict(list)
# self.times = 0
# self.update(seq)
#
# def update(self, seq, counts = 1):
# for pos, nt in enumerate(seq):
# self.seq[pos].append(nt)
# self.times += counts
#
# def get(self):
# seq = ""
# for pos in sorted(self.seq.keys()):
# lst = self.seq[pos]
# seq += max(lst, key=lst.count)
# return seq
. Output only the next line. | keep[(umis, seq)] = [umi(seq), quality(qual)] |
Here is a snippet: <|code_start|>def chdir(new_dir):
"""
stolen from bcbio.
Context manager to temporarily change to a new directory.
http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/
"""
cur_dir = os.getcwd()
_mkdir(new_dir)
os.chdir(new_dir)
try:
yield
finally:
os.chdir(cur_dir)
def _get_miraligner():
opts = "-Xms750m -Xmx4g"
try:
tool = "miraligner"
ret = os.system(tool)
if ret != 0:
raise SystemExit("%s not installed." % tool)
except SystemExit:
tool = None
print("miraligner not found. I'll try to download it.")
pass
if not tool:
if not utils.file_exists(op.abspath("miraligner.jar")):
url = "https://raw.githubusercontent.com/lpantano/seqbuster/miraligner/modules/miraligner/miraligner.jar"
cmd = ["wget", "-O miraligner.jar", "--no-check-certificate", url]
<|code_end|>
. Write the next line using the current file imports:
import os.path as op
import os
import sys
import subprocess
import contextlib
import yaml
import bcbio
import bcbio.install as install
from argparse import ArgumentParser
from seqcluster.libs import do, utils
from bcbio import install as bcb
from bcbio import install as bcb
and context from other files:
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# def find_bash():
# def find_cmd(cmd):
# def _normalize_cmd_args(cmd):
# def _do_run(cmd, checks, log_stdout=False):
#
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
, which may include functions, classes, or code. Output only the next line. | do.run(" ".join(cmd), "Download miraligner.") |
Predict the next line for this snippet: <|code_start|> raise
@contextlib.contextmanager
def chdir(new_dir):
"""
stolen from bcbio.
Context manager to temporarily change to a new directory.
http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/
"""
cur_dir = os.getcwd()
_mkdir(new_dir)
os.chdir(new_dir)
try:
yield
finally:
os.chdir(cur_dir)
def _get_miraligner():
opts = "-Xms750m -Xmx4g"
try:
tool = "miraligner"
ret = os.system(tool)
if ret != 0:
raise SystemExit("%s not installed." % tool)
except SystemExit:
tool = None
print("miraligner not found. I'll try to download it.")
pass
if not tool:
<|code_end|>
with the help of current file imports:
import os.path as op
import os
import sys
import subprocess
import contextlib
import yaml
import bcbio
import bcbio.install as install
from argparse import ArgumentParser
from seqcluster.libs import do, utils
from bcbio import install as bcb
from bcbio import install as bcb
and context from other files:
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
# log_stdout=False):
# def find_bash():
# def find_cmd(cmd):
# def _normalize_cmd_args(cmd):
# def _do_run(cmd, checks, log_stdout=False):
#
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
, which may contain function names, class names, or code. Output only the next line. | if not utils.file_exists(op.abspath("miraligner.jar")): |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger('stats')
def stats(args):
"""Create stats from the analysis
"""
logger.info("Reading sequences")
<|code_end|>
with the help of current file imports:
import os
import pysam
import logging
import json
from seqcluster.libs.inputs import parse_ma_file
from seqcluster.libs.sam2bed import makeBED
from collections import defaultdict, Counter
and context from other files:
# Path: seqcluster/libs/inputs.py
# def parse_ma_file(seq_obj, in_file):
# """
# read seqs.ma file and create dict with
# sequence object
# """
# name = ""
# index = 1
# total = defaultdict(int)
# ratio = list()
# with open(in_file) as handle_in:
# line = handle_in.readline().strip()
# cols = line.split("\t")
# samples = cols[2:]
# for line in handle_in:
# line = line.strip()
# cols = line.split("\t")
# name = int(cols[0].replace("seq_", ""))
# seq = cols[1]
# exp = {}
# for i in range(len(samples)):
# exp[samples[i]] = int(cols[i+2])
# total[samples[i]] += int(cols[i+2])
# ratio.append(np.array(list(exp.values())) / np.mean(list(exp.values())))
# index = index+1
# if name in seq_obj:
# seq_obj[name].set_freq(exp)
# seq_obj[name].set_seq(seq)
# # new_s = sequence(seq, exp, index)
# # seq_l[name] = new_s
# df = pd.DataFrame(ratio)
# df = df[(df.T != 0).all()]
# size_factor = dict(zip(samples, df.median(axis=0)))
# seq_obj = _normalize_seqs(seq_obj, size_factor)
# return seq_obj, total, index
#
# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
# samFlag = int(samFields.flag)
# # Only create a BED entry if the read was aligned
# if (not (samFlag & 0x0004)) and samFields.pos:
# name = samFields.qname
# seq = name.split("-")[1]
# chrom = samFields.rname
# start = str(int(samFields.pos))
# end = str(int(samFields.pos) + len(seq) - 1)
# strand = getStrand(samFlag)
# # Write out the BED entry
# return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" % (chrom, start, end, name, strand))
# else:
# return False
, which may contain function names, class names, or code. Output only the next line. | data = parse_ma_file(args.ma) |
Next line prediction: <|code_start|>
logger = logging.getLogger('stats')
def stats(args):
"""Create stats from the analysis
"""
logger.info("Reading sequences")
data = parse_ma_file(args.ma)
logger.info("Get sequences from sam")
is_align = _read_sam(args.sam)
is_json, is_db = _read_json(args.json)
res = _summarise_sam(data, is_align, is_json, is_db)
_write_suma(res, os.path.join(args.out, "stats_align.dat"))
logger.info("Done")
def _read_sam(sam):
is_align = set()
with pysam.Samfile(sam, "rb") as samfile:
for a in samfile.fetch():
<|code_end|>
. Use current file imports:
(import os
import pysam
import logging
import json
from seqcluster.libs.inputs import parse_ma_file
from seqcluster.libs.sam2bed import makeBED
from collections import defaultdict, Counter)
and context including class names, function names, or small code snippets from other files:
# Path: seqcluster/libs/inputs.py
# def parse_ma_file(seq_obj, in_file):
# """
# read seqs.ma file and create dict with
# sequence object
# """
# name = ""
# index = 1
# total = defaultdict(int)
# ratio = list()
# with open(in_file) as handle_in:
# line = handle_in.readline().strip()
# cols = line.split("\t")
# samples = cols[2:]
# for line in handle_in:
# line = line.strip()
# cols = line.split("\t")
# name = int(cols[0].replace("seq_", ""))
# seq = cols[1]
# exp = {}
# for i in range(len(samples)):
# exp[samples[i]] = int(cols[i+2])
# total[samples[i]] += int(cols[i+2])
# ratio.append(np.array(list(exp.values())) / np.mean(list(exp.values())))
# index = index+1
# if name in seq_obj:
# seq_obj[name].set_freq(exp)
# seq_obj[name].set_seq(seq)
# # new_s = sequence(seq, exp, index)
# # seq_l[name] = new_s
# df = pd.DataFrame(ratio)
# df = df[(df.T != 0).all()]
# size_factor = dict(zip(samples, df.median(axis=0)))
# seq_obj = _normalize_seqs(seq_obj, size_factor)
# return seq_obj, total, index
#
# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
# samFlag = int(samFields.flag)
# # Only create a BED entry if the read was aligned
# if (not (samFlag & 0x0004)) and samFields.pos:
# name = samFields.qname
# seq = name.split("-")[1]
# chrom = samFields.rname
# start = str(int(samFields.pos))
# end = str(int(samFields.pos) + len(seq) - 1)
# strand = getStrand(samFlag)
# # Write out the BED entry
# return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" % (chrom, start, end, name, strand))
# else:
# return False
. Output only the next line. | a = makeBED(a) |
Continue the code snippet: <|code_start|> input:
template ../header.html
parent app/app/index.html
output:
app/header.html
"""
relative_path = re.compile('(./|../)', re.IGNORECASE)
relative_dir = re.compile('([^/\s]{1,}/)', re.IGNORECASE)
real_name = re.compile('([^/\s]{1,}$)')
def join_path(self, template, parent):
t_group = self.relative_path.findall(template)
p_group = self.relative_dir.findall(parent)
t_group_length = len(t_group)
template_name = template
#
real_template_path = p_group
if t_group_length:
template_name = self.real_name.match(
template, template.rfind('/') + 1).group()
real_template_path = p_group[0:0 - t_group_length]
real_template_path.append(template_name)
return ''.join(real_template_path)
def turbo_jinja2(func):
<|code_end|>
. Use current file imports:
import re
import functools
from turbo.conf import app_config
from jinja2 import Environment, FileSystemLoader
and context (classes, functions, or code) from other files:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
. Output only the next line. | _jinja2_env = Jinja2Environment(loader=FileSystemLoader(app_config.web_application_setting[ |
Next line prediction: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
sess = requests.session()
sess.keep_alive = False
app_config.app_name = 'app_test'
app_config.app_setting['template'] = 'jinja2'
tmp_source = tempfile.mkdtemp()
TEMPLATE_PATH = os.path.join(tmp_source, "templates")
app_config.web_application_setting = {
'xsrf_cookies': False,
'cookie_secret': 'adasfd',
'template_path': TEMPLATE_PATH,
'debug': True,
}
<|code_end|>
. Use current file imports:
(import multiprocessing
import os
import shutil
import signal
import socket
import tempfile
import time
import requests
from turbo import app
from turbo import register
from turbo.conf import app_config
from turbo.template import turbo_jinja2
from util import unittest)
and context including class names, function names, or small code snippets from other files:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/template.py
# def turbo_jinja2(func):
# _jinja2_env = Jinja2Environment(loader=FileSystemLoader(app_config.web_application_setting[
# 'template_path']), auto_reload=app_config.web_application_setting['debug'])
#
# @functools.wraps(func)
# def wrapper(self, template_name, **kwargs):
# template = _jinja2_env.get_template(
# ('%s%s') % (self.template_path, template_name))
# return template.render(handler=self, request=self.request, xsrf_form_html=self.xsrf_form_html(),
# context=self.get_context(), **kwargs)
#
# return wrapper
. Output only the next line. | class HomeHandler(app.BaseHandler): |
Given snippet: <|code_start|>sess = requests.session()
sess.keep_alive = False
app_config.app_name = 'app_test'
app_config.app_setting['template'] = 'jinja2'
tmp_source = tempfile.mkdtemp()
TEMPLATE_PATH = os.path.join(tmp_source, "templates")
app_config.web_application_setting = {
'xsrf_cookies': False,
'cookie_secret': 'adasfd',
'template_path': TEMPLATE_PATH,
'debug': True,
}
class HomeHandler(app.BaseHandler):
def get(self):
self.render('index.html')
@turbo_jinja2
def render_string(self, *args, **kwargs):
pass
PID = None
URL = None
def run_server(port):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import multiprocessing
import os
import shutil
import signal
import socket
import tempfile
import time
import requests
from turbo import app
from turbo import register
from turbo.conf import app_config
from turbo.template import turbo_jinja2
from util import unittest
and context:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/template.py
# def turbo_jinja2(func):
# _jinja2_env = Jinja2Environment(loader=FileSystemLoader(app_config.web_application_setting[
# 'template_path']), auto_reload=app_config.web_application_setting['debug'])
#
# @functools.wraps(func)
# def wrapper(self, template_name, **kwargs):
# template = _jinja2_env.get_template(
# ('%s%s') % (self.template_path, template_name))
# return template.render(handler=self, request=self.request, xsrf_form_html=self.xsrf_form_html(),
# context=self.get_context(), **kwargs)
#
# return wrapper
which might include code, classes, or functions. Output only the next line. | register.register_url('/', HomeHandler) |
Based on the snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
sess = requests.session()
sess.keep_alive = False
<|code_end|>
, predict the immediate next line with the help of imports:
import multiprocessing
import os
import shutil
import signal
import socket
import tempfile
import time
import requests
from turbo import app
from turbo import register
from turbo.conf import app_config
from turbo.template import turbo_jinja2
from util import unittest
and context (classes, functions, sometimes code) from other files:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/template.py
# def turbo_jinja2(func):
# _jinja2_env = Jinja2Environment(loader=FileSystemLoader(app_config.web_application_setting[
# 'template_path']), auto_reload=app_config.web_application_setting['debug'])
#
# @functools.wraps(func)
# def wrapper(self, template_name, **kwargs):
# template = _jinja2_env.get_template(
# ('%s%s') % (self.template_path, template_name))
# return template.render(handler=self, request=self.request, xsrf_form_html=self.xsrf_form_html(),
# context=self.get_context(), **kwargs)
#
# return wrapper
. Output only the next line. | app_config.app_name = 'app_test' |
Given snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
sess = requests.session()
sess.keep_alive = False
app_config.app_name = 'app_test'
app_config.app_setting['template'] = 'jinja2'
tmp_source = tempfile.mkdtemp()
TEMPLATE_PATH = os.path.join(tmp_source, "templates")
app_config.web_application_setting = {
'xsrf_cookies': False,
'cookie_secret': 'adasfd',
'template_path': TEMPLATE_PATH,
'debug': True,
}
class HomeHandler(app.BaseHandler):
def get(self):
self.render('index.html')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import multiprocessing
import os
import shutil
import signal
import socket
import tempfile
import time
import requests
from turbo import app
from turbo import register
from turbo.conf import app_config
from turbo.template import turbo_jinja2
from util import unittest
and context:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/template.py
# def turbo_jinja2(func):
# _jinja2_env = Jinja2Environment(loader=FileSystemLoader(app_config.web_application_setting[
# 'template_path']), auto_reload=app_config.web_application_setting['debug'])
#
# @functools.wraps(func)
# def wrapper(self, template_name, **kwargs):
# template = _jinja2_env.get_template(
# ('%s%s') % (self.template_path, template_name))
# return template.render(handler=self, request=self.request, xsrf_form_html=self.xsrf_form_html(),
# context=self.get_context(), **kwargs)
#
# return wrapper
which might include code, classes, or functions. Output only the next line. | @turbo_jinja2 |
Given the code snippet: <|code_start|># -*- coding:utf-8 -*-
# todo change name
class BaseModel(turbo.model.BaseModel):
package_space = globals()
def __init__(self, db_name='test'):
super(BaseModel, self).__init__(db_name, _MONGO_DB_MAPPING)
def get_count(self, spec=None):
return self.find(spec=spec).count()
class SqlBaseModel(object):
def __init__(self, db_name='test'):
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from bson.objectid import ObjectId
from pymongo import ASCENDING, DESCENDING
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from .settings import (
MONGO_DB_MAPPING as _MONGO_DB_MAPPING,
DB_ENGINE_MAPPING as _DB_ENGINE_MAPPING,
)
import time
import turbo.model
import turbo.util
import turbo_motor.model
and context (functions, classes, or occasionally code) from other files:
# Path: demos/models/settings.py
# MONGO_DB_MAPPING = {
# 'db': {
# 'test': _test,
# 'user': _user,
# 'tag': _tag,
# },
# 'db_file': {
# 'test': _test_files,
# 'user': _user_files,
# }
# }
#
# DB_ENGINE_MAPPING = {
# 'blog': blog_engine,
# }
. Output only the next line. | engine = _DB_ENGINE_MAPPING[db_name] |
Given the code snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
class _HelperObjectDict(dict):
def __setitem__(self, name, value):
return super(_HelperObjectDict, self).setdefault(name, value)
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise ValueError(name)
def install_helper(installing_helper_list, package_space):
for item in installing_helper_list:
# db model package
package = import_object('.'.join(['helpers', item]), package_space)
package_space[item] = _HelperObjectDict()
# all py files included by package
all_modules = getattr(package, '__all__', [])
for m in all_modules:
try:
module = import_object(
'.'.join(['helpers', item, m]), package_space)
except:
<|code_end|>
, generate the next line using the imports in this file:
import sys
from turbo.log import helper_log
from turbo.util import import_object, camel_to_underscore
and context (functions, classes, or occasionally code) from other files:
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# def import_object(name, package_space=None):
# if name.count('.') == 0:
# return __import__(name, package_space, None)
#
# parts = name.split('.')
# obj = __import__('.'.join(parts[:-1]),
# package_space, None, [str(parts[-1])], 0)
# try:
# return getattr(obj, parts[-1])
# except AttributeError:
# raise ImportError("No module named %s" % parts[-1])
#
# def camel_to_underscore(name):
# """
# convert CamelCase style to under_score_case
# """
# as_list = []
# length = len(name)
# for index, i in enumerate(name):
# if index != 0 and index != length - 1 and i.isupper():
# as_list.append('_%s' % i.lower())
# else:
# as_list.append(i.lower())
#
# return ''.join(as_list)
. Output only the next line. | helper_log.error('module helpers.%s.%s Import Error' % |
Next line prediction: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
class _HelperObjectDict(dict):
def __setitem__(self, name, value):
return super(_HelperObjectDict, self).setdefault(name, value)
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise ValueError(name)
def install_helper(installing_helper_list, package_space):
for item in installing_helper_list:
# db model package
<|code_end|>
. Use current file imports:
(import sys
from turbo.log import helper_log
from turbo.util import import_object, camel_to_underscore)
and context including class names, function names, or small code snippets from other files:
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# def import_object(name, package_space=None):
# if name.count('.') == 0:
# return __import__(name, package_space, None)
#
# parts = name.split('.')
# obj = __import__('.'.join(parts[:-1]),
# package_space, None, [str(parts[-1])], 0)
# try:
# return getattr(obj, parts[-1])
# except AttributeError:
# raise ImportError("No module named %s" % parts[-1])
#
# def camel_to_underscore(name):
# """
# convert CamelCase style to under_score_case
# """
# as_list = []
# length = len(name)
# for index, i in enumerate(name):
# if index != 0 and index != length - 1 and i.isupper():
# as_list.append('_%s' % i.lower())
# else:
# as_list.append(i.lower())
#
# return ''.join(as_list)
. Output only the next line. | package = import_object('.'.join(['helpers', item]), package_space) |
Next line prediction: <|code_start|> def __setitem__(self, name, value):
return super(_HelperObjectDict, self).setdefault(name, value)
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise ValueError(name)
def install_helper(installing_helper_list, package_space):
for item in installing_helper_list:
# db model package
package = import_object('.'.join(['helpers', item]), package_space)
package_space[item] = _HelperObjectDict()
# all py files included by package
all_modules = getattr(package, '__all__', [])
for m in all_modules:
try:
module = import_object(
'.'.join(['helpers', item, m]), package_space)
except:
helper_log.error('module helpers.%s.%s Import Error' %
(item, m), exc_info=True)
sys.exit(0)
for model_name in getattr(module, 'MODEL_SLOTS', []):
model = getattr(module, model_name, None)
if model:
camel_name = model.__name__
<|code_end|>
. Use current file imports:
(import sys
from turbo.log import helper_log
from turbo.util import import_object, camel_to_underscore)
and context including class names, function names, or small code snippets from other files:
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# def import_object(name, package_space=None):
# if name.count('.') == 0:
# return __import__(name, package_space, None)
#
# parts = name.split('.')
# obj = __import__('.'.join(parts[:-1]),
# package_space, None, [str(parts[-1])], 0)
# try:
# return getattr(obj, parts[-1])
# except AttributeError:
# raise ImportError("No module named %s" % parts[-1])
#
# def camel_to_underscore(name):
# """
# convert CamelCase style to under_score_case
# """
# as_list = []
# length = len(name)
# for index, i in enumerate(name):
# if index != 0 and index != length - 1 and i.isupper():
# as_list.append('_%s' % i.lower())
# else:
# as_list.append(i.lower())
#
# return ''.join(as_list)
. Output only the next line. | underscore_name = camel_to_underscore(camel_name) |
Given snippet: <|code_start|> return outwrapper
class CallFuncAsAttr(object):
class __CallObject(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __init__(self, file_attr):
name = file_attr
filepath = os.path.abspath(file_attr)
if os.path.isfile(filepath):
name, ext = os.path.splitext(os.path.basename(filepath))
setattr(self, self._name, {})
_mutation[name] = weakref.ref(self)
@property
def __get_func(self):
return getattr(self, self._name)
def register(self, func):
if not inspect.isfunction(func):
raise TypeError("argument expect function, now is '%s'" % func)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import functools
import inspect
import weakref
from turbo.util import get_func_name
and context:
# Path: turbo/util.py
# def get_func_name(func):
# name = getattr(func, 'func_name', None)
# if not name:
# name = getattr(func, '__name__', None)
# return name
which might include code, classes, or functions. Output only the next line. | name = get_func_name(func) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding:utf-8 -*-
from __future__ import (
absolute_import,
division,
print_function,
with_statement
)
sys.path.insert(
0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def main():
<|code_end|>
, predict the next line using imports from the current file:
import sys
import os
from tests.util import unittest # noqa E402
and context including class names, function names, and sometimes code from other files:
# Path: tests/util.py
# def port_is_used(port):
# def get_free_tcp_port():
. Output only the next line. | testSuite = unittest.TestSuite() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.