code
stringlengths
17
6.64M
def test_ou_process(): DATE = int(pd.to_datetime('20210205').to_datetime64()) MKT_OPEN = (DATE + str_to_ns('09:30:00')) MKT_CLOSE = (DATE + str_to_ns('16:00:00')) r_bar = 100000 kappa_oracle = 1.67e-16 fund_vol = 5e-05 megashock_lambda_a = 2.77778e-18 megashock_mean = 1000 megashoc...
def test_rmsc04(): config = build_config_rmsc04(seed=1, book_logging=False, end_time='10:00:00', log_orders=False, exchange_log_orders=False) kernel_seed = np.random.randint(low=0, high=(2 ** 32), dtype='uint64') kernel = Kernel(log_dir='__test_logs', random_state=np.random.RandomState(seed=kernel_seed), ...
class policyPassive(): def __init__(self): self.name = 'passive' def get_action(self, state): return 1
class policyAggressive(): def __init__(self): self.name = 'aggressive' def get_action(self, state): return 0
class policyRandom(): def __init__(self): self.name = 'random' def get_action(self, state): return np.random.choice([0, 1])
class policyRandomWithNoAction(): def __init__(self): self.name = 'random_no_action' def get_action(self, state): return np.random.choice([0, 1, 2])
class policyRL(): '\n policy learned during the training\n get the best policy from training {name_xp}\n Use this policy to compute action\n ' def __init__(self): self.name = 'rl' name_xp = 'dqn_execution_demo_4' data_folder = f'~/ray_results/{name_xp}' analysis = ...
def generate_env(seed): '\n generates specific environment with the parameters defined and set the seed\n ' env = gym.make('markets-execution-v0', background_config='rmsc04', timestep_duration='10S', execution_window='04:00:00', parent_order_size=20000, order_fixed_size=50, not_enough_reward_update=(- 1...
def flatten_dict(d: MutableMapping, sep: str='.') -> MutableMapping: [flat_dict] = pd.json_normalize(d, sep=sep).to_dict(orient='records') return flat_dict
def run_episode(seed=None, policy=None): '\n run fully one episode for a given seed and a given policy\n ' env = generate_env(seed) state = env.reset() done = False episode_reward = 0 while (not done): action = policy.get_action(state) (state, reward, done, info) = env.st...
def run_N_episode(N): '\n run in parallel N episode of testing for the different policies defined in policies list\n heads-up: does not work yet for rllib policies - pickle error\n #https://stackoverflow.com/questions/28821910/how-to-get-around-the-pickling-error-of-python-multiprocessing-without-being-i...
def run(config, log_dir='', kernel_seed=np.random.randint(low=0, high=(2 ** 32), dtype='uint64')): print() print('╔═══════════════════════════════════════════════════════════╗') print('β•‘ ABIDES: Agent-Based Interactive Discrete Event Simulation β•‘') print('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•...
def version_greaterorequal(l1, l2): if (l1[0] > l2[0]): return True elif (l1[0] < l2[0]): return False elif (l1[0] == l2[0]): if (len(l1) == 1): return True else: return version_greaterorequal(l1[1:], l2[1:])
def get_git_version(): result = subprocess.run(['git', '--version'], stdout=subprocess.PIPE).stdout.decode('utf-8') version = [int(c) for c in result.replace('git version ', '').replace('\n', '').split('.')] return version
def run_command(command, commit_sha, specific_path_underscore='0', git_path=None, pass_logdir_sha=None, old_new_flag=None): 'pass_logdir_sha is either null or tuple with arg name and function taking commit sha as input to produce arg value' if pass_logdir_sha: shutil.rmtree(pass_logdir_sha, ignore_err...
def get_path(level): path = pathlib.Path(__file__).parent.absolute() path = str(path) if (level == 0): return path else: path = path.split('/')[:(- level)] return '/'.join(path)
def get_paths(parameters): specific_path = f"{parameters['new']['config']}/{parameters['shared']['end-time'].replace(':', '-')}/{parameters['shared']['seed']}" specific_path_underscore = f"{parameters['new']['config']}_{parameters['shared']['end-time'].replace(':', '-')}_{parameters['shared']['seed']}" re...
def run_test(test_): (parameters, old_new_flag) = test_ (specific_path, specific_path_underscore) = get_paths(parameters) now = dt.datetime.now() stamp = now.strftime('%Y%m%d%H%M%S') time = runasof.run_command(parameters['command'][old_new_flag], commit_sha=parameters[old_new_flag]['sha'], specifi...
def compute_ob(path_old, path_new): ob_old = pd.read_pickle(path_old) ob_new = pd.read_pickle(path_new) if ob_old.equals(ob_new): return 0 else: return 1
def run_tests(LIST_PARAMETERS, varying_parameters): old_new_flags = ['old', 'new'] tests = list(itertools.product(LIST_PARAMETERS, old_new_flags)) outputs = p_map(run_test, tests) df = pd.DataFrame(outputs) df_old = df[(df['flag'] == 'old')] df_new = df[(df['flag'] == 'new')] print(f'THERE...
def get_path(level): path = pathlib.Path(__file__).parent.absolute() path = str(path) if (level == 0): return path else: path = path.split('/')[:(- level)] return '/'.join(path)
def generate_parameter_dict(seed, config, end_time, with_log): if with_log: log_orders = True exchange_log_orders = True book_freq = 0 else: log_orders = None exchange_log_orders = None book_freq = None parameters = {'old': {'sha': 'f1968a56fdb55fd7c70be1db0...
def generate_command(parameters): specific_command_old = f"{parameters['old']['script']} -config {parameters['old']['config']}" specific_command_new = f"{parameters['new']['script']} -config {parameters['new']['config']}" shared_command = [f'--{key} {val}' for (key, val) in parameters['shared'].items()] ...
def get_path(level): path = pathlib.Path(__file__).parent.absolute() path = str(path) if (level == 0): return path else: path = path.split('/')[:(- level)] return '/'.join(path)
def generate_parameter_dict(seed): parameters = {'sha_old': '8ab374e8d7c9f6fa6ab522502259e94e550e81b5', 'sha_new': 'ccdb7b3b0b099b89b86a6500e4f8f731a5dc6410', 'script_old': 'abides.py', 'script_new': 'abides_cmd.py', 'config_old': 'rmsc03', 'config_new': 'rmsc03_function', 'end-time': '10', 'seed': seed} retu...
def list_pmhc_types(): return ['A0101_VTEHDTLLY_IE-1_CMV_binder', 'A0201_KTWGQYWQV_gp100_Cancer_binder', 'A0201_ELAGIGILTV_MART-1_Cancer_binder', 'A0201_CLLWSFQTSA_Tyrosinase_Cancer_binder', 'A0201_IMDQVPFSV_gp100_Cancer_binder', 'A0201_SLLMWITQV_NY-ESO-1_Cancer_binder', 'A0201_KVAELVHFL_MAGE-A3_Cancer_binder', '...
def load_receptors(base_dir, pmhc): receptors = {} for subject in ['1', '2', '3', '4']: barcodes = {} path_csv = ((((base_dir + '/') + 'vdj_v1_hs_aggregated_donor') + subject) + '_all_contig_annotations.csv') with open(path_csv, 'r') as stream: reader = csv.DictReader(strea...
def normalize_sample(receptors): total_count = np.float64(0.0) for quantity in receptors.values(): total_count += quantity for receptor in receptors.keys(): receptors[receptor] /= total_count return receptors
def collapse_samples(samples, labels): receptors_collapse = {} for (i, (receptors, label)) in enumerate(zip(samples, labels)): for (receptor, quantity) in receptors.items(): if (receptor not in receptors_collapse): receptors_collapse[receptor] = {} if (label not...
def split_dataset(receptors, ratios): rs = np.array(ratios, dtype=np.float64) ss = (rs / np.sum(rs)) cs = np.cumsum(ss) ps = np.pad(cs, [1, 0], 'constant', constant_values=0) keys = list(receptors.keys()) np.random.shuffle(keys) keys_split = [] for i in range(len(ratios)): (j1,...
def insert_receptors(path_db, name, receptors, max_cdr3_length=32): labels = set() for quantities in receptors.values(): labels.update(quantities.keys()) labels = sorted(list(labels)) dtype_receptor = ([('tra_vgene', 'S16'), ('tra_cdr3', ('S' + str(max_cdr3_length))), ('tra_jgene', 'S16'), ('t...
class Alignment(Layer): def __init__(self, filters, weight_steps, penalties_feature=0.0, penalties_filter=0.0, length_normalize=False, kernel_initializer='uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): self.filt...
class Length(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def compute_mask(self, inputs, mask=None): if (mask is None): return mask return K.any(mask, axis=1) def call(self, inputs, mask=None): lengths = K.sum(K.cast(mask, d...
class NormalizeInitialization(Layer): def __init__(self, epsilon=1e-05, **kwargs): self.epsilon = epsilon super(__class__, self).__init__(**kwargs) def build(self, input_shape): (input_shape, _) = input_shape self.counter = self.add_weight(name='counter', shape=[1], initializ...
def load_similarity_matrix(filename): similarity_matrix = {} reader = csv.DictReader(open(filename, 'r')) entries = [] for row in reader: entries.append(row) for k in reader.fieldnames: if (len(k) < 1): continue similarity_matrix[k] = [float(obj[k]) for obj in e...
def print_matrix(m, cdr3): max_col = len(cdr3) print((' %11s' % ''), end='') for col in range(0, max_col): print((' %11s' % cdr3[col]), end='') print('') for row in range(0, 33): for col in range(0, (max_col + 1)): print((' %11.4f' % m[row][col]), end='') print(...
def print_bp(bp, cdr3): max_col = len(cdr3) print((' %11s' % ''), end='') for col in range(0, max_col): print((' %11s' % cdr3[col]), end='') print('') for row in range(0, 33): for col in range(0, (max_col + 1)): print((' %11s' % bp[row][col]), end='') print('')
def print_alignment(bp, cdr3): cdr3_align = [] theta_align = [] max_col = len(cdr3) col = max_col row = 32 done = False while (not done): if (bp[row][col] == 'diag'): theta_align.append(row) cdr3_align.append(cdr3[(col - 1)]) row -= 1 ...
def do_alignment(sm, cdr3): theta_gap = 0 cdr3_gap = (- 1000) am = [] bp = [] for row in range(0, 33): am.append([0.0 for col in range(0, 33)]) bp.append([None for col in range(0, 33)]) max_col = (len(cdr3) + 1) score = 0 for row in range(0, 33): am[row][0] = sc...
def do_file_alignment(input, output, sm_tra, sm_trb, tag): reader = csv.DictReader(open(input, 'r')) fieldnames = reader.fieldnames.copy() fieldnames.append(('tra_alignment_' + tag)) fieldnames.append(('tra_score_' + tag)) fieldnames.append(('trb_alignment_' + tag)) fieldnames.append(('trb_sco...
def test_alignment(sm, cdr3): align = do_alignment(sm, cdr3) print_matrix(align[0], cdr3) print_bp(align[1], cdr3) print(print_alignment(align[1], cdr3))
class GlobalPoolWithMask(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def compute_mask(self, inputs, mask=None): return tf.reduce_any(mask, axis=1) def call(self, inputs, mask=None): indicators = tf.expand_dims(tf.cast(mask, dtype=inputs.dtype)...
def generate_model(input_shape_tra_cdr3, input_shape_tra_vgene, input_shape_tra_jgene, input_shape_trb_cdr3, input_shape_trb_vgene, input_shape_trb_jgene, num_outputs): kmer_size = 4 features_tra_cdr3 = Input(shape=input_shape_tra_cdr3) features_tra_vgene = Input(shape=input_shape_tra_vgene) features_...
class GlobalPoolWithMask(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def compute_mask(self, inputs, mask=None): return tf.reduce_any(mask, axis=1) def call(self, inputs, mask=None): indicators = tf.expand_dims(tf.cast(mask, dtype=inputs.dtype)...
def generate_model(input_shape_tra_cdr3, input_shape_tra_vgene, input_shape_tra_jgene, input_shape_trb_cdr3, input_shape_trb_vgene, input_shape_trb_jgene, num_outputs): kmer_size = 4 features_tra_cdr3 = Input(shape=input_shape_tra_cdr3) features_tra_vgene = Input(shape=input_shape_tra_vgene) features_...
def generate_model(input_shape_tra_cdr3, input_shape_tra_vgene, input_shape_tra_jgene, input_shape_trb_cdr3, input_shape_trb_vgene, input_shape_trb_jgene, num_outputs, num_steps): kmer_size = 5 features_tra_cdr3 = Input(shape=input_shape_tra_cdr3) features_tra_vgene = Input(shape=input_shape_tra_vgene) ...
def handcrafted_features(data, tags): basicity = {'A': 206.4, 'B': 210.7, 'C': 206.2, 'D': 208.6, 'E': 215.6, 'F': 212.1, 'G': 202.7, 'H': 223.7, 'I': 210.8, 'K': 221.8, 'L': 209.6, 'M': 213.3, 'N': 212.8, 'P': 214.4, 'Q': 214.2, 'R': 237.0, 'S': 207.6, 'T': 211.7, 'V': 208.7, 'W': 216.1, 'X': 210.2, 'Y': 213.1, ...
def load_datasets(path_db, splits, tags, uniform=False, permute=False): num_categories = len(tags) receptors_dict = {} for split in splits: with h5py.File(path_db, 'r') as db: receptors = db[split][...] weights = 0.0 for tag in tags: weights += receptors[('f...
def balanced_sampling(xs, ys, ws, batch_size): rs = np.arange(xs.shape[0]) ws_ = (ws / np.sum(ws)) while True: js = np.random.choice(rs, size=batch_size, p=ws_) (yield (xs[js], ys[js]))
def generate_model(input_shape_tra_cdr3, input_shape_tra_vgene, input_shape_tra_jgene, input_shape_trb_cdr3, input_shape_trb_vgene, input_shape_trb_jgene, num_outputs): features_tra_cdr3 = Input(shape=input_shape_tra_cdr3) features_tra_vgene = Input(shape=input_shape_tra_vgene) features_tra_jgene = Input(...
def generate_model(input_shape_tra_cdr3, input_shape_tra_vgene, input_shape_tra_jgene, input_shape_trb_cdr3, input_shape_trb_vgene, input_shape_trb_jgene, num_outputs): features_tra_cdr3 = Input(shape=input_shape_tra_cdr3) features_tra_vgene = Input(shape=input_shape_tra_vgene) features_tra_jgene = Input(...
def handcrafted_features(data, tags): basicity = {'A': 206.4, 'B': 210.7, 'C': 206.2, 'D': 208.6, 'E': 215.6, 'F': 212.1, 'G': 202.7, 'H': 223.7, 'I': 210.8, 'K': 221.8, 'L': 209.6, 'M': 213.3, 'N': 212.8, 'P': 214.4, 'Q': 214.2, 'R': 237.0, 'S': 207.6, 'T': 211.7, 'V': 208.7, 'W': 216.1, 'X': 210.2, 'Y': 213.1, ...
def load_datasets(path_db, splits, tags, uniform=False, permute=False): num_categories = len(tags) receptors_dict = {} for split in splits: with h5py.File(path_db, 'r') as db: receptors = db[split][...] weights = 0.0 for tag in tags: weights += receptors[('f...
def balanced_sampling(xs, ys, ws, batch_size): rs = np.arange(xs.shape[0]) ws_ = (ws / np.sum(ws)) while True: js = np.random.choice(rs, size=batch_size, p=ws_) (yield (xs[js], ys[js]))
def handcrafted_features(data, tags): basicity = {'A': 206.4, 'B': 210.7, 'C': 206.2, 'D': 208.6, 'E': 215.6, 'F': 212.1, 'G': 202.7, 'H': 223.7, 'I': 210.8, 'K': 221.8, 'L': 209.6, 'M': 213.3, 'N': 212.8, 'P': 214.4, 'Q': 214.2, 'R': 237.0, 'S': 207.6, 'T': 211.7, 'V': 208.7, 'W': 216.1, 'X': 210.2, 'Y': 213.1, ...
def load_datasets(path_db, splits, tags, uniform=False, permute=False): num_categories = len(tags) receptors_dict = {} for split in splits: with h5py.File(path_db, 'r') as db: receptors = db[split][...] weights = 0.0 for tag in tags: weights += receptors[('f...
def label_float2int(ys, num_classes): ys_index = np.argmax(ys, axis=1) ys_onehot = np.squeeze(np.eye(num_classes)[ys_index.reshape((- 1))]) ys_hard = ys_onehot.astype(np.int64) return ys_hard
def crossentropy(labels, logits, weights): weights = (weights / tf.reduce_sum(weights)) costs = ((- tf.reduce_sum((labels * logits), axis=1)) + tf.reduce_logsumexp(logits, axis=1)) cost = tf.reduce_sum((weights * costs)) return cost
def accuracy(labels, logits, weights): probabilities = tf.math.softmax(logits) weights = (weights / tf.reduce_sum(weights)) corrects = tf.cast(tf.equal(tf.argmax(labels, axis=1), tf.argmax(probabilities, axis=1)), probabilities.dtype) accuracy = tf.reduce_sum((weights * corrects)) return accuracy
def find_threshold(labels, logits, weights, target_accuracy): probabilities = tf.math.softmax(logits) weights = (weights / tf.reduce_sum(weights)) entropies = ((- tf.reduce_sum((probabilities * logits), axis=1)) + tf.reduce_logsumexp(logits, axis=1)) corrects = tf.cast(tf.equal(tf.argmax(labels, axis=...
def accuracy_with_threshold(labels, logits, weights, threshold): probabilities = tf.math.softmax(logits) weights = (weights / tf.reduce_sum(weights)) entropies = ((- tf.reduce_sum((probabilities * logits), axis=1)) + tf.reduce_logsumexp(logits, axis=1)) corrects = tf.cast(tf.equal(tf.argmax(labels, ax...
def crossentropy_with_threshold(labels, logits, weights, threshold): probabilities = tf.math.softmax(logits) weights = (weights / tf.reduce_sum(weights)) entropies = ((- tf.reduce_sum((probabilities * logits), axis=1)) + tf.reduce_logsumexp(logits, axis=1)) costs = ((- tf.reduce_sum((labels * logits),...
def fraction_with_threshold(logits, weights, threshold): probabilities = tf.math.softmax(logits) weights = (weights / tf.reduce_sum(weights)) entropies = ((- tf.reduce_sum((probabilities * logits), axis=1)) + tf.reduce_logsumexp(logits, axis=1)) masks = tf.where((entropies <= threshold), tf.ones_like(...
def generate_model(input_shape_tra_cdr3, input_shape_tra_vgene, input_shape_tra_jgene, input_shape_trb_cdr3, input_shape_trb_vgene, input_shape_trb_jgene, num_outputs, num_steps): features_tra_cdr3 = Input(shape=input_shape_tra_cdr3) features_tra_vgene = Input(shape=input_shape_tra_vgene) features_tra_jge...
def generate_model(input_shape_tra_cdr3, input_shape_tra_vgene, input_shape_tra_jgene, input_shape_trb_cdr3, input_shape_trb_vgene, input_shape_trb_jgene, num_outputs, num_steps): features_tra_cdr3 = Input(shape=input_shape_tra_cdr3) features_tra_vgene = Input(shape=input_shape_tra_vgene) features_tra_jge...
def balanced_sampling(xs, ys, ws, batch_size): rs = np.arange(xs[0].shape[0]) ws_ = (ws / np.sum(ws)) while True: js = np.random.choice(rs, size=batch_size, p=ws_) (yield ((xs[0][js], xs[1][js], xs[2][js], xs[3][js], xs[4][js], xs[5][js]), ys[js]))
def balanced_sampling(xs, ys, ws, batch_size): rs = np.arange(xs[0].shape[0]) ws_ = (ws / np.sum(ws)) while True: js = np.random.choice(rs, size=batch_size, p=ws_) (yield ((xs[0][js], xs[1][js], xs[2][js], xs[3][js], xs[4][js], xs[5][js]), ys[js]))
def load_receptors(path_tsv, min_cdr3_length=8, max_cdr3_length=32): receptors = {} with open(path_tsv, 'r') as stream: reader = csv.DictReader(stream, delimiter='\t') for row in reader: nns = row['nucleotide'] cdr3 = row['aminoAcid'] vgene = row['vGeneName'...
def normalize_receptors(receptors): total_quantity = np.float64(0.0) for quantity in sorted(receptors.values()): total_quantity += quantity for receptor in receptors.keys(): receptors[receptor] /= total_quantity return receptors
def insert_receptors(path_db, name, receptors, max_cdr3_length=32): dtype = [('cdr3', ('S' + str(max_cdr3_length))), ('frequency', 'f8')] rs = np.zeros(len(receptors), dtype=dtype) for (i, cdr3) in enumerate(sorted(receptors, key=receptors.get, reverse=True)): rs[i]['cdr3'] = cdr3 rs[i]['f...
def insert_samples(path_db, name, samples): dtype = [('sample', 'S32'), ('age', 'f8'), ('label', 'f8'), ('weight', 'f8')] ss = np.zeros(len(samples), dtype=dtype) num_pos = 0.0 for (i, sample) in enumerate(sorted(samples.keys())): if (samples[sample]['diagnosis'] > 0.5): num_pos +=...
class Abundance(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def compute_mask(self, inputs, mask=None): return mask def call(self, inputs, mask=None): inputs_expand = K.expand_dims(inputs, axis=1) outputs = K.log(inputs_expand) ...
class Alignment(Layer): def __init__(self, filters, weight_steps, penalties_feature=0.0, penalties_filter=0.0, length_normalize=False, kernel_initializer='uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): self.filt...
class BatchExpand(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def call(self, inputs, mask=None): (x, y) = inputs outputs = (x * K.ones_like(y, dtype=x.dtype)) return outputs
class FullFlatten(Layer): def compute_mask(self, inputs, mask=None): return None def call(self, inputs, mask=None): outputs = tf.reshape(inputs, [(- 1)]) return outputs
class Length(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def compute_mask(self, inputs, mask=None): if (mask is None): return mask return K.any(mask, axis=1) def call(self, inputs, mask=None): lengths = K.sum(K.cast(mask, d...
class NormalizeInitializationByAggregation(Layer): def __init__(self, level, epsilon=1e-05, **kwargs): self.level = level self.epsilon = epsilon super(__class__, self).__init__(**kwargs) def build(self, input_shape): (input_shape, _, _) = input_shape self.numerator = ...
def load_similarity_matrix(filename): similarity_matrix = {} reader = csv.DictReader(open(filename, 'r')) entries = [] for row in reader: entries.append(row) for k in reader.fieldnames: if (len(k) < 1): continue similarity_matrix[k] = [float(obj[k]) for obj in e...
def print_matrix(m, cdr3): max_col = len(cdr3) print((' %11s' % ''), end='') for col in range(0, max_col): print((' %11s' % cdr3[col]), end='') print('') for row in range(0, 9): for col in range(0, (max_col + 1)): print((' %11.4f' % m[row][col]), end='') print('...
def print_bp(bp, cdr3): max_col = len(cdr3) print((' %11s' % ''), end='') for col in range(0, max_col): print((' %11s' % cdr3[col]), end='') print('') for row in range(0, 9): for col in range(0, (max_col + 1)): print((' %11s' % bp[row][col]), end='') print('')
def print_alignment(bp, cdr3): cdr3_align = [] theta_align = [] max_col = len(cdr3) col = max_col row = 8 done = False while (not done): if (bp[row][col] == 'diag'): theta_align.append(row) cdr3_align.append(cdr3[(col - 1)]) row -= 1 ...
def do_alignment(sm, cdr3): theta_gap = (- 1000) cdr3_gap = 0 max_col = (len(cdr3) + 1) am = [] bp = [] for row in range(0, 9): am.append([0.0 for col in range(0, max_col)]) bp.append([None for col in range(0, max_col)]) score = 0 for row in range(0, 9): am[row]...
def do_file_alignment(input, output, sm_tra, sm_trb, tag): reader = csv.DictReader(open(input, 'r')) fieldnames = reader.fieldnames.copy() fieldnames.append(('tra_alignment_' + tag)) fieldnames.append(('tra_score_' + tag)) fieldnames.append(('trb_alignment_' + tag)) fieldnames.append(('trb_sco...
def test_alignment(sm, cdr3): align = do_alignment(sm, cdr3) print_matrix(align[0], cdr3) print_bp(align[1], cdr3) print(print_alignment(align[1], cdr3))
class BatchExpand(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def call(self, inputs, mask=None): (x, y) = inputs outputs = (x * K.ones_like(y, dtype=x.dtype)) return outputs
class GlobalPoolWithMask(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def compute_mask(self, inputs, mask=None): return tf.reduce_any(mask, axis=1) def call(self, inputs, mask=None): indicators = tf.expand_dims(tf.cast(mask, dtype=inputs.dtype)...
def generate_model(input_shape_cdr3, num_outputs, filter_size): features_cdr3 = Input(shape=input_shape_cdr3) features_quantity = Input(shape=[]) feature_age = Input(batch_shape=[1]) weight = Input(batch_shape=[1]) level = Input(batch_shape=[1]) features_mask = Masking(mask_value=0.0)(features...
def generate_model(input_shape_cdr3, num_outputs, filter_size): features_cdr3 = Input(shape=input_shape_cdr3) features_quantity = Input(shape=[]) feature_age = Input(batch_shape=[1]) weight = Input(batch_shape=[1]) level = Input(batch_shape=[1]) features_mask = Masking(mask_value=0.0)(features...
class BatchExpand(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def call(self, inputs, mask=None): (x, y) = inputs outputs = (x * K.ones_like(y, dtype=x.dtype)) return outputs
class GlobalPoolWithMask(Layer): def __init__(self, **kwargs): super(__class__, self).__init__(**kwargs) def compute_mask(self, inputs, mask=None): return tf.reduce_any(mask, axis=1) def call(self, inputs, mask=None): indicators = tf.expand_dims(tf.cast(mask, dtype=inputs.dtype)...
def generate_model(input_shape_cdr3, num_outputs, filter_size): features_cdr3 = Input(shape=input_shape_cdr3) features_quantity = Input(shape=[]) feature_age = Input(batch_shape=[1]) weight = Input(batch_shape=[1]) level = Input(batch_shape=[1]) features_mask = Masking(mask_value=0.0)(features...
def generate_model(input_shape_cdr3, num_outputs, filter_size): features_cdr3 = Input(shape=input_shape_cdr3) features_quantity = Input(shape=[]) feature_age = Input(batch_shape=[1]) weight = Input(batch_shape=[1]) level = Input(batch_shape=[1]) features_mask = Masking(mask_value=0.0)(features...
def train_one_epoch(model: torch.nn.Module, dl, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, args=None): model.train(True) optimizer.zero_grad() metric_logger = misc.MetricLogger(delimiter=' ') metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}')) ...
@torch.no_grad() def evaluate(model, dl, device, args): model.eval() metric_logger = misc.MetricLogger(delimiter=' ') header = 'Test:' all_preds = {} for batch in metric_logger.log_every(dl, 10, header): x = mem_inputs_to_device(batch, device, args) batch['known_mask1'] = known_ma...
def get_args_parser(): parser = argparse.ArgumentParser('Train Sequence Detector') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--aa_expand', default='backbone', help='scratch|backbone') parser.add_argument('--single_dec', default='naive', help='naive') parser.add_argume...
def main(args): misc.init_distributed_mode(args) if ((not args.disable_wandb) and misc.is_main_process()): run_name = args.output_dir.name wandb.init(project='mutate_everything', name=run_name, config=args, dir=args.output_dir) print(args) device = torch.device(args.device) seed = ...
def eval_ddg(df: pd.DataFrame, preds: dict, max_dets: list=[30], max_ddg: float=(- 0.5)): "\n Args:\n df: DataFrame with pdb_id, mut_info, gt ddg\n preds: dict of {pdb_id: {'mutations': [], 'scores': []}}\n mutations formatted f'{cur_aa}{seq_pos}{mut_aa}' (indexing from 1)\n max...
def _preprocess_gt_pr(df, preds): ' Clean the GT, then merge the predictions into the GT dataframe. ' df = df[(~ df.mut_info.isna())] df = df[(~ df.ddg.isna())] df['mut_info'] = df['mut_info'].str.upper() df = df.groupby(['pdb_id', 'mut_info'], as_index=False).median(numeric_only=True) if (('d...
def compute_detection_metrics(df: pd.DataFrame, max_dets: list=[30], max_ddg: float=(- 0.5)): metrics_pdb = [] for pdb_id in df.pdb_id.unique(): df_pdb = df[(df.pdb_id == pdb_id)].sort_values('scores', ascending=False) scores = df_pdb.scores.to_numpy() ddg = df_pdb.ddg.to_numpy() ...
def compute_precision(gt_pdb, pr_muts_sorted): '\n gt_pdb: DataFrame with pdb_id, mut_info, gt ddg with ONLY ddg < threshold\n pr_muts_sorted: list of mutations sorted by score already filtered to max_det\n ' assert (len(gt_pdb.pdb_id.unique()) == 1), f'more than 1 pdb {gt_pdb.pdb_id.unique()}' m...