code
stringlengths
17
6.64M
def get_multi_gpu_models_from_hist(hist_idx, hist, input_state, output_state, state_space, model_compile_dict): 'Given a set of indcies, build a dictionary of\n models from history file\n ' model_dict = {} for idx in hist_idx: model_state_str = [hist.iloc[idx][('L%i' % (i + 1))] for i in ran...
def match_quantity(q, p, num_slice=10, num_sample_per_slice=None, replace=False, random_state=777): 'from p samples a new distribution that matches q\n\n Returns:\n np.array: sampled idx in p\n ' np.random.seed(random_state) if (not num_sample_per_slice): num_sample_per_slice = int(np...
class InfoConstraint(Constraint): def __call__(self, w): w = (w * K.cast(K.greater_equal(w, 0), K.floatx())) w = (w * (2 / K.maximum(K.sum(w, axis=1, keepdims=True), 2))) return w
class NegativeConstraint(Constraint): def __call__(self, w): w = (w * K.cast(K.less_equal(w, 0), K.floatx())) return w
def filter_reg(w, lambda_filter, lambda_l1): filter_penalty = (lambda_filter * K.sum(K.l2_normalize(K.sum(w, axis=0), axis=1))) weight_penalty = (lambda_l1 * K.sum(K.abs(w))) return (filter_penalty + weight_penalty)
def pos_reg(w, lambda_pos, filter_len): location_lambda = (K.cast(K.concatenate([K.arange((filter_len / 2), stop=0, step=(- 1)), K.arange(start=1, stop=((filter_len / 2) + 1))]), 'float32') * (lambda_pos / (filter_len / 2))) location_penalty = K.sum((location_lambda * K.sum(K.abs(w), axis=(0, 2, 3)))) ret...
def total_reg(w, lambda_filter, lambda_l1, lambda_pos, filter_len): return (filter_reg(w, lambda_filter, lambda_l1) + pos_reg(w, lambda_pos, filter_len))
def Layer_deNovo(filters, kernel_size, strides=1, padding='valid', activation='sigmoid', lambda_pos=0.003, lambda_l1=0.003, lambda_filter=1e-08, name='denovo'): return Conv2D(filters, (4, kernel_size), strides=strides, padding=padding, activation=activation, kernel_initializer=normal(0, 0.5), bias_initializer='ze...
class DenovoConvMotif(Layer): '\n De Novo motif learning Convolutional layers, as described in\n https://github.com/mPloenzke/learnMotifs/blob/master/R/layer_denovoMotif.R\n by Matthew Ploenzke, Raphael Irrizarry. Accessed 2018.12.05\n ' def __init__(self, output_dim, filters, filter_len, lambda...
def sparsek_vec(x): convmap = x shape = tf.shape(convmap) nb = shape[0] nl = shape[1] tk = tf.cast((0.2 * tf.cast(nl, tf.float32)), tf.int32) convmapr = tf.reshape(convmap, tf.stack([nb, (- 1)])) (th, _) = tf.nn.top_k(convmapr, tk) th1 = tf.slice(th, [0, (tk - 1)], [(- 1), 1]) thr ...
def get_features_in_block(spatial_outputs, f_kmean_assign): n_clusters = (np.max(f_kmean_assign) + 1) block_ops = [] for c in range(n_clusters): i = np.where((f_kmean_assign == c))[0] block_ops.append(tf.gather(spatial_outputs, indices=i, axis=(- 1), batch_dims=0)) return block_ops
class CnnFeatureModel(): '\n Convert the last Conv layer in a Cnn model as features to a Dnn model\n Keep all Tensors for future Operations\n ' def __init__(self, base_model, session, feature_assign_fn, feature_map_orientation='channels_last', x=None, y=None, batch_size=128, target_layer=None, train...
class MultiIOArchitecture(): def __init__(self, num_layers, num_inputs, num_outputs): self.num_layers = num_layers self.num_inputs = num_inputs self.num_outputs = num_outputs def decode(self, arc_seq): start_idx = 0 operations = [] inputs = [] skips = ...
class ResConvNetArchitecture(): def __init__(self, model_space): 'ResConvNetArchitecture is a class for decoding and encoding neural architectures of convolutional neural\n networks with residual connections\n\n Parameters\n ----------\n model_space : amber.architect.ModelSpac...
def get_dag(arg): "Getter method for getting a DAG class from a string\n\n DAG refers to the underlying tensor computation graphs for child models. Whenever possible, we prefer to use Keras\n Model API to get the job done. For ENAS, the parameter-sharing scheme is implemented by tensorflow.\n\n Parameter...
def get_layer(x, state, with_bn=False): 'Getter method for a Keras layer, including native Keras implementation and custom layers that are not included in\n Keras.\n\n Parameters\n ----------\n x : tf.keras.layers or None\n The input Keras layer\n state : amber.architect.Operation\n T...
class ComputationNode(): def __init__(self, operation, node_name, merge_op=Concatenate): assert (type(operation) is State), ('Expect operation is of type amber.architect.State, got %s' % type(operation)) self.operation = operation self.node_name = node_name self.merge_op = merge_o...
class DAG(): def __init__(self, arc_seq, num_layers, model_space, input_node, output_node, with_skip_connection=True, with_input_blocks=True): assert all([(not x.is_built) for x in input_node]), 'input_node must not have been built' if (type(output_node) is list): assert all([(not x.i...
class InputBlockDAG(DAG): def __init__(self, add_output=True, *args, **kwargs): super().__init__(*args, **kwargs) assert self.with_input_blocks, '`InputBlockDAG` class only handles `with_input_blocks=True`' self.added_output_nodes = [] self.add_output = add_output def _build_...
class InputBlockAuxLossDAG(InputBlockDAG): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) assert self.add_output, 'InputBlockAuxLossDAG must have `add_output=True`' self.input_block_loss_mapping = {} def _build_dag(self): assert (type(self.input_node) ...
class EnasAnnDAG(): def __init__(self, model_space, input_node, output_node, model_compile_dict, session, l1_reg=0.0, l2_reg=0.0, with_skip_connection=True, with_input_blocks=True, with_output_blocks=False, controller=None, feature_model=None, feature_model_trainable=None, child_train_op_kwargs=None, name='EnasD...
class EnasConv1dDAG(): def __init__(self, model_space, input_node, output_node, model_compile_dict, session, with_skip_connection=True, batch_size=128, keep_prob=0.9, l1_reg=0.0, l2_reg=0.0, reduction_factor=4, controller=None, child_train_op_kwargs=None, stem_config=None, data_format='NWC', train_fixed_arc=Fals...
class EnasConv1DwDataDescrption(EnasConv1dDAG): 'This is a modeler that specifiied for convolution network with data description features\n Date: 2020.5.17\n ' def __init__(self, data_description, *args, **kwargs): self.data_description = data_description super().__init__(*args, **kwarg...
class ModelBuilder(): 'Scaffold of Model Builder\n ' def __init__(self, inputs, outputs, *args, **kwargs): raise NotImplementedError('Abstract method.') def __call__(self, model_states): raise NotImplementedError('Abstract method.')
class DAGModelBuilder(ModelBuilder): def __init__(self, inputs_op, output_op, model_space, model_compile_dict, num_layers=None, with_skip_connection=True, with_input_blocks=True, dag_func=None, *args, **kwargs): if (type(inputs_op) not in (list, tuple)): self.inputs_op = [inputs_op] ...
class EnasAnnModelBuilder(DAGModelBuilder): 'This function builds an Artificial Neural net.\n\n It uses tensorflow low-level API to define a big graph, where\n each child network architecture is a subgraph in this big DAG.\n\n Parameters\n ----------\n session\n controller\n dag_func\n l1_...
class EnasCnnModelBuilder(DAGModelBuilder): def __init__(self, session=None, controller=None, dag_func='EnasConv1DDAG', l1_reg=0.0, l2_reg=0.0, batch_size=None, dag_kwargs=None, *args, **kwargs): '\n Args:\n session:\n controller:\n dag_func:\n l1_reg:\n...
class KerasModelBuilder(ModelBuilder): def __init__(self, inputs_op, output_op, model_compile_dict, model_space=None, gpus=None, **kwargs): self.model_compile_dict = model_compile_dict self.input_node = inputs_op self.output_node = output_op self.model_space = model_space ...
class KerasBranchModelBuilder(ModelBuilder): def __init__(self, inputs_op, output_op, model_compile_dict, model_space=None, with_bn=False, **kwargs): assert (type(model_space) is BranchedModelSpace) assert (len(inputs_op) == len(model_space.subspaces[0])) self.inputs_op = inputs_op ...
class KerasResidualCnnBuilder(ModelBuilder): "Function class for converting an architecture sequence tokens to a Keras model\n\n Parameters\n ----------\n inputs_op : amber.architect.modelSpace.Operation\n output_op : amber.architect.modelSpace.Operation\n fc_units : int\n number of units in...
class KerasMultiIOModelBuilder(ModelBuilder): '\n Note:\n Still not working if num_outputs=0\n ' def __init__(self, inputs_op, output_op, model_compile_dict, model_space, with_input_blocks, with_output_blocks, dropout_rate=0.2, wsf=1, **kwargs): self.model_compile_dict = model_compile_di...
def build_sequential_model(model_states, input_state, output_state, model_compile_dict, **kwargs): "\n Parameters\n ----------\n model_states: a list of _operators sampled from operator space\n input_state:\n output_state: specifies the output tensor, e.g. Dense(1, activation='sigmoid')\n model_...
def build_multi_gpu_sequential_model(model_states, input_state, output_state, model_compile_dict, gpus=4, **kwargs): try: from tensorflow.keras.utils import multi_gpu_model except Exception as e: raise Exception(('multi gpu not supported in keras. check your version. Error: %s' % e)) with ...
def build_sequential_model_from_string(model_states_str, input_state, output_state, state_space, model_compile_dict): 'build a sequential model from a string of states\n ' assert (len(model_states_str) == len(state_space)) str_to_state = [[str(state) for state in state_space[i]] for i in range(len(stat...
def build_multi_gpu_sequential_model_from_string(model_states_str, input_state, output_state, state_space, model_compile_dict): 'build a sequential model from a string of states\n ' assert (len(model_states_str) == len(state_space)) str_to_state = [[str(state) for state in state_space[i]] for i in rang...
def compare_motif_diff_size(P, Q): 'find maximum match between two metrics\n P and Q with different sizes\n ' best_d = float('inf') P_half_len = int(np.ceil((P.shape[0] / 2.0))) Q_pad = np.concatenate([(np.ones((P_half_len, Q.shape[1])) / Q.shape[1]), Q, (np.ones((P_half_len, Q.shape[1])) / Q.sh...
def remove_dup_motif(motif_dict, threshold=0.05): tmp = {} for motif_name in motif_dict: this_motif = motif_dict[motif_name] best_d = 100 for (_, ref_motif) in tmp.items(): new_d = compare_motif_diff_size(this_motif, ref_motif) if (new_d < best_d): ...
def make_output_annot(label_annot, cat_list): split_vec = [] for x in cat_list: if (type(x) is str): split_vec.append(np.where((label_annot.category == x))[0]) elif (type(x) in (list, tuple)): split_vec.append([i for i in range(label_annot.shape[0]) if (label_annot.cate...
def basewise_bits(motif): epsilon = 0.001 assert (motif.shape[1] == 4) ent = np.apply_along_axis((lambda x: (- np.sum((x * np.log2(np.clip(x, epsilon, (1 - epsilon))))))), 1, motif) return ent
def group_motif_by_factor(motif_dict, output_factors, threshold=0.1, pure_only=True): new_dict = defaultdict(dict) black_list_factors = ['CTCF', 'NFKB'] for motif_name in motif_dict: factor = motif_name.split('_')[0] if (not (factor in output_factors)): continue if (fac...
def get_seq_chunks(idx, min_cont=5, max_gap=3): intv = (idx[1:] - idx[:(- 1)]) break_points = np.concatenate([[(- 1)], np.where((intv > max_gap))[0], [(idx.shape[0] - 1)]]) if (len(break_points) <= 3): return [] chunks = [] for i in range(0, (len(break_points) - 1)): tmp = idx[[(br...
def convert_ppm_to_pwm(m, eps=0.001): m = np.clip(m, eps, (1 - eps)) m_ = (np.log2(m) - np.log2(0.25)) return m_
def create_conv_from_motif(input_ph, motifs, factor_name='None'): max_motif_len = max([m.shape[0] for m in motifs.values()]) new_motifs = [] for m in motifs.values(): left = ((max_motif_len - m.shape[0]) // 2) right = ((max_motif_len - m.shape[0]) - left) m_ = np.concatenate([(np.o...
def _index_to_label(index): 'Convert a pandas index or multiindex to an axis label.' if isinstance(index, pd.MultiIndex): return '-'.join(map(to_utf8, index.names)) else: return index.name
def _index_to_ticklabels(index): 'Convert a pandas index or multiindex into ticklabels.' if isinstance(index, pd.MultiIndex): return ['-'.join(map(to_utf8, i)) for i in index.values] else: return index.values
def _matrix_mask(data, mask): 'Ensure that data and mask are compatabile and add missing values.\n\n Values will be plotted for cells where ``mask`` is ``False``.\n\n ``data`` is expected to be a DataFrame; ``mask`` can be an array or\n a DataFrame.\n\n ' if (mask is None): mask = np.zeros...
class _HeatMapper2(object): 'Draw a heatmap plot of a matrix with nice labels and colormaps.' def __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cellsize, cellsize_vmax, cbar, cbar_kws, xticklabels=True, yticklabels=True, mask=None, ax_kws=None, rect_kws=None): 'Initial...
def heatmap2(data, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt='.2g', annot_kws=None, cellsize=None, cellsize_vmax=None, cbar=True, cbar_kws=None, cbar_ax=None, square=False, xticklabels='auto', yticklabels='auto', mask=None, ax=None, ax_kws=None, rect_kws=None): plotter = _HeatMap...
def plot_nx_dag(ss, save_fn=None): reset_plot() g = nx.DiGraph() g.add_edges_from([(i, ss.nodes[i].child[j].id) for i in ss.nodes for j in range(len(ss.nodes[i].child))]) pos = graphviz_layout(g, prog='dot') nx.draw_networkx_nodes(g, pos, cmap=plt.get_cmap('jet'), node_size=500) nx.draw_networ...
def plot_all_stats(file_list, baseline_file): dfs = [read_csv(f) for f in file_list] base_df = read_csv(baseline_file) n_run = 20 find_min_dict = {'Knowledge': True, 'Loss': True, 'Accuracy': False} for key in ['Knowledge', 'Accuracy', 'Loss']: plt.close() for (i, df) in enumerate(...
def get_random_data(num_samps=1000): x = np.random.sample(((10 * 4) * num_samps)).reshape((num_samps, 10, 4)) y = np.random.sample(num_samps) return (x, y)
def get_class_name(*args): id = args[1] map = {0: 'TestGeneralEnv', 1: 'TestEnasEnv'} return map[id]
@parameterized_class(attrs=('foo', 'manager_getter', 'controller_getter', 'modeler_getter', 'trainenv_getter'), input_values=[(0, architect.GeneralManager, architect.GeneralController, modeler.KerasResidualCnnBuilder, architect.ControllerTrainEnvironment), (1, architect.EnasManager, architect.GeneralController, model...
class TestBuffer(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestBuffer, self).__init__(*args, **kwargs) self.buffer_getter = architect.buffer.get_buffer('ordinal') def setUp(self): super(TestBuffer, self).setUp() self.tempdir = tempfile.TemporaryDirectory(...
class TestReplayBuffer(TestBuffer): def __init__(self, *args, **kwargs): super(TestReplayBuffer, self).__init__(*args, **kwargs) self.buffer_getter = architect.buffer.get_buffer('replay')
class TestMultiManagerBuffer(TestBuffer): def __init__(self, *args, **kwargs): super(TestMultiManagerBuffer, self).__init__(*args, **kwargs) self.buffer_getter = architect.buffer.get_buffer('multimanager') def setUp(self): super(TestBuffer, self).setUp() self.tempdir = tempfi...
class TestReward(unittest.TestCase): data = (None, np.array([0, 0, 0, 1, 1, 1])) model = testing_utils.PseudoModel(pred_retr=np.array([(- 1), (- 1), (- 1), 1, 1, 1]), eval_retr={'val_loss': 0.5}) knowledge_fn = testing_utils.PseudoKnowledge(k_val=0.2)
class TestAucReward(TestReward): def __init__(self, *args, **kwargs): super(TestAucReward, self).__init__(*args, **kwargs) self.reward_getter = architect.reward.LossAucReward @parameterized.expand([('auc', 1), ('aupr', 1), ((lambda y_true, y_score: scipy.stats.spearmanr(y_true, y_score)[0]),...
class TestLossReward(TestReward): def __init__(self, *args, **kwargs): super(TestLossReward, self).__init__(*args, **kwargs) self.reward_getter = architect.reward.LossReward def test_methods_call(self): reward_fn = self.reward_getter() (reward, loss_and_metrics, reward_metric...
@parameterized_class(('eval_retr', 'k_val', 'Lambda', 'exp_reward'), [(0.5, 0.2, 1, (- 0.7)), (0.5, 0.2, 2, (- 0.9)), (0.5, 0.2, 0, (- 0.5))]) class TestKnowledgeReward(TestReward): def __init__(self, *args, **kwargs): super(TestKnowledgeReward, self).__init__(*args, **kwargs) self.reward_getter ...
class TestManager(testing_utils.TestCase): x = np.random.sample(((10 * 4) * 1000)).reshape((1000, 10, 4)) y = np.random.sample(1000) def __init__(self, *args, **kwargs): super(TestManager, self).__init__(*args, **kwargs) self.reward_fn = testing_utils.PseudoReward() self.model_fn ...
class TestStore(testing_utils.TestCase): x = np.random.sample(((10 * 4) * 1000)).reshape((1000, 10, 4)) y = np.random.sample(1000) def setUp(self): self.tempdir = tempfile.TemporaryDirectory() self.trial = 0 self.model = testing_utils.PseudoConv1dModelBuilder(input_shape=(10, 4), ...
class TestModelSpace(testing_utils.TestCase): def test_conv1d_model_space(self): model_space = architect.ModelSpace() num_layers = 2 out_filters = 8 layer_ops = [architect.Operation('conv1d', filters=out_filters, kernel_size=8, activation='relu'), architect.Operation('conv1d', fil...
class TestGeneralController(testing_utils.TestCase): def setUp(self): super(TestGeneralController, self).setUp() self.session = tf.Session() (self.model_space, _) = testing_utils.get_example_conv1d_space() self.controller = architect.GeneralController(model_space=self.model_space,...
class TestOperationController(testing_utils.TestCase): def setUp(self): super(TestOperationController, self).setUp() (self.model_space, _) = testing_utils.get_example_conv1d_space() self.controller = architect.OperationController(state_space=self.model_space, controller_units=8, kl_thresh...
def get_controller(state_space, sess): 'Test function for building controller network. A controller is a LSTM cell that predicts the next\n layer given the previous layer and all previous layers (as stored in the hidden cell states). The\n controller model is trained by policy gradients as in reinforcement ...
def get_mock_manager(history_fn_list, Lambda=1.0, wd='./tmp_mock'): 'Test function for building a mock manager. A mock manager\n returns a loss and knowledge instantly based on previous\n training history.\n ' manager = MockManager(history_fn_list=history_fn_list, model_compile_dict={'loss': 'binary_...
def get_environment(controller, manager, should_plot=True, logger=None, wd='./tmp_mock/'): 'Test function for getting a training environment for controller.\n ' env = ControllerTrainEnvironment(controller, manager, max_episode=100, max_step_per_ep=3, logger=logger, resume_prev_run=False, should_plot=should...
class TestBootstrap(testing_utils.TestCase): Lambda = 1 def __init__(self, *args, **kwargs): super(TestBootstrap, self).__init__(*args, **kwargs) self.hist_file_list = [os.path.join(os.path.dirname(__file__), ('mock_black_box/tmp_%i/train_history.csv.gz' % i)) for i in range(1, 21)] s...
class TestEnasConvModeler(testing_utils.TestCase): def setUp(self): self.session = tf.Session() self.input_op = [architect.Operation('input', shape=(10, 4), name='input')] self.output_op = architect.Operation('dense', units=1, activation='sigmoid', name='output') self.x = np.rando...
class TestKerasBuilder(testing_utils.TestCase): def setUp(self): (self.model_space, _) = testing_utils.get_example_conv1d_space(num_layers=2) self.target_arc = [0, 0, 1] self.input_op = architect.Operation('input', shape=(10, 4), name='input') self.output_op = architect.Operation(...
class TestKerasGetLayer(testing_utils.TestCase): @parameterized.expand([((100,), 'dense', {'units': 4}), ((100,), 'identity', {}), ((100, 4), 'conv1d', {'filters': 5, 'kernel_size': 8}), ((100, 4), 'maxpool1d', {'pool_size': 4, 'strides': 4}), ((100, 4), 'avgpool1d', {'pool_size': 4, 'strides': 4}), ((100, 4), '...
def run_from_ipython(): try: __IPYTHON__ return True except NameError: return False
def get_available_gpus(): from tensorflow.python.client import device_lib local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if (x.device_type == 'GPU')]
def setup_logger(working_dir='.', verbose_level=logging.INFO): 'The logging used by throughout the training envrionment\n\n Parameters\n ----------\n working_dir : str\n File path to working directory. Logging will be stored in working directory.\n\n verbose_level : int\n Verbosity level...
def get_session(gpu_fraction=0.75): 'Assume that you have 6GB of GPU memory and want to allocate ~2GB' gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction) if num_threads: print(('with nthreads=%s' % num_threads)) return tf.Session(config=tf.ConfigProto(allow_soft_plac...
def get_session2(CPU, GPU): if GPU: num_GPU = 1 num_CPU = 1 if CPU: num_CPU = 1 num_GPU = 0 config = tf.ConfigProto(intra_op_parallelism_threads=num_threads, inter_op_parallelism_threads=num_threads, allow_soft_placement=True, device_count={'CPU': num_CPU, 'GPU': num_GPU}) ...
class TestCase(tf.test.TestCase): def tearDown(self): tf.keras.backend.clear_session() keras.backend.clear_session() super(TestCase, self).tearDown()
class PseudoModel(): def __init__(self, pred_retr, eval_retr): self.pred_retr = pred_retr self.eval_retr = eval_retr def predict(self, *args, **kwargs): return self.pred_retr def evaluate(self, *args, **kwargs): return self.eval_retr def fit(self, *args, **kwargs): ...
class PseudoKnowledge(): def __init__(self, k_val): self.k_val = k_val def __call__(self, *args, **kwargs): return self.k_val
class PseudoConv1dModelBuilder(): def __init__(self, input_shape, output_units, model_compile_dict=None): self.input_shape = input_shape self.output_units = output_units self.model_compile_dict = (model_compile_dict or {'optimizer': 'sgd', 'loss': 'mse'}) self.session = None ...
class PseudoCaller(): def __init__(self, retr_val=0): self.retr_val = retr_val def __call__(self, *args, **kwargs): return self.retr_val
class PseudoReward(PseudoCaller): def __init__(self, retr_val=0): self.retr_val = retr_val self.knowledge_function = None def __call__(self, *args, **kwargs): return (self.retr_val, [self.retr_val], None)
def get_example_conv1d_space(out_filters=8, num_layers=2): model_space = architect.ModelSpace() num_pool = 1 expand_layers = [((num_layers // k) - 1) for k in range(1, num_pool)] layer_sharing = {} for i in range(num_layers): model_space.add_layer(i, [architect.Operation('conv1d', filters=...
class TestEncodedGenome(unittest.TestCase): def setUp(self): self.bases = ['A', 'C', 'G', 'T'] self.bases_to_arr = dict(A=numpy.array([1, 0, 0, 0]), C=numpy.array([0, 1, 0, 0]), G=numpy.array([0, 0, 1, 0]), T=numpy.array([0, 0, 0, 1]), N=numpy.array([0.25, 0.25, 0.25, 0.25])) self.chrom_t...
class TestEncodedGenomeInMemory(TestEncodedGenome): def setUp(self): super(TestEncodedGenomeInMemory, self).setUp() self.in_memory = True def test_in_memory(self): self.assertTrue(self.in_memory) def test_genome_in_memory(self): g = self._get_small_genome() self....
class TestEncodedHDF5Genome(unittest.TestCase): def setUp(self): self.bases = ['A', 'C', 'G', 'T'] self.bases_to_arr = dict(A=numpy.array([1, 0, 0, 0]), C=numpy.array([0, 1, 0, 0]), G=numpy.array([0, 0, 1, 0]), T=numpy.array([0, 0, 0, 1]), N=numpy.array([0.25, 0.25, 0.25, 0.25])) self.chr...
class TestEncodedHDF5GenomeInMemory(TestEncodedHDF5Genome): def setUp(self): super(TestEncodedHDF5GenomeInMemory, self).setUp() self.in_memory = True def test_in_memory(self): self.assertTrue(self.in_memory) def test_genome_in_memory(self): g = self._get_small_genome() ...
class TestGenome(unittest.TestCase): def setUp(self): self.bases = ['A', 'C', 'G', 'T'] self.bases_to_arr = dict(A=numpy.array([1, 0, 0, 0]), C=numpy.array([0, 1, 0, 0]), G=numpy.array([0, 0, 1, 0]), T=numpy.array([0, 0, 0, 1]), N=numpy.array([0.25, 0.25, 0.25, 0.25])) self.chrom_to_lens ...
class TestGenomeInMemory(TestGenome): def setUp(self): super(TestGenomeInMemory, self).setUp() self.in_memory = True def test_in_memory(self): self.assertTrue(self.in_memory) def test_genome_in_memory(self): g = self._get_small_genome() self.assertTrue(g.in_memor...
class TestHDF5Genome(unittest.TestCase): def setUp(self): self.bases = ['A', 'C', 'G', 'T'] self.bases_to_arr = dict(A=numpy.array([1, 0, 0, 0]), C=numpy.array([0, 1, 0, 0]), G=numpy.array([0, 0, 1, 0]), T=numpy.array([0, 0, 0, 1]), N=numpy.array([0.25, 0.25, 0.25, 0.25])) self.chrom_to_l...
class TestHDF5GenomeInMemory(TestHDF5Genome): def setUp(self): super(TestHDF5GenomeInMemory, self).setUp() self.in_memory = True def test_in_memory(self): self.assertTrue(self.in_memory) def test_genome_in_memory(self): g = self._get_small_genome() self.assertTru...
class Amber(): 'The main wrapper class for AMBER\n\n This class facilitates the GUI and TUI caller, and should always be maintained\n\n Parameters\n ----------\n types: dict\n specs: dict\n\n Attributes\n ----------\n type_dict: dict\n is_built: bool\n model_space: amber.architect.Mo...
def convert_file(input_file, output_file): fasta = pyfaidx.Fasta(input_file) h5 = h5py.File(output_file, 'w') for k in fasta.keys(): s = str(fasta[k][:].seq).upper() ds = h5.create_dataset(k, (len(s),), dtype='S1') for i in range(len(s)): ds[i] = numpy.string_(s[i]) ...
def draw_samples(genome_file, bed_file, output_file, feature_name_file, bin_size, cvg_frac, n_examples, chrom_pad, chrom_pattern, max_unk, interval_file): feature_name_set = set() i_to_feature_name = list() feature_name_to_i = dict() i = 0 with open(feature_name_file, 'r') as read_file: fo...
def split_samples(input_file, feature_name_file, output_dir): i_to_feat = list() with open(feature_name_file, 'r') as read_file: for line in read_file: line = line.strip() if line: i_to_feat.append(line) feat_to_i = dict() for (i, feat) in enumerate(i_to...
def download_data_from_s3(task): 'Download pde data from s3 to store in temp directory' s3_base = 'https://pde-xd.s3.amazonaws.com' download_directory = '.' if (task == 'ECG'): data_files = ['challenge2017.pkl'] s3_folder = 'ECG' elif (task == 'satellite'): data_files = ['s...
def main(): task = sys.argv[1] download_data_from_s3(task)
def convert_timedelta(duration): (days, seconds) = (duration.days, duration.seconds) hours = ((days * 24) + (seconds // 3600)) minutes = ((seconds % 3600) // 60) seconds = (seconds % 60) return (hours, minutes, seconds)
def dataset_split(set_, train_prop, test_prop): df = pd.read_csv('./data/final_df.csv') df['genename_num'] = df['genename'].str.cat(df['Number'].astype(str), sep='-') samp_lst = df['genename_num'].tolist() np.random.seed(115) np.random.shuffle(samp_lst) num_test = int((len(samp_lst) * train_pr...