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
PyBDSF
PyBDSF-master/bdsf/collapse.py
"""Module collapse Defines operation Op_collapse which collapses 3D image. Calculates and stores mean and rms (normal and clipped) per channel anyway for further use, even if weights are unity. """ from __future__ import absolute_import import numpy as N from .image import * from . import _cbdsm #_cbdsm.init_numpy() ...
11,493
36.562092
114
py
PyBDSF
PyBDSF-master/bdsf/const.py
"""Constants Some universal constants """ import math pi=math.pi fwsig=2.35482 rad=180.0/pi c=2.99792458e8 bolt=1.3806505e-23 sq2=math.sqrt(2)
147
8.866667
24
py
PyBDSF
PyBDSF-master/bdsf/readimage.py
"""Module readimage. Defines operation Op_readimage which initializes image and WCS The current implementation tries to reduce input file to 2D if possible, as this makes more sense atm. One more important thing to note -- in its default configuration pyfits will read data in non-native format, so we have to convert ...
25,341
40.13961
119
py
PyBDSF
PyBDSF-master/bdsf/spectralindex.py
"""Module Spectral index. This module calculates spectral indices for Gaussians and sources for a multichannel cube. """ from __future__ import print_function from __future__ import absolute_import import numpy as N from .image import Op from . import mylogger from copy import deepcopy as cp from . import functio...
29,798
46.602236
146
py
PyBDSF
PyBDSF-master/bdsf/image.py
"""Module image. Instances of class Image are a primary data-holders for all PyBDSF operations. They store the image itself together with some meta-information (such as headers), options for processing modules and all data generated during processing. A few convenience methods are also defined here for interactive use...
7,542
34.580189
88
py
PyBDSF
PyBDSF-master/bdsf/wavelet_atrous.py
"""Compute a-trous wavelet transform of the gaussian residual image. Do source extraction on this if asked. """ from __future__ import print_function from __future__ import absolute_import import numpy as N from .image import * from . import mylogger import os from . import has_pl if has_pl: import matplotlib.pypl...
30,509
40.966988
170
py
PyBDSF
PyBDSF-master/bdsf/mylogger.py
""" WARNING, ERROR, and CRITICAL are always output to screen and to log file. INFO and USERINFO always go to the log file. DEBUG goes to log file if debug is True. USERINFO goes to screen only if quiet is False. Use as follows: mylog = mylogger.logging.getLogger("name") mylog.info('info') --> print to logfile, but n...
4,331
30.852941
79
py
PyBDSF
PyBDSF-master/bdsf/polarisation.py
"""Module polarisation. This module finds the Q, U, and V fluxes, the total, linear, and circular polarisation fractions and the linear polarisation angle of each source identified by gaul2srl. The position angle is defined from North, with positive angles towards East. """ from __future__ import absolute_import fro...
30,916
46.2737
145
py
PyBDSF
PyBDSF-master/bdsf/cleanup.py
""" Does miscellaneous jobs at the end, which assumes all other tasks are run. """ from __future__ import absolute_import import numpy as N import os from .image import * from . import mylogger from . import has_pl if has_pl: import matplotlib.pyplot as pl import matplotlib.cm as cm from . import funct...
1,688
29.160714
102
py
PyBDSF
PyBDSF-master/bdsf/islands.py
"""Module islands. Defines operation Op_islands which does island detection. Current implementation uses scipy.ndimage operations for island detection. While it's implemented to work for images of arbitrary dimensionality, the bug in the current version of scipy (0.6) often causes crashes (or just wrong results) for 3...
18,339
41.258065
148
py
PyBDSF
PyBDSF-master/bdsf/opts.py
"""PyBDSF options Options are essentially user-controllable parameters passed into PyBDSF operations, and allow for end-users to control the exact details of how calculations are done. The doc string should give a short description of the option, followed by a line break ('\n') then a long, detailed description. The ...
103,331
65.537025
116
py
PyBDSF
PyBDSF-master/bdsf/sourcecounts.py
"""Sourcecounts s is flux in Jy and n is number > s per str """ import numpy as N s=N.array([ 9.9999997e-05, 0.00010328281, 0.00010667340, 0.00011017529, 0.00011379215, 0.00011752774, 0.00012138595, \ 0.00012537083, 0.00012948645, 0.00013373725, 0.00013812761, 0.00014266209, 0.00014734542, 0.00015218249, 0.000157178...
12,587
104.781513
123
py
PyBDSF
PyBDSF-master/bdsf/functions.py
# some functions from __future__ import print_function from __future__ import absolute_import try: # For Python 2 basestring = basestring except NameError: basestring = str def poly(c,x): """ y = Sum { c(i)*x^i }, i=0,len(c)""" import numpy as N y=N.zeros(len(x)) for i in range(len(c)): ...
80,495
32.950232
141
py
PyBDSF
PyBDSF-master/bdsf/psf_vary.py
from __future__ import print_function from __future__ import absolute_import import numpy as N from .image import * from . import mylogger from copy import deepcopy as cp from . import has_pl if has_pl: import matplotlib.pyplot as pl import scipy import scipy.signal as S from . import _cbdsm from . import function...
49,211
44.821229
176
py
PyBDSF
PyBDSF-master/bdsf/pybdsf.py
"""Interactive PyBDSF shell. This module initializes the interactive PyBDSF shell, which is a customized IPython enviroment. It should be called from the terminal prompt using the command "pybdsf". """ from __future__ import print_function import bdsf from bdsf.image import Image import pydoc import sys import inspect...
29,572
38.378162
83
py
PyBDSF
PyBDSF-master/bdsf/plotresults.py
"""Plotting module This module is used to display fits results. """ from __future__ import print_function from __future__ import absolute_import from .image import * from . import has_pl if has_pl: import matplotlib.pyplot as pl import matplotlib.cm as cm import matplotlib.patches as mpatches from matp...
29,396
38.672065
137
py
PyBDSF
PyBDSF-master/bdsf/tc.py
"""Defines some basic facilities for handling typed values. It's quite basic and limited implementation tailored specifically for use in the PyBDSM user-options and derived properties. For a user option, one can define a group that is used when listing the options to the screen. For a property (e.g., flux density), o...
20,582
29.092105
77
py
PyBDSF
PyBDSF-master/bdsf/_version.py
"""Version module. This module simply stores the version number, as well as a changelog. """ # Version number __version__ = '1.11.0a1' # Changelog def changelog(): """ PyBDSF Changelog. ----------------------------------------------------------------------- 2023/05/22 - Version 1.10.3 2023/05/0...
29,263
39.985994
85
py
PyBDSF
PyBDSF-master/bdsf/gausfit.py
"""Module gausfit. This module does multi-gaussian fits for all detected islands. At the moment fitting algorithm is quite simple -- we just add gaussians one-by-one as long as there are pixels with emission in the image, and do post-fitting flagging of the extracted gaussians. The fitting itself is implemented by th...
48,011
43.414431
138
py
PyBDSF
PyBDSF-master/bdsf/multi_proc.py
"""Multiprocessing module to handle parallelization. This module can optionally update a statusbar and can divide tasks between cores using weights (so that each core gets a set of tasks with the same total weight). Adapted from a module by Brian Refsdal at SAO, available at AstroPython (http://www.astropython.org/sn...
7,753
31.041322
83
py
PyBDSF
PyBDSF-master/bdsf/threshold.py
"""Module threshold. Defines operation Op_threshold. If the option 'thresh' is defined as 'fdr' then the value of thresh_pix is estimated using the False Detection Rate algorithm (using the user defined value of fdr_alpha). If thresh is None, then the false detection probability is first calculated, and if the number ...
4,603
38.689655
113
py
PyBDSF
PyBDSF-master/bdsf/__init__.py
"""Initialize PyBDSF namespace. Import all standard operations, define default chain of operations and provide function 'execute', which can execute chain of operations properly. Also define the 'process_image' convienence function that can take options as arguments rather than as a dictionary (as required by 'execute...
9,534
35.957364
118
py
PyBDSF
PyBDSF-master/bdsf/gaul2srl.py
"""Module gaul2srl This will group gaussians in an island into sources. Will code callgaul2srl.f here, though it could probably be made more efficient. img.sources is a list of source objects, which are instances of the class Source (with attributes the same as in .srl of fbdsm). img.sources[n] is a source. source.g...
34,935
49.927114
142
py
PyBDSF
PyBDSF-master/bdsf/interface.py
"""Interface module. The interface module handles all functions typically needed by the user in an interactive environment such as IPython. Many are also used by the custom IPython shell defined in pybdsf. """ from __future__ import print_function from __future__ import absolute_import try: # For Python 2, use r...
47,513
40.244792
125
py
PyBDSF
PyBDSF-master/bdsf/make_residimage.py
"""Module make_residimage. It calculates residual image from the list of gaussians and shapelets """ from __future__ import absolute_import import numpy as N from scipy import stats # for skew and kurtosis from .image import * from .shapelets import * from . import mylogger class Op_make_residimage(Op): """Crea...
9,400
40.052402
120
py
PyBDSF
PyBDSF-master/bdsf/shapefit.py
"""Module shapelets This will do all the shapelet analysis of islands in an image """ from __future__ import absolute_import from .image import * from .islands import * from .shapelets import * from . import mylogger from . import statusbar from . import multi_proc as mp import itertools try: from itertools impor...
6,326
38.792453
117
py
PyBDSF
PyBDSF-master/bdsf/output.py
"""Module output. Defines functions that write the results of source detection in a variety of formats. These are then used as methods of Image objects and/or are called by the outlist operation if output_all is True. """ from __future__ import print_function from __future__ import absolute_import from .image import ...
49,335
40.147623
130
py
PyBDSF
PyBDSF-master/bdsf/preprocess.py
"""Module preprocess Calculates some basic statistics of the image and sets up processing parameters for PyBDSM. """ from __future__ import absolute_import import numpy as N from . import _cbdsm from .image import * from math import pi, sqrt, log from . import const from . import functions as func from . import mylog...
6,799
37.418079
116
py
PyBDSF
PyBDSF-master/bdsf/statusbar.py
"""Display an animated statusbar""" from __future__ import absolute_import import sys import os from . import functions as func class StatusBar(): # class variables: # max: number of total items to be completed # pos: number of completed items # spin_pos: current position in array of busy_chars #...
3,257
31.58
187
py
PyBDSF
PyBDSF-master/bdsf/rmsimage.py
"""Module rmsimage. Defines operation Op_rmsimage which calculates mean and rms maps. The current implementation will handle both 2D and 3D images, where for 3D case it will calculate maps for each plane (= Stokes images). """ from __future__ import absolute_import import numpy as N import scipy.ndimage as nd from ....
47,148
43.818441
129
py
PyBDSF
PyBDSF-master/bdsf/shapelets.py
"""Module shapelets. nmax => J = 0..nmax; hence nmax+1 orders calculated. ordermax = nmax+1; range(ordermax) has all the values of n Order n => J=n, where J=0 is the gaussian. """ from __future__ import print_function from __future__ import absolute_import import numpy as N try: from astropy.io import fits as py...
13,371
33.552972
108
py
PyBDSF
PyBDSF-master/bdsf/nat/__init__.py
# Adapted for numpy/ma/cdms2 by convertcdms.py """--------------------------------------------------------------------------------------------- INTRODUCTION TO NGMATH The ngmath library is a collection of interpolators and approximators for one-dimensional, two-dimensional and three-dimensional da...
88,775
47.19544
242
py
PyBDSF
PyBDSF-master/natgrid/setup.py
#!/usr/bin/env python from numpy.distutils.core import setup, Extension import glob,sys sources=glob.glob('Src/*.c') setup (name = "natgrid", version='1.0', description = "natgrid", url = "http://cdat.sf.net", packages = [''], package_dir = {'': 'Lib'}, include_dirs = ['Inclu...
404
22.823529
58
py
PyBDSF
PyBDSF-master/natgrid/Test/test_natgrid.py
# Adapted for numpy/ma/cdms2 by convertcdms.py """Documentation for module natgridtest: an automatic test for natgrid, an interface to the ngmath NATGRID TESTING Typing cdat natgridtest.py generates some testing of the natgridmodule using analytical functions a...
51,193
45.120721
133
py
PyBDSF
PyBDSF-master/doc/source/conf.py
# -*- coding: utf-8 -*- # # PyBDSF documentation build configuration file, created by # sphinx-quickstart on Thu Jan 19 13:27:03 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
9,149
30.6609
83
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/load_data_clean.py
# -*- coding: utf-8 -*- """ Created on Wed Nov 17 21:11:58 2021 @author: Vu Nguyen """ import pandas as pd from sklearn import preprocessing import numpy as np from sklearn.datasets import load_iris,load_breast_cancer,load_digits import pickle import os path ='./vector_data/' #======================================...
3,686
27.804688
115
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/setup.py
from setuptools import setup, find_packages setup( name='csa', version='1.0', packages=find_packages(), include_package_data = True, description='Confident Sinkhorn Allocation', install_requires=[ "colorama>=0.4.5", "cycler>=0.11.0", "fonttools>=4.33.3", "joblib>...
741
23.733333
48
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/load_multi_label_data.py
# -*- coding: utf-8 -*- """ Created on Thu Feb 3 14:25:12 2022 @author: Vu Nguyen """ #import arff from scipy.io import arff import pandas as pd from sklearn.preprocessing import OneHotEncoder import pickle def load_yeast_multilabel(folder=''): # temp = arff.loadarff(open('vector_data/yeast-train.arff', 'r')) ...
2,733
24.082569
69
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/load_data.py
# -*- coding: utf-8 -*- """ Created on Wed Nov 17 21:11:58 2021 @author: Vu Nguyen """ import pandas as pd from sklearn import preprocessing import numpy as np from sklearn.datasets import load_iris,load_breast_cancer,load_digits import pickle import os path ='./vector_data/' #======================================...
3,540
27.556452
115
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/__init__.py
#from algorithm import * #from utilities import *
49
24
24
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/utilities/utils.py
# -*- coding: utf-8 -*- """ Created on Wed Mar 16 20:14:22 2022 @author: Vu Nguyen """ import pickle import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler def str2num(s, encoder): return encoder[s] def append_acc_early_termination(AccList, NumIte...
8,280
39.004831
148
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/utilities/__init__.py
0
0
0
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/run_experiments/run_ups.py
import sys #sys.path.insert(0,'..') sys.path.append('..') from tqdm import tqdm import numpy as np import os import argparse import logging import pickle from algorithm.pseudo_labeling import Pseudo_Labeling #from algorithm.flexmatch import FlexMatch from algorithm.ups import UPS #from algorithm.csa import CSA from ...
4,544
38.181034
175
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/run_experiments/plot_results.py
import sys import os sys.path.append('../') sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import numpy as np import matplotlib.pyplot as plt #from algorithm.pseudo_labeling import Pseudo_Labeling from algorithm.pseudo_labeling import Pseudo_Labeling from algorithm.flexmatch impo...
4,373
32.906977
159
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/run_experiments/run_pseudo_labeling.py
import sys #sys.path.insert(0,'..') sys.path.append('..') import numpy as np import os import argparse import logging import pickle from tqdm import tqdm from algorithm.pseudo_labeling import Pseudo_Labeling #from algorithm.flexmatch import FlexMatch #from algorithm.ups import UPS #from algorithm.csa import CSA fro...
4,272
36.814159
171
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/run_experiments/run_sla.py
import sys import os sys.path.insert(0,'..') sys.path.append("../algorithm") sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import numpy as np import argparse import logging import pickle from tqdm import tqdm from algorithm.pseudo_labeling import Pseudo_Labeling #from confident_si...
4,557
38.293103
171
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/run_experiments/run_flexmatch.py
import sys sys.path.append('..') import numpy as np import os import argparse import logging import pickle from tqdm import tqdm from algorithm.pseudo_labeling import Pseudo_Labeling from algorithm.flexmatch import FlexMatch #from algorithm.ups import UPS #from algorithm.csa import CSA from utilities.utils import g...
4,104
37.364486
171
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/run_experiments/run_csa.py
import sys import os sys.path.insert(0,'..') #sys.path.append('..') sys.path.append("../algorithm") sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import numpy as np import os import argparse import logging import pickle from tqdm import tqdm from algorithm.pseudo_labeling import P...
4,521
37.649573
171
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/algorithm/flexmatch.py
# -*- coding: utf-8 -*- """ Created on Mon Nov 15 14:19:22 2021 @author: Vu Nguyen """ import numpy as np from tqdm import tqdm from sklearn.metrics import accuracy_score from xgboost import XGBClassifier from scipy import stats from .pseudo_labeling import Pseudo_Labeling # FlexMatch Strategy for Pseudo-Labeling...
8,767
42.405941
151
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/algorithm/pseudo_labeling.py
import numpy as np from tqdm import tqdm from sklearn.metrics import accuracy_score from xgboost import XGBClassifier import matplotlib.pyplot as plt from sklearn.multioutput import MultiOutputClassifier import copy import sklearn class Pseudo_Labeling(object): # implementation of the master class for pseudo...
16,406
38.439904
144
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/algorithm/__init__.py
0
0
0
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/algorithm/csa.py
# -*- coding: utf-8 -*- """ Created on Mon Nov 15 14:19:22 2021 @author: Vu Nguyen """ import numpy as np from tqdm import tqdm from sklearn.metrics import accuracy_score from xgboost import XGBClassifier import matplotlib.pyplot as plt from scipy import stats import time from .pseudo_labeling import Pseudo_Labe...
16,573
38.368171
155
py
confident-sinkhorn-allocation
confident-sinkhorn-allocation-master/algorithm/ups.py
# -*- coding: utf-8 -*- """ Created on Mon Nov 15 14:19:22 2021 @author: Vu Nguyen """ import numpy as np from tqdm import tqdm from sklearn.metrics import accuracy_score from xgboost import XGBClassifier import matplotlib.pyplot as plt from .pseudo_labeling import Pseudo_Labeling # UPS: ==========================...
7,123
42.175758
135
py
Unimer
Unimer-master/lr_scheduler_wrapper.py
# coding=utf8 from typing import Dict, Any from overrides import overrides from torch.optim.lr_scheduler import MultiStepLR from allennlp.training.learning_rate_schedulers import LearningRateScheduler class PyTorchMultiStepLearningRateSchedulerWrapper(LearningRateScheduler): def __init__(self, lr_scheduler: Mu...
816
27.172414
76
py
Unimer
Unimer-master/evaluations.py
# coding=utf-8 import re import numpy as np from grammars.utils import action_sequence_to_logical_form def evaluate_grammar_based_prediction(instance, prediction, grammar, preprocessor, postprocessor=None): meta_field = instance['meta_field'] question = meta_field['question'] truth_logical_form = meta_fi...
8,052
38.282927
112
py
Unimer
Unimer-master/custom_trainer.py
# coding=utf8 import math import time import torch import logging from typing import Dict, List, Tuple, Optional, Iterable, Union, Callable, NoReturn from allennlp.data import Instance from allennlp.data.iterators.data_iterator import TensorDict, DataIterator from allennlp.models import Model from allennlp.training.ch...
13,380
46.282686
119
py
Unimer
Unimer-master/nni_main.py
# coding=utf-8 import os import re import time import json import shutil import subprocess from absl import app from absl import flags from pprint import pprint import nni # Data flags.DEFINE_integer('cuda_device', 0, 'cuda_device') flags.DEFINE_string('train_data', os.path.join('data', 'geo', 'geo_funql_train.tsv'),...
3,358
33.628866
142
py
Unimer
Unimer-master/model_builder.py
# coding=utf8 import numpy import torch from typing import Dict, List, Callable from overrides import overrides from allennlp.modules.seq2seq_encoders import PytorchSeq2SeqWrapper from allennlp.training.metrics import Metric from allennlp.models.model import Model from allennlp.data.vocabulary import Vocabulary from a...
15,631
50.084967
120
py
Unimer
Unimer-master/__init__.py
0
0
0
py
Unimer
Unimer-master/run_parser.py
# coding=utf-8 import re import os import json import copy import random import torch import itertools from typing import Dict, Any from overrides import overrides from absl import app from absl import flags import numpy as np import torch import torch.optim as optim from torch.optim.lr_scheduler import MultiStepLR fr...
21,059
46.432432
120
py
Unimer
Unimer-master/text2sql_data.py
# coding=utf8 """ Parsing data from https://github.com/jkkummerfeld/text2sql-data/tree/master/data """ import os import json import copy def get_sql_data(basepath, raw_data_path): with open(raw_data_path, 'r') as f: data = json.load(f) question_based_train_dataset, question_based_dev_dataset, questio...
2,982
41.014085
121
py
Unimer
Unimer-master/hyperparameters/read_hyperparameter.py
# coding=utf8 import json import argparse from pprint import pprint def main(path): with open(path, 'r', encoding='utf8') as f: for line in f: results = json.loads(json.loads(line)) pprint(results) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_...
456
20.761905
74
py
Unimer
Unimer-master/neural_models/recombination_seq2seq_copy.py
# coding=utf8 from typing import Dict, List, Tuple import numpy from overrides import overrides import torch import torch.nn.functional as F from torch.nn.modules.linear import Linear from torch.nn.modules.rnn import LSTMCell from allennlp.common.util import START_SYMBOL, END_SYMBOL from allennlp.data.vocabulary imp...
29,535
47.182708
137
py
Unimer
Unimer-master/neural_models/seq2seq_model.py
# coding=utf8 import torch from overrides import overrides from typing import Dict, List, Tuple from allennlp.training.metrics import Metric from allennlp.models.model import Model from allennlp.data.vocabulary import Vocabulary from allennlp.nn import util from allennlp.modules import Attention, TextFieldEmbedder, Se...
3,441
37.244444
98
py
Unimer
Unimer-master/neural_models/utils.py
# coding=utf8 import numpy import torch from typing import List def has_nan(x: torch.Tensor) -> bool: return torch.isnan(x).any() def matrix_cosine_similarity(x: torch.Tensor, y: torch.Tensor, eps: float=1e-8): """ :param x (batch_size, length_1, dim) :param y (batch_size, length_2, dim) :retur...
1,279
31.820513
80
py
Unimer
Unimer-master/neural_models/GNN.py
# coding=utf8 import numpy import torch import torch.nn as nn from allennlp.models.model import Model from allennlp.data.tokenizers import Token from allennlp.common.util import START_SYMBOL, END_SYMBOL from allennlp.data.vocabulary import Vocabulary from allennlp.modules import Embedding from allennlp.modules.text_fi...
33,952
50.057143
122
py
Unimer
Unimer-master/neural_models/GNN2.py
# coding=utf8 import numpy import torch import torch.nn as nn from allennlp.models.model import Model from allennlp.data.tokenizers import Token from allennlp.common.util import START_SYMBOL, END_SYMBOL from allennlp.data.vocabulary import Vocabulary from allennlp.modules import Embedding from allennlp.modules.text_fi...
34,001
50.130827
122
py
Unimer
Unimer-master/neural_models/__init__.py
# coding=utf-8
16
4.666667
14
py
Unimer
Unimer-master/neural_models/grammar_based_models.py
# coding=utf8 import numpy import torch import torch.nn as nn from typing import Dict, List from overrides import overrides from allennlp.training.metrics import Metric from allennlp.models.model import Model from allennlp.data.vocabulary import Vocabulary from allennlp.nn import util from allennlp.modules.text_field_...
3,744
42.546512
134
py
Unimer
Unimer-master/neural_models/recombination_seq2seq.py
# coding=utf8 import numpy import torch from typing import Dict, Tuple, Union, List, Any from allennlp.models import SimpleSeq2Seq from allennlp.data.vocabulary import Vocabulary from allennlp.modules import TextFieldEmbedder, Seq2SeqEncoder, Attention, SimilarityFunction from allennlp.nn import util, InitializerAppli...
11,830
47.093496
122
py
Unimer
Unimer-master/neural_models/modules/grammar_decoder.py
# coding=utf-8 import torch import copy import numpy as np import torch.nn as nn import torch.nn.functional as F from overrides import overrides from allennlp.modules import Embedding from typing import Tuple, List, Dict from .. import utils as nn_utils class LSTMGrammarDecoder(nn.Module): def __init__(self, ...
14,904
44.166667
137
py
Unimer
Unimer-master/neural_models/modules/gnn_multi_head_attention.py
# coding=utf8 import math import torch import numpy as np import torch.nn as nn from allennlp.nn import util from torch.nn import Parameter import torch.nn.functional as F from torch.nn.init import xavier_uniform_ class GNNMatrixMultiHeadAttention(nn.Module): def __init__(self, d_model: int, nhead: int, nlabels...
17,043
40.77451
134
py
Unimer
Unimer-master/neural_models/modules/gnn_encoder.py
# coding=utf8 import copy import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import MultiheadAttention from .gnn_multi_head_attention import GNNMatrixMultiHeadAttention, GNNVectorMultiHeadAttention, \ GNNVectorContinuousMultiHeadAttention, GNNVectorMultiHeadAttention2 def _get_clone...
20,183
48.349633
179
py
Unimer
Unimer-master/neural_models/modules/grammar_copy_decoder_2.py
# coding=utf-8 import torch import copy import numpy as np import torch.nn as nn import torch.nn.functional as F from overrides import overrides from allennlp.modules import Embedding from typing import Tuple, List, Dict from .. import utils as nn_utils class LSTMGrammarCopyDecoder(nn.Module): def __init__(self...
20,773
46.429224
150
py
Unimer
Unimer-master/neural_models/modules/grammar_copy_decoder.py
# coding=utf-8 import torch import copy import numpy as np import torch.nn as nn import torch.nn.functional as F from overrides import overrides from allennlp.modules import Embedding from typing import Tuple, List, Dict from .. import utils as nn_utils class LSTMGrammarCopyDecoder(nn.Module): def __init__(self...
20,697
46.363844
150
py
Unimer
Unimer-master/executions/compare_funql_prolog_denotations.py
# codint=uf8 import re def read_logical_forms(path): ql_dict = dict() with open(path, 'r') as f: for line in f: line = line.strip() splits = line.split('\t') ql_dict[splits[0]] = splits[1] return ql_dict def process_prolog_denotation(denotation): assert d...
2,670
30.05814
83
py
Unimer
Unimer-master/executions/geo/get_sql_denotations.py
# coding=utf8 from sql.evaluator import get_result def evaluate(path): questions, logical_forms = list(), list() with open(path, 'r') as f: for line in f: line = line.strip() splits = line.split('\t') q, l = splits[0], splits[1] questions.append(q) ...
922
27.84375
63
py
Unimer
Unimer-master/executions/geo/get_prolog_denotations.py
# coding=utf8 import os import re import json import argparse import subprocess pattern = re.compile('(\d+)(\[.*\])') script_template = """ :-compile('%s'). :-compile('%s'). %s :-halt. """ def evaluate(path): questions, logical_forms = list(), list() with open(path, 'r') as f: for line in f: ...
2,091
28.464789
94
py
Unimer
Unimer-master/executions/geo/evaluate_sql.py
# coding=utf8 import os import re import json import argparse from sql.evaluator import compare_sqls def evaluate(path, timeout=120): with open(path, 'r') as f: predictions = json.load(f) total = len(predictions) correct = 0 for pidx, p in enumerate(predictions): truth = p['truth...
790
24.516129
87
py
Unimer
Unimer-master/executions/geo/evaluate_lambda_calculus.py
# coding=utf8 import re import os import json import shutil import argparse import subprocess from lambda_calculus.transform_lambda_caculus import transform import sys sys.path += ['..', os.path.join('..', '..')] pattern = re.compile('\(\"([p|t])\",(\d+),Just\s+(.*)\)') failed_pattern = re.compile('\(\"([p|t])\",(\d...
5,659
32.892216
103
py
Unimer
Unimer-master/executions/geo/evaluate_funql.py
# coding=utf8 import os import re import json import argparse import subprocess pattern = re.compile("(\d+)'\s+([yn])'") script_template = """ :-compile('%s'). :-compile('%s'). :-compile('%s'). :-use_module(library(time)). %s :-halt. """ def evaluate(path, timeout=120): with open(path, 'r') as f: pred...
2,316
30.310811
251
py
Unimer
Unimer-master/executions/geo/evaluate_prolog.py
# coding=utf8 import re import os import json import argparse import subprocess import sys sys.path += ['..', '../../'] pattern = re.compile("(\d+)'\s+([yn])'") script_template = """ :-compile('%s'). :-compile('%s'). :-compile('%s'). :-use_module(library(time)). %s :-halt. """ def tokenize(logical_form): no...
4,435
30.913669
243
py
Unimer
Unimer-master/executions/geo/get_lambda_calculus_denotations.py
# coding=utf8 import os import re import json import shutil import argparse import subprocess from geo.lambda_calculus.transform_lambda_caculus import transform pattern = re.compile('\((\d+),Just\s+(.*)\)') failed_pattern = re.compile('\((\d+),Nothing\)') script_template = r""" module Main where import Lib import G...
2,902
28.323232
124
py
Unimer
Unimer-master/executions/geo/__init__.py
0
0
0
py
Unimer
Unimer-master/executions/geo/get_funql_denotations.py
# coding=utf8 import os import re import json import argparse import subprocess pattern = re.compile('(\d+)(\[.*\])') script_template = """ :-compile('%s'). :-compile('%s'). :-compile('%s'). %s :-halt. """ def evaluate(path): questions, logical_forms = list(), list() with open(path, 'r') as f: for ...
1,642
25.934426
92
py
Unimer
Unimer-master/executions/geo/sql/evaluator.py
# coding=utf8 import re import mysql.connector from pprint import pprint db = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="geo", auth_plugin='mysql_native_password' ) def normalize(sql): s = re.sub(' +', ' ', sql) s = s.replace('MAX (', 'MAX(') ...
2,741
32.439024
690
py
Unimer
Unimer-master/executions/geo/lambda_calculus/parse_geobase.py
# coding=utf8 import re def parse_state(path): with open(path, 'r') as f: for line in f: line = line.strip() if line.startswith('state('): info = line[len('state('):-2] # print(info) infos = info.split(',') for idx, c...
7,848
37.665025
112
py
Unimer
Unimer-master/executions/geo/lambda_calculus/transform_lambda_caculus.py
# coding=utf8 import re import json entity_pattern = re.compile('\s([a-z|_|.]+?:[a-z]+)[\s|)]') def process_logic_expression(haskell_lf, is_and): if is_and: target, replace_target, replace_result = "(and:<t*,t>", "and:<t*,t>", "and [" else: target, replace_target, replace_result = "(or:<t*,t...
6,483
42.810811
122
py
Unimer
Unimer-master/executions/geo/lambda_calculus/__init__.py
# coding=utf8
13
13
13
py
Unimer
Unimer-master/executions/geo/lambda_calculus/create_evaluate_script.py
# coding=utf8 import os import json script_template = r""" module Main where import Lib import Geobase import Geofunctions import System.Environment import System.Timeout main :: IO () main = do putStrLn "Execute Lambda Calculus" -- let predicted_result = (count_ (\x -> (and [(river x), (loc x "texas:s")])...
1,605
26.689655
170
py
Unimer
Unimer-master/executions/atis/evaluate_sql.py
# coding=utf8 import os import re import json import argparse from sql.evaluator import compare_sqls def evaluate(path, timeout=120): with open(path, 'r') as f: predictions = json.load(f) total = len(predictions) correct = 0 for pidx, p in enumerate(predictions): truth = p['truth...
956
24.184211
87
py
Unimer
Unimer-master/executions/atis/evaluate_lambda_calculus.py
# coding=utf8 import json import argparse from lambda_calculus.lc_evaluator import compare_lambda_calculus def evaluate(path, timeout=600): with open(path, 'r') as f: predictions = json.load(f) total = len(predictions) correct = 0 for pidx, p in enumerate(predictions): print(pidx) ...
1,076
26.615385
87
py
Unimer
Unimer-master/executions/atis/evaluate_funql.py
# coding=utf8 import json import argparse from funql.evaluator import compare_funql def evaluate(path, timeout=600): with open(path, 'r') as f: predictions = json.load(f) total = len(predictions) correct = 0 for pidx, p in enumerate(predictions): print(pidx) print(p['question...
1,042
26.447368
87
py
Unimer
Unimer-master/executions/atis/__init__.py
0
0
0
py
Unimer
Unimer-master/executions/atis/funql/transform.py
# coding=utf ENTITY_TYPE_MAP = { "ac": "aircraft_code", "al": "airline_code", "ci": "city_name", "ap": "airport_code", "fn": "flight_number", "cl": "class_description", "ti": "time", "pd": "day_period", "mf": "manufacturer", "mn": "month", "da": "day", "i": "integer", ...
2,952
29.760417
102
py
Unimer
Unimer-master/executions/atis/funql/evaluator.py
# coding=utf8 import logging from .query import * from .transform import transform def get_result(funql): python_lf = transform(funql) return_dict = dict() try: results = eval(python_lf) except: logging.error("Exception", exc_info=True) return_dict['is_valid'] = False else...
2,277
30.638889
116
py
Unimer
Unimer-master/executions/atis/funql/__init__.py
0
0
0
py
Unimer
Unimer-master/executions/atis/funql/query.py
# coding=utf8 import re import mysql.connector from pprint import pprint from .transform import transform db = None def get_connection(): global db if db and db.is_connected(): return db else: db = mysql.connector.connect( host="localhost", user="root", ...
80,393
34.651441
399
py
Unimer
Unimer-master/executions/atis/sql/evaluator.py
# coding=utf8 from multiprocessing import Process, Manager import re import mysql.connector from pprint import pprint class TimeoutException(Exception): pass def normalize(sql): s = re.sub(' +', ' ', sql) s = s.replace('MAX (', 'MAX(') s = s.replace('MIN (', 'MIN(') s = s.replace('AVG (', 'AVG(...
3,401
29.648649
551
py
Unimer
Unimer-master/executions/atis/sql/__init__.py
0
0
0
py