repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
DMASTE
DMASTE-main/BMRC/utils.py
# coding: UTF-8 # @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 import torch from torch.nn import functional as F import logging def normalize_size(tensor): if len(tensor.size()) == 3: tensor = tensor.contiguous().view(-1, tensor.size(2)) elif len(tensor.size()) == 2...
3,575
35.121212
128
py
DMASTE
DMASTE-main/BMRC/data_utils.py
from torch.utils.data import Dataset import random import torch class Domain: Target = 1 Source = 0 class Unlabeled_Dataset(Dataset): def __init__(self, path, tokenizer, max_len=256): self.data = [] self.max_len = max_len with open(path) as f: for line in f: ...
2,601
45.464286
150
py
DMASTE
DMASTE-main/BMRC/makeData_dual.py
# @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 import torch from torch.utils.data import Dataset from transformers import BertTokenizer import numpy as np _tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') class dual_sample(object): def __init__(self, ...
24,242
50.037895
144
py
DMASTE
DMASTE-main/BMRC/Model.py
# coding: UTF-8 # @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 from transformers import BertTokenizer, BertModel, BertConfig import torch.nn as nn class BERTModel(nn.Module): def __init__(self, args): hidden_size = args.hidden_size super(BERTModel, self).__init...
1,477
35.04878
104
py
DMASTE
DMASTE-main/BMRC/makeData_standard.py
# @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 import torch import pickle from dataProcess import get_text def make_standard(home_path, dataset_name, dataset_type): # read triple f = open(home_path + dataset_name + "/" + dataset_type + ".txt", "r", encoding="utf-8") te...
2,219
35.393443
113
py
DMASTE
DMASTE-main/BMRC/scripts/cross-domain/dann/run.py
import os import sys import time import random import threading source_list = ['electronics', 'home', 'beauty', 'fashion', 'all'] target_list = ['book', 'grocery', 'pet', 'toy'] class Param: def __init__(self, model_name, source, target, ad_steps): self.model_name = model_name self.source = sou...
1,911
31.965517
128
py
DMASTE
DMASTE-main/BMRC/scripts/cross-domain/dann/run_xu.py
import os import sys import time import random import threading source_list = ['14res', '15res', '16res', '14lap', '14lap', '14lap'] target_list = ['14lap', '14lap', '14lap', '14res', '15res', '16res'] class Param: def __init__(self, model_name, source, target, ad_steps): self.model_name = model_name ...
1,935
32.964912
128
py
DMASTE
DMASTE-main/Generative-ABSA/main.py
import argparse import os import logging import time import pickle from tqdm import tqdm import torch from torch.utils.data import DataLoader import pytorch_lightning as pl from pytorch_lightning import seed_everything from transformers import AdamW, T5ForConditionalGeneration, T5Tokenizer from transformers import ge...
16,407
42.638298
158
py
DMASTE
DMASTE-main/Generative-ABSA/convert_to_triplets.py
def idx2term(sent, triplets): words = sent.split() ret = [] for a, o, s in triplets: a_term = words[a[0]: a[-1] + 1] o_term = words[o[0]: o[-1] + 1] ret.append((' '.join(a_term), ' '.join(o_term), s)) return ret def convert(examples, all_preds, golden): ret = [] for sent...
1,537
39.473684
106
py
DMASTE
DMASTE-main/Generative-ABSA/data_utils.py
# This file contains all data loading and transformation functions import time from torch.utils.data import Dataset senttag2word = {'POS': 'positive', 'NEG': 'negative', 'NEU': 'neutral'} def read_line_examples_from_file(data_path): """ Read data from file, each line is: sent####labels Return List[List[...
11,367
34.304348
105
py
DMASTE
DMASTE-main/Generative-ABSA/error_analysis.py
import pickle as pk def get_result(source, target): sentences = f'data/aste/{target}/test.txt' in_domain = f'log/results-aste-{target}.pickle' cross_domain = f'log/results-aste-{source}_2_{target}.pickle' lines = [] with open(sentences) as f: for line in f: lines.append(line.st...
1,251
30.3
83
py
DMASTE
DMASTE-main/Generative-ABSA/eval_utils.py
# This file contains the evaluation functions import re import editdistance sentiment_word_list = ['positive', 'negative', 'neutral'] aspect_cate_list = ['location general', 'food prices', 'food quality', 'ambience general', 'service general', 'restaurant prices', 'drinks prices', 'restaurant miscellaneous', ...
11,361
31.462857
97
py
DMASTE
DMASTE-main/GTS/code/NNModel/main.py
#coding utf-8 import json, os import random import argparse import numpy import torch import torch.nn.functional as F from tqdm import trange import numpy as np from data import load_data_instances, DataIterator from model import MultiInferRNNModel, MultiInferCNNModel import utils def train(args): # load doub...
7,166
39.954286
127
py
DMASTE
DMASTE-main/GTS/code/NNModel/attention_module.py
import copy import math import torch import torch.nn.functional as F def attention(query, key, value, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) \ / math.sqrt(d_k) if mask is not None: ...
4,281
38.648148
112
py
DMASTE
DMASTE-main/GTS/code/NNModel/utils.py
import multiprocessing import pickle import numpy as np import sklearn id2sentiment = {1: 'neg', 3: 'neu', 5: 'pos'} def get_aspects(tags, length, ignore_index=-1): spans = [] start = -1 for i in range(length): if tags[i][i] == ignore_index: continue elif tags[i][i] == 1: if s...
5,783
37.052632
105
py
DMASTE
DMASTE-main/GTS/code/NNModel/model.py
import torch import torch.nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.nn.functional as F from attention_module import MultiHeadedAttention, SelfAttention class MultiInferRNNModel(torch.nn.Module): def __init__(self, gen_emb, domain_emb, args): '''double embedd...
7,886
41.632432
123
py
DMASTE
DMASTE-main/GTS/code/NNModel/data.py
import math import torch sentiment2id = {'negative': 3, 'neutral': 4, 'positive': 5} def get_spans(tags): '''for BIO tag''' tags = tags.strip().split() length = len(tags) spans = [] start = -1 for i in range(length): if tags[i].endswith('B'): if start != -1: ...
5,123
36.955556
93
py
DMASTE
DMASTE-main/GTS/code/BertModel/main.py
#coding utf-8 import json, os import random import argparse import torch import torch.nn.functional as F from tqdm import trange from data import load_data_instances, DataIterator from model import MultiInferBert import utils def train(args): # load dataset train_sentence_packs = json.load(open(args.prefi...
6,176
37.60625
124
py
DMASTE
DMASTE-main/GTS/code/BertModel/utils.py
import multiprocessing import pickle import numpy as np import sklearn id2sentiment = {1: 'neg', 3: 'neu', 5: 'pos'} def get_aspects(tags, length, ignore_index=-1): spans = [] start = -1 for i in range(length): if tags[i][i] == ignore_index: continue elif tags[i][i] == 1: if s...
8,201
43.096774
145
py
DMASTE
DMASTE-main/GTS/code/BertModel/model.py
import torch import torch.nn from transformers import BertModel, BertTokenizer class MultiInferBert(torch.nn.Module): def __init__(self, args): super(MultiInferBert, self).__init__() self.args = args self.bert = BertModel.from_pretrained(args.bert_model_path) self.tokenizer = Ber...
2,451
37.3125
114
py
DMASTE
DMASTE-main/GTS/code/BertModel/data.py
import math import torch import numpy as np sentiment2id = {'negative': 3, 'neutral': 4, 'positive': 5} from transformers import BertTokenizer def get_spans(tags): '''for BIO tag''' tags = tags.strip().split() length = len(tags) spans = [] start = -1 for i in range(length): if tags[i...
7,269
36.864583
100
py
DMASTE
DMASTE-main/BARTABSA/peng/convert_to_triplets.py
from transformers import AutoTokenizer import json import numpy as np def init_tokenizer(): tokenizer = AutoTokenizer.from_pretrained('facebook/bart-base') unique_no_split_tokens = tokenizer.unique_no_split_tokens tokenizer.unique_no_split_tokens = unique_no_split_tokens + ['[ia]'] tokenizer.add_toke...
4,318
37.5625
92
py
DMASTE
DMASTE-main/BARTABSA/peng/__init__.py
0
0
0
py
DMASTE
DMASTE-main/BARTABSA/peng/train.py
import sys sys.path.append('../') import os if 'p' in os.environ: os.environ['CUDA_VISIBLE_DEVICES'] = os.environ['p'] # os.environ['CUDA_VISIBLE_DEVICES'] = '7' import warnings warnings.filterwarnings('ignore') from data.pipe import BartBPEABSAPipe from peng.model.bart_absa import BartSeq2SeqModel from fastN...
7,183
37.623656
128
py
DMASTE
DMASTE-main/BARTABSA/peng/data/pipe.py
from fastNLP.io import Pipe, DataBundle, Loader import os import json from fastNLP import DataSet, Instance from transformers import AutoTokenizer import numpy as np from itertools import chain from functools import cmp_to_key def cmp_aspect(v1, v2): if v1[0]['from']==v2[0]['from']: return v1[1]['from'] -...
7,390
40.757062
148
py
DMASTE
DMASTE-main/BARTABSA/peng/data/__init__.py
0
0
0
py
DMASTE
DMASTE-main/BARTABSA/peng/model/losses.py
from fastNLP import LossBase import torch.nn.functional as F from fastNLP import seq_len_to_mask class Seq2SeqLoss(LossBase): def __init__(self): super().__init__() def get_loss(self, tgt_tokens, tgt_seq_len, pred): """ :param tgt_tokens: bsz x max_len, [sos, tokens, eos] :p...
671
27
81
py
DMASTE
DMASTE-main/BARTABSA/peng/model/utils.py
import numpy as np def get_max_len_max_len_a(data_bundle, max_len=10): """ :param data_bundle: :param max_len: :return: """ max_len_a = -1 for name, ds in data_bundle.iter_datasets(): if name=='train':continue src_seq_len = np.array(ds.get_field('src_seq_len').content) ...
756
26.035714
82
py
DMASTE
DMASTE-main/BARTABSA/peng/model/bart_absa.py
import torch from .modeling_bart import BartEncoder, BartDecoder, BartModel from transformers import BartTokenizer from fastNLP import seq_len_to_mask from fastNLP.modules import Seq2SeqEncoder, Seq2SeqDecoder, State import torch.nn.functional as F from fastNLP.models import Seq2SeqModel from torch import nn import mat...
14,844
46.428115
145
py
DMASTE
DMASTE-main/BARTABSA/peng/model/modeling_bart.py
# coding=utf-8 # Copyright 2020 The Facebook AI Research Team Authors and The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LIC...
58,282
41.234058
213
py
DMASTE
DMASTE-main/BARTABSA/peng/model/metrics.py
from fastNLP import MetricBase from fastNLP.core.metrics import _compute_f_pre_rec from collections import Counter class Seq2SeqSpanMetric(MetricBase): def __init__(self, eos_token_id, num_labels, opinion_first=True): super(Seq2SeqSpanMetric, self).__init__() self.eos_token_id = eos_token_id ...
5,863
34.539394
120
py
DMASTE
DMASTE-main/BARTABSA/peng/model/__init__.py
0
0
0
py
DMASTE
DMASTE-main/BARTABSA/peng/model/generator.py
r"""Modify from fastNLP""" import torch from torch import nn from fastNLP.models.seq2seq_model import Seq2SeqModel from fastNLP.modules.decoder.seq2seq_decoder import Seq2SeqDecoder, State import torch.nn.functional as F from fastNLP.core.utils import _get_model_device from functools import partial class SequenceGen...
23,989
44.435606
126
py
DMASTE
DMASTE-main/BARTABSA/data/process.py
import os import json def convert_triples(triples, words): aspects = [] opinions = [] for i, triple in enumerate(triples): a, o, s = triple aspect = {'index': i, 'from': a[0], 'to': a[-1] + 1, 'polarity': s, 'term': words[a[0]: a[-1] + 1]} opinion = {'index': i, 'from': o[0], 'to': ...
1,503
32.422222
107
py
DMASTE
DMASTE-main/mySpanASTE/main.py
import os import random import argparse import torch from transformers import BertTokenizer, BertModel from torch.utils.data import DataLoader from torch.optim import AdamW from tqdm import tqdm from transformers.optimization import get_linear_schedule_with_warmup from torch.utils.tensorboard import SummaryWriter ...
8,336
46.369318
190
py
DMASTE
DMASTE-main/mySpanASTE/DANN_main.py
import os import random import argparse import torch from transformers import BertTokenizer, BertModel from torch.utils.data import DataLoader from torch.optim import AdamW from tqdm import tqdm from transformers.optimization import get_linear_schedule_with_warmup from torch.utils.tensorboard import SummaryWriter ...
10,335
47.754717
232
py
DMASTE
DMASTE-main/mySpanASTE/models/relation.py
from os import read import torch import math from utils.data_utils import RelationLabel, SpanLabel from utils.index_select import batched_index_select from models.feedForward import FeedForward def bucket_values( distances: torch.Tensor, num_identity_buckets: int = 4, num_total_buckets: int = 10 ) -> torch.Tens...
8,024
51.796053
186
py
DMASTE
DMASTE-main/mySpanASTE/models/feedForward.py
import torch class FeedForward(torch.nn.Module): def __init__(self, input_dim, hidden_dim, num_layers, activation, dropout): super(FeedForward, self).__init__() hidden_dims = [hidden_dim] * num_layers # type: ignore activations = [activation] * num_layers # type: ignore dropout =...
1,421
39.628571
79
py
DMASTE
DMASTE-main/mySpanASTE/models/DANN_span_aste.py
import torch from torch.nn import functional as F from utils.index_select import batched_index_select from models.ner import NERModel from models.relation import RelationModel from models.functions import ReverseLayerF class SpanModel(torch.nn.Module): def __init__(self, encoder, width_embedding_dim=20, max_width...
3,605
59.1
157
py
DMASTE
DMASTE-main/mySpanASTE/models/ner.py
import torch from torch.nn.modules import dropout import torch.nn.functional as F from utils.data_utils import SpanLabel from models.feedForward import FeedForward class NERModel(torch.nn.Module): def __init__(self, span_embed_dim, hidden_dim=150, num_layers=2, activation=torch.nn.ReLU(), dropout=0.4, n_labels=3...
2,651
48.111111
188
py
DMASTE
DMASTE-main/mySpanASTE/models/functions.py
from torch.autograd import Function class ReverseLayerF(Function): @staticmethod def forward(ctx, x, alpha): ctx.alpha = alpha return x.view_as(x) @staticmethod def backward(ctx, grad_output): output = grad_output.neg() * ctx.alpha return output, None
305
18.125
46
py
DMASTE
DMASTE-main/mySpanASTE/models/span_aste.py
import torch from utils.index_select import batched_index_select from models.ner import NERModel from models.relation import RelationModel class SpanModel(torch.nn.Module): def __init__(self, encoder, width_embedding_dim=20, max_width=512, spans_per_word=0.5): super(SpanModel, self).__init__() sel...
2,370
52.886364
157
py
DMASTE
DMASTE-main/mySpanASTE/scripts/cross-domain/dann/run.py
import os import sys import time import random import threading source_list = ['electronics', 'home', 'beauty', 'fashion', 'all'] target_list = ['book', 'grocery', 'pet', 'toy'] class Param: def __init__(self, model_name, source, target, ad_steps): self.model_name = model_name self.source = sou...
1,907
31.896552
128
py
DMASTE
DMASTE-main/mySpanASTE/scripts/cross-domain/dann/run_eq.py
import os import sys import time import random import threading source_list = ['electronics', 'home', 'beauty', 'fashion', 'all'] target_list = ['book', 'grocery', 'pet', 'toy'] class Param: def __init__(self, model_name, source, target, ad_steps): self.model_name = model_name self.source = sou...
1,910
31.948276
131
py
DMASTE
DMASTE-main/mySpanASTE/scripts/cross-domain/dann/run_xu.py
import os import sys import time import random import threading source_list = ['14res', '15res', '16res', '14lap', '14lap', '14lap'] target_list = ['14lap', '14lap', '14lap', '14res', '15res', '16res'] class Param: def __init__(self, model_name, source, target, ad_steps): self.model_name = model_name ...
1,926
32.224138
128
py
DMASTE
DMASTE-main/mySpanASTE/utils/data_utils_unlabeled.py
import os from enum import IntEnum from torch.utils.data import Dataset class DomainLabel(IntEnum): Source = 0 Target = 1 class UnlabeledDataset(Dataset): def __init__(self, features): self.features = features def __getitem__(self, index): return self.features[index] ...
3,572
33.68932
92
py
DMASTE
DMASTE-main/mySpanASTE/utils/collate_unlabeled.py
import torch from utils.data_utils import RelationLabel from utils.data_utils_unlabeled import DomainLabel def collate_fn_target(data): """批处理,填充同一batch中句子最大的长度""" def pad_and_tensor(data, pad_value=0): max_len = max([len(x) for x in data]) new_data = [] mask = [] for x in dat...
1,535
36.463415
99
py
DMASTE
DMASTE-main/mySpanASTE/utils/data_utils.py
import os from enum import IntEnum from pydantic import BaseModel from typing import List from torch.utils.data import Dataset import torch class SpanLabel(IntEnum): INVALID = 0 ASPECT = 1 OPINION = 2 class RelationLabel(IntEnum): INVALID = 0 POS = 1 NEG = 2 NEU = 3 class ABSADataset...
8,811
38.339286
155
py
DMASTE
DMASTE-main/mySpanASTE/utils/collate.py
import torch from utils.data_utils import RelationLabel def collate_fn(data): """批处理,填充同一batch中句子最大的长度""" def pad_and_tensor(data, pad_value=0): max_len = max([len(x) for x in data]) new_data = [] mask = [] for x in data: tmp_data = torch.tensor(x) siz...
2,502
39.370968
106
py
DMASTE
DMASTE-main/mySpanASTE/utils/__init__.py
0
0
0
py
DMASTE
DMASTE-main/mySpanASTE/utils/index_select.py
import torch def batched_index_select(target, indices): """ target : `torch.Tensor`, required. A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size). This is the tensor to be indexed. indices : `torch.LongTensor` A tensor of shape (batch_size, ...), where eac...
1,622
42.864865
111
py
DMASTE
DMASTE-main/mySpanASTE/utils/metric.py
import torch from utils.data_utils import convert_pad_tensor_to_list, convert_predictions_to_triples, SpanLabel, RelationLabel from sklearn.metrics import precision_score, recall_score, f1_score def convert_relations_to_list(relations, mask): ret = [] for i in range(relations.shape[0]): r, m = relatio...
6,970
51.022388
159
py
GPOMCP
GPOMCP-master/logscan.py
import sys import math threshold_string = "threshold = " reward_string = "Obtained an accum reward of: " if len(sys.argv) != 4: print "3 Arguments required: input_file and output_file and avg_out_file" exit(0) in_filename = sys.argv[1] out_filename = sys.argv[2] avg_out_filename = sys.argv[3] in_file = open(...
1,478
24.5
77
py
GPOMCP
GPOMCP-master/datscan.py
import sys import math threshold_string = "threshold = " reward_string = "Obtained an accum reward of: " if len(sys.argv) != 5: print "4 Arguments required: input_file1 "\ "input_file2 and output_file and avg_out_file" exit(0) in_filename1 = sys.argv[1] in_filename2 = sys.argv[2] out_filename = sys.a...
1,752
22.689189
69
py
GPOMCP
GPOMCP-master/Examples/Hallway/hallcp.py
from shutil import copyfile import os for i in range(1,10): os.system("mkdir "+"./hallway"+str(i)) os.system("python genHallway.py "+"maph"+str(i)+".txt "+"hallway"+str(i)+".POMDP") os.system("mv maph"+str(i)+ ".txt ./hallway"+str(i)) os.system("mv hallway"+str(i)+ ".POMDP ./hallway"+str(i))
298
32.222222
83
py
GPOMCP
GPOMCP-master/Examples/Hallway/genHallway.py
# Generates a POMDP file with a Hallway instance from a given maze map in a text file. # Usage: python genHallway.py input_map.txt output_file [discount_factor] # Hallway: a classic POMDP robot navigation benchmark. We have a maze with walls, traps and goals. # The robot can move forward or turn left and right and it ...
11,319
36.859532
147
py
GPOMCP
GPOMCP-master/Examples/Hallway/hallcp2.py
import os for i in range(1,10): os.system("python genHallway.py hallway"+str(i)+".txt hallway"+str(i)+".POMDP")
114
22
80
py
GPOMCP
GPOMCP-master/Examples/Hallway/MazeGen/MazeGeneratorRecursiveDivision.py
import random import numpy def isIn(i,j,num_rows,num_cols): b = 1 if (i < 0) or (j < 0) or (i >= num_rows) or (j >= num_cols): b=0; return b; def Modify(M,x_ul,y_ul,x_dr,y_dr): if (x_dr - x_ul < 5) or (y_dr - y_ul < 5): pass else: x_cut = random.randint(x_ul+2,x_dr-2) if not (x_ul...
2,613
25.673469
94
py
GPOMCP
GPOMCP-master/Examples/Hallway/MazeGen/MazeGenerator.py
import random import numpy def isIn(i,j,num_rows,num_cols): b = 1 if (i < 0) or (j < 0) or (i >= num_rows) or (j >= num_cols): b=0; return b; #input num_rows = int(input("Rows-2: ")) num_cols = int(input("Columns-2: ")) num_nowall = int(input("Number of cells that are not walls: ")) num_trap = ...
4,716
28.298137
118
py
GPOMCP
GPOMCP-master/Examples/rockSample/genScript/Coord.py
#dimX = 6 #dimY = 6 # dimY = 2 class Coord: # (0,0) bottom left corner def __init__(self,x,y,dim): self.x = x self.y = y self.dim = dim def setWalls(self,walls): self.walls = walls def __str__(self): return "%dx%d" % (self.x, self.y) def __repr__(self): ...
2,694
24.186916
102
py
GPOMCP
GPOMCP-master/Examples/rockSample/genScript/State.py
from Coord import * import itertools class State: def __init__(self, robot, mines, observation): self.robot = robot self.mines = mines self.observation = observation def __repr__(self): return "N%sM%sT" % (str(self.robot),str(self.mines)) # return "(R:%s,T:%s,A: %s,O:%s)" % (self.robot,self.target,self.a...
2,678
24.514286
158
py
GPOMCP
GPOMCP-master/Examples/rockSample/genScript/genRockSample.py
import itertools import random from State import * from Coord import * # Here you can set up rewards for various type of transitions and other stepRew = -1 goodMineRew = 50 badMineRew = -25 illegalMoveRew = -100 discount = 0.98 sense = -5 assert not badMineRew == 0 and not goodMineRew == 0 and not badMineRew == g...
15,375
31.033333
163
py
ges-idr5
ges-idr5-master/cross_validate_sun.py
""" Cross-validate ensemble model on the sun. """ import yaml import logging import os import matplotlib.pyplot as plt import numpy as np from glob import glob from code import (GESDatabase, plot, summary) from astropy.table import Table # Initialize logging. logger = logging.getLogger("ges.idr5.qc") logger.setLeve...
2,635
22.327434
158
py
ges-idr5
ges-idr5-master/setup.py
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys from setuptools import setup, find_packages from codecs import open from os import path, system from re import compile as re_compile # For convenience. if sys.argv[-1] == "publish": system("python setup.py sdist upload") sys.exit() def read(filename):...
1,640
28.836364
72
py
ges-idr5
ges-idr5-master/sandbox_plot.py
from code.model import ensemble, plot raise a for wg in (11, ): for parameter in ("teff", "logg", "feh"): model = ensemble.EnsembleModel.read( "homogenisation-wg11-{}.model".format(parameter), None) # Plot the distribution of biases for each node fig = plot.biases(model...
1,991
38.058824
86
py
ges-idr5
ges-idr5-master/sandbox_plotting.py
#!/usr/bin/python import yaml import logging import os import matplotlib.pyplot as plt from glob import glob from code import (GESDatabase, plot, summary) from astropy.table import Table # Initialize logging. logger = logging.getLogger("ges.idr5.qc") logger.setLevel(logging.DEBUG) handler = logging.StreamHandler()...
12,041
25.819599
89
py
ges-idr5
ges-idr5-master/sandbox_ensemble.py
""" Sandbox for ensemble model """ import yaml import logging import os import matplotlib.pyplot as plt import numpy as np from glob import glob from code import (GESDatabase, plot, summary) from astropy.table import Table # Initialize logging. logger = logging.getLogger("ges.idr5.qc") logger.setLevel(logging.DEBUG...
7,903
27.534296
121
py
ges-idr5
ges-idr5-master/sandbox_plot_wg_performance.py
import yaml from glob import glob from code import (GESDatabase, plot, summary) from astropy.table import Table # Create a database object. db_filename = "db.yaml" with open(db_filename, "r") as fp: credentials = yaml.load(fp) database = GESDatabase(**credentials) # Clean up bits and pieces... savefig_kwds = ...
3,134
30.35
95
py
ges-idr5
ges-idr5-master/sandbox_plot_flags.py
#!/usr/bin/python import yaml from code import (GESDatabase, plot) # Create a database object. db_filename = "db.yaml" with open(db_filename, "r") as fp: credentials = yaml.load(fp) database = GESDatabase(**credentials) for wg in (10, 11, 12, 13): fig, meta = plot.flags.heatmap(database, wg, show_...
751
24.931034
74
py
ges-idr5
ges-idr5-master/sandbox_mean_ensemble.py
""" Sandbox for ensemble model """ import yaml import logging import os import matplotlib.pyplot as plt import numpy as np from glob import glob from code import (GESDatabase, plot, summary) from astropy.table import Table # Initialize logging. logger = logging.getLogger("ges.idr5.qc") logger.setLevel(logging.DEBUG...
1,405
18.260274
114
py
ges-idr5
ges-idr5-master/scripts/plot_korn_cluster.py
import yaml import logging import os import matplotlib.pyplot as plt from glob import glob from code import (GESDatabase, plot, summary) from astropy.table import Table # Initialize logging. logger = logging.getLogger("ges.idr5.qc") logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() handler.setFormatt...
2,899
25.363636
93
py
ges-idr5
ges-idr5-master/scripts/propagate_flags.py
#!/usr/bin/python """ Propagate relevant flag information from one node to others. """ import logging import yaml from code import GESDatabase # Connect to database. db_filename = "db.yaml" with open(db_filename, "r") as fp: credentials = yaml.load(fp) # Create a database object. database = GESDatabase(**crede...
10,591
35.524138
1,133
py
ges-idr5
ges-idr5-master/scripts/homogenise_wg11.py
""" Homogenisation models. """ import yaml import logging import numpy as np from code import GESDatabase from code.model.ensemble import SingleParameterEnsembleModel from astropy.table import Table # Initialize logging. logger = logging.getLogger("ges") # Create a database object. db_filename = "db.yaml" with o...
2,151
25.567901
95
py
ges-idr5
ges-idr5-master/scripts/homogenise_fast.py
""" Homogenisation models. """ import yaml import logging import numpy as np import os from astropy.table import Table from collections import OrderedDict from code import GESDatabase from code.model.ensemble import EnsembleModel, MedianModel # Initialize logging. logger = logging.getLogger("ges") # Create a data...
2,926
27.980198
107
py
ges-idr5
ges-idr5-master/scripts/setup_db.py
#!/usr/bin/python """ Create database for the fifth internal data release of the Gaia-ESO Survey. """ import logging import numpy as np import psycopg2 as pg import yaml from glob import glob # For fake data generation import os from astropy.io import fits from code import GESDatabase db_filename = "db.yaml" nod...
2,824
25.401869
82
py
ges-idr5
ges-idr5-master/scripts/update_benchmarks.py
""" Update the benchmark parameters to include some values -- even if they are uncertain -- and to include a less-biased value for HD 140283. """ from astropy.table import Table input_path = "../fits-templates/benchmarks/GES_iDR5_FGKMCoolWarm_Benchmarks_AcceptedParams_01082016.fits" output_path = "../fits-templates/...
1,167
24.391304
105
py
ges-idr5
ges-idr5-master/scripts/ship_wg11.py
""" Ship a WG11 recommended SP product. """ import yaml import logging from code import GESDatabase, ship # Initialize logging. logger = logging.getLogger("ges") # Create a database object. db_filename = "db.yaml" with open(db_filename, "r") as fp: credentials = yaml.load(fp) database = GESDatabase(**credentia...
845
25.4375
100
py
ges-idr5
ges-idr5-master/scripts/homogenise_all_wgs.py
""" Homogenisation models. """ import yaml import logging import numpy as np import os from astropy.table import Table from collections import OrderedDict from code import GESDatabase from code.model.ensemble import SingleParameterEnsembleModel # Initialize logging. logger = logging.getLogger("ges") # Create a d...
2,757
27.142857
95
py
ges-idr5
ges-idr5-master/code/db.py
""" A convenience object for databases. """ import logging import numpy as np import psycopg2 as pg from astropy.table import Table from collections import Counter from decimal import Decimal from time import time logger = logging.getLogger("ges") class Database(object): def __init__(self, **kwargs): ...
5,523
27.183673
81
py
ges-idr5
ges-idr5-master/code/ship.py
""" Fucking :shipit: """ import logging import numpy as np from astropy.io import fits from astropy.table import Table from datetime import datetime import utils from db import Database logger = logging.getLogger("ges") def wg_recommended_sp_template(database, input_path, output_path, wg, ext=-1, overwrite=Fa...
4,674
24.972222
78
py
ges-idr5
ges-idr5-master/code/utils.py
""" General utility functions. """ import os from numpy import isfinite def safe_int(x, fill_value=-1): try: return int(x) except: return fill_value def wg_as_int(wg): return int(str(wg).strip().lower().lstrip("wg")) def parse_node_filename(filename): # GES_iDR5_WG10_NodeTemplate...
675
17.777778
52
py
ges-idr5
ges-idr5-master/code/__init__.py
import logging logger = logging.getLogger("ges") logger.setLevel(logging.INFO) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( "%(asctime)s [%(levelname)-8s] %(message)s")) logger.addHandler(handler) from . import model from .gesdb import GESDatabase
285
19.428571
49
py
ges-idr5
ges-idr5-master/code/gesdb.py
""" A specialized database class for Gaia-ESO Survey data releases. """ import logging import numpy as np from astropy.io import fits from astropy.table import Table import utils from db import Database logger = logging.getLogger("ges") class GESDatabase(Database): def __init__(self, *args, **kwargs): ...
10,196
28.903226
99
py
ges-idr5
ges-idr5-master/code/summary.py
""" Produce summary tables. """ import numpy as np from collections import Counter from astropy.table import Table import utils def stellar_parameter_range(database, wg=None): """ Produce a summary table outlining the range of stellar parameters reported. :param database: A database for transa...
4,274
28.895105
86
py
ges-idr5
ges-idr5-master/code/plot/nodes.py
import numpy as np import os import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib import gridspec import corner import utils __all__ = ["compare_nodes_within_wg", "compare_to_photometric_teff", "compare_to_previous_dr"] def compare_to_previous_dr(database, wg, node_name,...
9,929
30.324921
80
py
ges-idr5
ges-idr5-master/code/plot/cluster.py
import logging import numpy as np import os import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib import gridspec import utils __all__ = ["cluster", "param_vs_param"] logger = logging.getLogger("ges.idr5.qc") def param_vs_param(database, wg, node_name, ges_fld, reference_parame...
9,020
30.876325
84
py
ges-idr5
ges-idr5-master/code/plot/benchmarks.py
import logging import numpy as np import os import matplotlib.pyplot as plt from astropy.table import Table from matplotlib.ticker import MaxNLocator from matplotlib import gridspec import utils __all__ = ["node_benchmark_performance", "wg_benchmark_performance"] benchmark_filename = "fits-templates/benchmarks/GES...
13,779
34.792208
110
py
ges-idr5
ges-idr5-master/code/plot/utils.py
import numpy as np from astropy.table import Table def parse_isochrone(filename): """ Parse a PARSEC or Siess isochrone. :param filename: The filename of the isochrone. """ is_parsec = "parsec" in filename.lower() kwds = { "format": "ascii" } if is_parsec: kwd...
1,119
19.363636
78
py
ges-idr5
ges-idr5-master/code/plot/flags.py
import numpy as np import matplotlib.pyplot as plt from itertools import combinations from matplotlib.colors import LogNorm import scipy.sparse.csgraph _WG14_NODE_IDS = { "01": "Arcetri", "02": "CAUP", "03": "EPINARBO", "04": "IAC", "05": "Lumba", "06": "MaxPlanck", "07": "MyGIsFOS", ...
9,136
30.725694
87
py
ges-idr5
ges-idr5-master/code/plot/__init__.py
from hrd import * from cluster import * from nodes import * from benchmarks import * import flags
97
18.6
24
py
ges-idr5
ges-idr5-master/code/plot/hrd.py
__all__ = ["hrd", "stellar_parameter_histograms", "stellar_parameter_error_histograms", "hrd_by_setup"] import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib import gridspec import utils def hrd_by_setup(database, wg, node_name): """ Show Hertszpr...
9,544
28.642857
87
py
ges-idr5
ges-idr5-master/code/model/plot.py
""" Plot things relevant to the ensemble model. """ import cPickle as pickle import itertools import logging import numpy as np import scipy.sparse import matplotlib.pyplot as plt from collections import OrderedDict from matplotlib.ticker import MaxNLocator import brewer2mpl # For pretty colors. logger = logging.g...
22,417
30.619182
124
py
ges-idr5
ges-idr5-master/code/model/__init__.py
from .ensemble import *
23
23
23
py
ges-idr5
ges-idr5-master/code/model/ensemble.py
""" Classes to deal with homogenisation models written in Stan. """ import cPickle as pickle import logging import numpy as np import os import pystan as stan from astropy.table import Table from collections import OrderedDict from itertools import combinations from time import time from . import plot logger = logg...
40,550
34.854111
98
py
YouTokenToMe
YouTokenToMe-master/setup.py
import io import os from setuptools import Extension, find_packages, setup from Cython.Build import cythonize extensions = [ Extension( "_youtokentome_cython", [ "youtokentome/cpp/yttm.pyx", "youtokentome/cpp/bpe.cpp", "youtokentome/cpp/utils.cpp", "...
1,673
29.436364
82
py
YouTokenToMe
YouTokenToMe-master/tests/speed_test/speed_test.py
import argparse import os from pathlib import Path from time import time from tabulate import tabulate from tokenizers import pre_tokenizers from tokenizers import Tokenizer as HuggingFaceBPETokenizer from tokenizers.models import BPE as HuggingFaceBPEModel from tokenizers.trainers import BpeTrainer as HuggingFaceBPET...
9,224
34.755814
120
py
YouTokenToMe
YouTokenToMe-master/tests/unit_tests/test_cli.py
import os import random from subprocess import run from utils_for_testing import ( BASE_MODEL_FILE, RENAME_ID_MODEL_FILE, TEST_FILE, TRAIN_FILE, BOS_ID, EOS_ID, file_starts_with, generate_artifacts, ) def test_bos_eos_reverse(): generate_artifacts() cmd_args = [ "yttm"...
5,301
23.892019
114
py
YouTokenToMe
YouTokenToMe-master/tests/unit_tests/test_stress.py
import os from subprocess import run tests_compiled = False def compile_test(): global tests_compiled if tests_compiled: return build_files = ["bpe.cpp", "utils.cpp", "utf8.cpp"] files = ["../../youtokentome/cpp/" + file_name for file_name in build_files] files.append("stress_test.cpp") ...
1,115
20.882353
90
py
YouTokenToMe
YouTokenToMe-master/tests/unit_tests/test_python_api.py
import os import random import youtokentome as yttm from utils_for_testing import ( BASE_MODEL_FILE, RENAME_ID_MODEL_FILE, TEST_FILE, TRAIN_FILE, BOS_ID, EOS_ID, file_starts_with, generate_artifacts, ) def test_encode_decode(): generate_artifacts() os.remove(BASE_MODEL_FILE) ...
1,411
26.153846
86
py
YouTokenToMe
YouTokenToMe-master/tests/unit_tests/test_manual.py
# -*- coding: utf-8 -*- import os import youtokentome as yttm def test_russian(): train_text = """ собирать cборник сборище отобранный сборщица """ test_text = """ собранный собрание прибор """ TRAIN_DATA_PATH = "train_data.txt" MODEL_PATH = "model.yttm" with op...
2,294
29.197368
113
py