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 |
|---|---|---|---|---|---|---|
z3 | z3-master/scripts/mk_util.py | ############################################
# Copyright (c) 2012 Microsoft Corporation
#
# Auxiliary scripts for generating Makefiles
# and Visual Studio project files.
#
# Author: Leonardo de Moura (leonardo)
############################################
import io
import sys
import os
import re
import getopt
import sh... | 143,588 | 39.550409 | 287 | py |
z3 | z3-master/scripts/mk_make.py | ############################################
# Copyright (c) 2012 Microsoft Corporation
#
# Scripts for generating Makefiles and Visual
# Studio project files.
#
# Author: Leonardo de Moura (leonardo)
############################################
from mk_util import *
from mk_project import *
parse_options()
check_eol(... | 487 | 21.181818 | 45 | py |
z3 | z3-master/scripts/update_header_guards.py | # Copyright (c) 2015 Microsoft Corporation
import os
import re
ifndef = re.compile("#ifndef \_(.*)\_H\_")
doubleu = re.compile("#(.*) (.*)\_\_H\_")
defn = re.compile("#define \_(.*)\_H\_")
endif = re.compile("#endif /\* \_(.*)\_H\_")
def fix_hdr(file):
print(file)
tmp = "%s.tmp" % file
ins = open(... | 1,792 | 23.902778 | 46 | py |
z3 | z3-master/scripts/mk_project.py | ############################################
# Copyright (c) 2012 Microsoft Corporation
#
# Z3 project configuration files
#
# Author: Leonardo de Moura (leonardo)
############################################
from mk_util import *
def init_version():
set_version(4, 12, 3, 0) # express a default build version or p... | 7,467 | 62.288136 | 184 | py |
z3 | z3-master/scripts/mk_def_file.py | # - /usr/bin/env python
"""
Reads a list of Z3 API header files and
generate a ``.def`` file to define the
exported symbols of a dll. This file
can be passed to the ``/DEF`` to the
linker used by MSVC.
"""
import mk_genfile_common
import argparse
import logging
import os
import sys
def main(args):
logging.basicCo... | 1,024 | 26.702703 | 69 | py |
z3 | z3-master/scripts/mk_mem_initializer_cpp.py | # -- /usr/bin/env python
"""
Scans the listed header files for
memory initializers and finalizers and
emits and implementation of
``void mem_initialize()`` and
``void mem_finalize()`` into ``mem_initializer.cpp``
in the destination directory.
"""
import mk_genfile_common
import argparse
import logging
import os
import ... | 1,144 | 26.926829 | 72 | py |
z3 | z3-master/scripts/mk_unix_dist.py | ############################################
# Copyright (c) 2013 Microsoft Corporation
#
# Scripts for automatically generating
# Linux/OSX/BSD distribution zip files.
#
# Author: Leonardo de Moura (leonardo)
############################################
import os
import glob
import re
import getopt
import sys
import s... | 8,497 | 32.992 | 124 | py |
z3 | z3-master/scripts/update_api.py | # - !/usr/bin/env python
############################################
# Copyright (c) 2012 Microsoft Corporation
#
# Scripts for generating Makefiles and Visual
# Studio project files.
#
# Author: Leonardo de Moura (leonardo)
############################################
"""
This script generates the ``api_log_macros.h... | 81,103 | 37.347045 | 223 | py |
z3 | z3-master/scripts/mk_pat_db.py | # -- /usr/bin/env python
"""
Reads a pattern database and generates the corresponding
header file.
"""
import mk_genfile_common
import argparse
import logging
import os
import sys
def main(args):
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argume... | 810 | 26.033333 | 74 | py |
z3 | z3-master/scripts/update_include.py | # Copyright (c) 2017 Microsoft Corporation
import os
import re
is_include = re.compile("#include \"(.*)\"")
is_include2 = re.compile("#include\"(.*)\"")
def fix_include(file, paths):
tmp = "%s.tmp" % file
ins = open(file)
ous = open(tmp,'w')
line = ins.readline()
found = False
while line:
... | 1,855 | 25.514286 | 76 | py |
z3 | z3-master/scripts/mk_consts_files.py | # -- /usr/bin/env python
"""
Reads a list of Z3 API header files and
generate the constant declarations need
by one or more Z3 language bindings
"""
import mk_genfile_common
import argparse
import logging
import os
import sys
def main(args):
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentPa... | 2,919 | 35.049383 | 98 | py |
z3 | z3-master/scripts/mk_install_tactic_cpp.py | # -- /usr/bin/env python
"""
Determines the available tactics from a list of header files and generates a
``install_tactic.cpp`` file in the destination directory that defines a
function ``void install_tactics(tactic_manager& ctx)``.
"""
import mk_genfile_common
import argparse
import logging
import os
import sys
def ... | 1,330 | 29.953488 | 76 | py |
z3 | z3-master/scripts/mk_nuget_task.py | #
# Copyright (c) 2018 Microsoft Corporation
#
# 1. copy over dlls
# 2. copy over libz3.dll for the different architectures
# 3. copy over Microsoft.Z3.dll from suitable distribution
# 4. copy nuspec file from packages
# 5. call nuget pack
# 6. sign package
import json
import os
import zipfile
import sys
import os.p... | 5,105 | 32.372549 | 113 | py |
z3 | z3-master/doc/mk_params_doc.py | # Copyright (c) Microsoft Corporation 2015
"""
Z3 API documentation for parameters
"""
import argparse
import subprocess
import sys
import re
import os
BUILD_DIR='../build'
OUTPUT_DIRECTORY=os.path.join(os.getcwd(), 'api')
def parse_options():
global BUILD_DIR, OUTPUT_DIRECTORY
parser = argparse.ArgumentPars... | 1,772 | 26.276923 | 105 | py |
z3 | z3-master/doc/mk_api_doc.py | # Copyright (c) Microsoft Corporation 2015
"""
Z3 API documentation generator script
"""
import argparse
import os
import shutil
import re
import getopt
import pydoc
import sys
import subprocess
ML_ENABLED=False
MLD_ENABLED=False
JS_ENABLED=False
BUILD_DIR='../build'
DOXYGEN_EXE='doxygen'
TEMP_DIR=os.path.join(os.get... | 14,504 | 36.971204 | 235 | py |
z3 | z3-master/doc/mk_tactic_doc.py | # Copyright (c) Microsoft Corporation 2015
"""
Tactic documentation generator script
"""
import os
import re
import sys
import subprocess
BUILD_DIR='../build'
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
OUTPUT_DIRECTORY = os.path.join(os.getcwd(), 'api')
def doc_path(path):
return os.path.join(SCRIPT... | 3,668 | 27.223077 | 129 | py |
radynpy | radynpy-master/setup.py | from setuptools import setup, find_packages
def readme():
with open('README.rst') as f:
return f.read()
setup(name='radynpy',
version='0.5.0',
description='Analysis tools for Radyn in Python',
long_description=readme(),
url='http://github.com/Goobley/radynpy',
author='Chris O... | 772 | 31.208333 | 106 | py |
radynpy | radynpy-master/radynpy/__init__.py | from . import utils
from . import cdf
from . import matsplotlib
| 64 | 15.25 | 25 | py |
radynpy | radynpy-master/radynpy/cdf/GenRadynCdfHelp.py | import pickle
import re
from itertools import permutations
from collections import deque
from radynpy.cdf.auxtypes import Val, Array, Unknown
with open('RadynKeySizes.pickle', 'rb') as p:
keys = pickle.load(p)
# ntime and maxatomlevels added by cmo
# some corrections made where things are inconsistent with docs
#... | 14,115 | 30.299335 | 248 | py |
radynpy | radynpy-master/radynpy/cdf/CdfLoader.py | import pickle
import os
import numpy as np
import cdflib
fileLocation = os.path.dirname(os.path.abspath(__file__)) + '/'
with open(fileLocation + 'RadynFormatHelp.pickle', 'rb') as p:
helpInfo = pickle.load(p)
typeDict = helpInfo[2]
allVars = {**helpInfo[1]['const'], **helpInfo[1]['timeVary']}
def maybe_lookup(d... | 9,570 | 33.677536 | 113 | py |
radynpy | radynpy-master/radynpy/cdf/RadynKeyFile.py | import os
import cdflib
import pickle
from radynpy.cdf.auxtypes import Val, Array
import numpy as np
cdfFile = '/data/crisp/RadynGrid/radyn_out.val3c_d3_1.0e11_t20s_10kev_fp'
res = {}
cdf = cdflib.CDF(cdfFile)
for k in cdf.cdf_info()['zVariables']:
var = cdf.varget(k)
if len(var.shape) == 0:
# When t... | 780 | 25.931034 | 73 | py |
radynpy | radynpy-master/radynpy/cdf/__init__.py | from .CdfLoader import RadynData, LazyRadynData | 47 | 47 | 47 | py |
radynpy | radynpy-master/radynpy/cdf/auxtypes/AuxTypes.py | class Val:
def __init__(self, val):
self.val = val
def __repr__(self):
return 'Val(%s)' % self.val.__repr__()
class Array:
def __init__(self, shape):
self.shape = shape
def __repr__(self):
return 'Array%s' % self.shape.__repr__()
def idl_repr(self):
s = '[... | 626 | 18.59375 | 48 | py |
radynpy | radynpy-master/radynpy/cdf/auxtypes/__init__.py | from .AuxTypes import * | 23 | 23 | 23 | py |
radynpy | radynpy-master/radynpy/matsplotlib/ContribFn.py | import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import pchip_interpolate, interp1d, griddata
from skimage.exposure import equalize_adapthist, equalize_hist
from palettable.colorbrewer.sequential import Blues_9, PuBu_9
from colour import Color
from matplotlib.ticker import MaxNLocator, LogLocat... | 21,850 | 43.960905 | 124 | py |
radynpy | radynpy-master/radynpy/matsplotlib/__init__.py | from .Opacity import OpcFile, XtNyCalc, xt_calc
from .ContribFn import contrib_fn | 81 | 40 | 47 | py |
radynpy | radynpy-master/radynpy/matsplotlib/Opacity.py | import numpy as np
from radynpy.utils import voigt_H, gaunt_bf_h, hydrogen_absorption, hydrogen_bf_profile
import struct
import os
here = os.path.dirname(os.path.abspath(__file__)) + '/'
# Almost everything in here is a verbatim translation of the Radyn IDL routines
# supplied by M. Carlsson, many improvements could b... | 10,596 | 35.167235 | 121 | py |
radynpy | radynpy-master/radynpy/utils/Utils.py | import numpy as np
from scipy import special
import warnings
def voigt_H(a, v):
'''
Voigt H function -- same as is used in Lightweaver.
'''
z = (v + 1j * a)
return special.wofz(z).real
def gaunt_bf_h(n, qf):
# ;+
# ; gaunt(nn,qf)
# ;
# ; computes the bound-free gaunt f... | 8,398 | 30.456929 | 133 | py |
radynpy | radynpy-master/radynpy/utils/__init__.py | from .Utils import * | 20 | 20 | 20 | py |
GigaSpeech | GigaSpeech-main/toolkits/athena/prepare_data.py | #!/usr/bin/python
# coding=utf-8
# Copyright (C) 2021 ATHENA AUTHORS; Shuaijiang Zhao; Xiaoning Lei
#
# 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/LICE... | 7,248 | 40.1875 | 98 | py |
GigaSpeech | GigaSpeech-main/toolkits/athena/extract_meta.py | #!/usr/bin/python
# coding=utf-8
# Copyright 2021 Xiaomi Corporation (Author: Yongqing Wang)
# Athena Authors (Shuaijiang Zhao)
import sys
import os
import argparse
import json
def get_args():
parser = argparse.ArgumentParser(description="""
This script is used to process raw json dataset of... | 3,579 | 36.291667 | 105 | py |
GigaSpeech | GigaSpeech-main/toolkits/kaldi/extract_meta.py | # Copyright 2021 Xiaomi Corporation (Author: Yongqing Wang)
import sys
import os
import argparse
import json
def get_args():
parser = argparse.ArgumentParser(description="""
This script is used to process raw json dataset of GigaSpeech,
where the long wav is splitinto segments and
data of kaldi ... | 3,494 | 36.580645 | 105 | py |
GigaSpeech | GigaSpeech-main/toolkits/wenet/extract_meta.py | # Copyright 2021 Xiaomi Corporation (Author: Yongqing Wang)
# Mobvoi Corporation (Author: Di Wu)
import sys
import os
import argparse
import json
def get_args():
parser = argparse.ArgumentParser(description="""
This script is used to process raw json dataset of GigaSpeech,
where the l... | 3,125 | 35.348837 | 105 | py |
GigaSpeech | GigaSpeech-main/utils/extract_subset_segments.py | #!/usr/bin/env python3
# coding=utf8
# Copyright 2022 Jiayu DU
'''
This tool is used to extract supervised segments from GigaSpeech,
segments are saved in .wav format, supervisions are saved in a simple .tsv file:
--- exampler tsv begin ---
ID AUDIO BEGIN DURATION TEXT
POD1000000004_S0000017 audio/POD1000000... | 3,742 | 39.247312 | 127 | py |
GigaSpeech | GigaSpeech-main/utils/opus_to_wav.py | # Copyright 2021 Xiaomi (Author:Yongqing Wang)
import os
import argparse
import re
def get_args():
parser = argparse.ArgumentParser(description="""
This script is used to convert opus file into wav file.""")
parser.add_argument('--remove-opus', action='store_true', default='False',
help="""If true, r... | 1,021 | 23.926829 | 76 | py |
GigaSpeech | GigaSpeech-main/utils/gigaspeech_scoring.py | #!/usr/bin/env python3
import os
import argparse
conversational_filler = ['UH', 'UHH', 'UM', 'EH', 'MM', 'HM', 'AH', 'HUH', 'HA', 'ER', 'OOF', 'HEE' , 'ACH', 'EEE', 'EW']
unk_tags = ['<UNK>', '<unk>']
gigaspeech_punctuations = ['<COMMA>', '<PERIOD>', '<QUESTIONMARK>', '<EXCLAMATIONPOINT>']
gigaspeech_garbage_utterance... | 2,186 | 39.5 | 121 | py |
MIED | MIED-main/setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="mied",
version="0.0.1",
author="Lingxiao Li",
description="Mollified interactive energy descent for constrained/unconstrained sampling",
long_description=long_description,
long_descrip... | 626 | 27.5 | 94 | py |
MIED | MIED-main/mied/validators/metrics.py | '''
Metrics to evaluate samples:
1. With ground truth samples, we can compute
a. Wasserstein distance between mu and mu^*
b. KL(mu^* || mu)
2. With access to ground truth density (which is always the case), we can compute
a. KSD, directly applicable
b. KL(mu || mu^*)
'''
import torch
import numpy as np... | 5,968 | 36.074534 | 83 | py |
MIED | MIED-main/mied/validators/particle.py | import torch
import numpy as np
import math
from mied.utils.h5_helpers import save_dict_h5
from mied.utils.batch_eval import batch_eval_index
from mied.validators.metrics import compute_metric
class ParticleValidator:
def __init__(self, *,
problem):
self.problem = problem
self.devi... | 3,751 | 32.20354 | 91 | py |
MIED | MIED-main/mied/solvers/ksdd.py | import torch
import numpy as np
from mied.utils.batch_jacobian import compute_jacobian
from mied.utils.kernels import GaussianKernel
from mied.solvers.particle_base import ParticleBasedSolver
def compute_ksd(X, grad_log_p, kernel):
'''
:param X: (B, D)
:param grad_log_p: (B, D)
:param kernel: an insta... | 2,133 | 30.382353 | 75 | py |
MIED | MIED-main/mied/solvers/lmc.py | import torch
import numpy as np
from mied.solvers.particle_base import ParticleBasedSolver
from mied.utils.batch_jacobian import compute_jacobian
from mied.solvers.mirror_maps import BoxMap, BoxEntropicMap
class LMC(ParticleBasedSolver):
def __init__(self,
lmc_lr,
mirror_map,
... | 1,405 | 32.47619 | 90 | py |
MIED | MIED-main/mied/solvers/no_op_projector.py | import torch
from mied.solvers.projector_base import ProjectorBase
'''
Handle multiple constraints by projecting the gradients using
Dystra algorithm.
'''
class NoOpProjector(ProjectorBase):
def __init__(self):
pass
def step(self, X, update, problem):
return update
def get_violation(sel... | 343 | 17.105263 | 61 | py |
MIED | MIED-main/mied/solvers/particle_base.py | from abc import ABC, abstractmethod
import torch
import numpy as np
from pathlib import Path
from tqdm import trange
from mied.utils.batch_hessian import compute_hessian
class ParticleBasedSolver(ABC):
def __init__(self, *,
problem,
projector,
num_particle,
... | 7,284 | 31.092511 | 86 | py |
MIED | MIED-main/mied/solvers/dynamic_barrier.py | import torch
from mied.solvers.projector_base import ProjectorBase
from mied.utils.batch_jacobian import compute_jacobian
from mied.utils.proj_polyhedra import proj_polyhedra
'''
Handle multiple constraints by projecting the gradients using
Dystra algorithm.
'''
class DynamicBarrier(ProjectorBase):
def __init__(se... | 1,597 | 29.150943 | 73 | py |
MIED | MIED-main/mied/solvers/mirror_maps.py | from abc import ABC, abstractmethod
import torch
def safe_log(x):
# return torch.log(torch.maximum(1e-32, x))
# return torch.log(torch.maximum(1e-8, x))
return torch.log(x + 1e-32)
class MirrorMapBase(ABC):
@abstractmethod
def phi(self, theta):
pass
@abstractmethod
def nabla_phi(... | 1,416 | 22.616667 | 84 | py |
MIED | MIED-main/mied/solvers/svgd.py | import torch
import numpy as np
from mied.solvers.particle_base import ParticleBasedSolver
from mied.utils.batch_jacobian import compute_jacobian
def svgd_update(P, grad_log_p, kernel='gaussian', kernel_h=-1,
riesz_s=-1, riesz_eps=1e-4):
'''
SVGD update with Gaussian kernel.
:param P: (B... | 2,656 | 29.193182 | 78 | py |
MIED | MIED-main/mied/solvers/projector_base.py | from abc import ABC, abstractmethod
import torch
class ProjectorBase:
def __init__(self):
pass
@abstractmethod
def step(self, particles, update_grad, problem, optimizer):
'''
Update particles given update directions update_grad while projecting
to the constraints given by ... | 422 | 19.142857 | 77 | py |
MIED | MIED-main/mied/solvers/mied.py | import torch
import numpy as np
import math
from mied.solvers.particle_base import ParticleBasedSolver
def log_exp_diff(a, b):
'''
Compute log|e^a - e^b| * sign(a-b)
:param a, b: torch scalars
'''
if a > b:
return a + torch.log(1 - torch.exp(b - a))
else:
return -(b + torch.log... | 4,561 | 29.824324 | 88 | py |
MIED | MIED-main/mied/solvers/ipd.py | import torch
import numpy as np
from mied.solvers.particle_base import ParticleBasedSolver
from mied.utils.batch_jacobian import compute_jacobian
'''
Independent particle descent, a dumb baseline.
'''
class IPD(ParticleBasedSolver):
def __init__(self,
**kwargs):
super().__init__(**kwargs... | 798 | 25.633333 | 77 | py |
MIED | MIED-main/mied/problems/problem_base.py | from abc import ABC, abstractmethod
import torch
from mied.utils.batch_jacobian import compute_jacobian
class ProblemBase(ABC):
def __init__(self, *,
device,
in_dim):
'''
A problem describes the sampling problem with unnormalized density
p(x) and constraint... | 1,956 | 20.988764 | 82 | py |
MIED | MIED-main/mied/problems/logistics.py | import torch
import torch.distributions
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
import numpy as np
from tqdm import tqdm
import scipy.io
from mied.problems.problem_base import ProblemBase
class BayesianLogistics(ProblemBase):
def __init__(self, *,
dev... | 5,753 | 32.649123 | 83 | py |
MIED | MIED-main/mied/problems/analytical_problems.py | import torch
import numpy as np
import math
from abc import ABC, abstractmethod
'''
bbox corresponds to the dimension of the variable (=dim) which is
not the same as the intrinsic dimension.
'''
def sample_simplex(dim, batch_size, device):
samples = torch.from_numpy(np.random.dirichlet(
torch.ones([dim]) ... | 17,849 | 31.046679 | 109 | py |
MIED | MIED-main/mied/problems/analytical.py | import torch
from mied.problems.problem_base import ProblemBase
class Analytical(ProblemBase):
def __init__(self, *,
bbox,
embed_dim,
log_p_fn,
prior_sample_fn,
eq_fn=None,
ineq_fn=None,
reparam_f... | 1,621 | 23.208955 | 63 | py |
MIED | MIED-main/mied/problems/fairness_bnn.py | import torch
from torch.distributions import Normal
import torch.nn.functional as F
import numpy as np
import random
from mied.problems.problem_base import ProblemBase
from mied.utils.adult_loader import load_data
# Using the same setup as https://proceedings.neurips.cc/paper/2021/hash/c61aed648da48aa3893fb3eaadd88a7... | 7,599 | 38.175258 | 122 | py |
MIED | MIED-main/mied/utils/kernels.py | from abc import ABC, abstractmethod
import torch
from mied.utils.batch_jacobian import compute_jacobian
class KernelBase(ABC):
@abstractmethod
def eval(self, X, Y):
'''
:param X: (B, D)
:param Y: (B, D)
:return: (B,)
'''
pass
@abstractmethod
def grad_1(... | 1,184 | 19.431034 | 79 | py |
MIED | MIED-main/mied/utils/batch_jacobian.py | import torch
def compute_jacobian(outputs, inputs,
create_graph=True, retain_graph=True):
'''
Compute Jacobian matrices in batch.
:param outputs: (..., D1)
:param inputs: (..., D2)
:returns: (..., D1, D2), computed Jacobian
'''
J = torch.cat([
torch.autograd.gr... | 631 | 27.727273 | 77 | py |
MIED | MIED-main/mied/utils/batch_hessian.py | import torch
from mied.utils.batch_jacobian import compute_jacobian
def compute_hessian(func, inputs):
'''
Compute Hessianmatrices in batch.
:param func: (B, D) -> (B,)
:param inputs: (B, D)
:returns: (B, D, D)
'''
outputs = func(inputs) # (B,)
grad = compute_jacobian(outputs.unsqueeze... | 420 | 21.157895 | 79 | py |
MIED | MIED-main/mied/utils/random.py | import torch
import numpy as np
import random
def seed_all(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
| 280 | 20.615385 | 42 | py |
MIED | MIED-main/mied/utils/proj_polyhedra.py | import torch
def proj_halfspace(p, c, y):
'''
Project p to halfspace defined by {x: c^T x <= y}.
:param p: (B, D)
:param c: (B, D)
:param y: (B,)
:return: (B, D), projected points
'''
norm = torch.norm(c, dim=-1) + 1e-8 # (B,)
c = c / norm.unsqueeze(-1) # (B, D)
y = y / norm #... | 3,305 | 32.393939 | 94 | py |
MIED | MIED-main/mied/utils/path.py | from pathlib import Path
import numpy as np
import re
import h5py
def grab_step_files(parent_dir, regex='step-([0-9]+)\.(h5|npy)'):
parent_dir = Path(parent_dir)
step_files = []
for f in parent_dir.iterdir():
m = re.search(regex, str(f))
if m is not None:
step_files.append((int(... | 676 | 23.178571 | 65 | py |
MIED | MIED-main/mied/utils/h5_helpers.py | import torch
import numpy as np
import h5py
from pathlib import Path
def save_dict_h5(save_dict, h5_path, create_dir=False):
def recurse(remain_dict, parent_handle):
for k, v in remain_dict.items():
if isinstance(v, dict):
child_handle = parent_handle.create_group(k)
... | 893 | 33.384615 | 63 | py |
MIED | MIED-main/mied/utils/ec.py | import torch
import argparse
import yaml
import copy
from pathlib import Path
import shutil
from datetime import datetime
from uuid import uuid4
from collections import namedtuple
import wandb
from mied.utils.shortname import \
convert_method_cls_to_str, convert_method_str_to_cls, \
convert_projector_cls_to_st... | 11,026 | 35.392739 | 82 | py |
MIED | MIED-main/mied/utils/adult_loader.py | # This file is kindly provided by Xingchao Liu ([email protected]).
import pandas as pd
import numpy as np
from pathlib import Path
def generate_one_hot_mat(mat):
upper_bound = np.max(mat)
mat_one_hot = np.zeros((mat.shape[0], int(upper_bound+1)))
for j in range(mat.shape[0]):
mat_one_hot[j, int(ma... | 8,040 | 46.023392 | 159 | py |
MIED | MIED-main/mied/utils/shortname.py | from mied.solvers.mied import MIED
from mied.solvers.svgd import SVGD
from mied.solvers.ksdd import KSDD
from mied.solvers.ipd import IPD
from mied.solvers.lmc import LMC
from mied.solvers.dynamic_barrier import DynamicBarrier
from mied.solvers.no_op_projector import NoOpProjector
g_methods = [
(MIED, 'MIED'),
... | 1,258 | 25.787234 | 67 | py |
MIED | MIED-main/mied/utils/batch_eval.py | import torch
from tqdm import tqdm
def batch_eval_index(f, total_count, batch_size=1024,
result_device=torch.device('cpu'),
detach=True,
no_tqdm=False):
'''
Batch evaluate f.
:param f: function to be evalutated. It should take in (B,) of indic... | 1,050 | 32.903226 | 76 | py |
MIED | MIED-main/tests/analytical/run.py | import torch
import argparse
from pathlib import Path
import math
import wandb
import matplotlib.pyplot as plt
from mied.validators.particle import ParticleValidator
from mied.utils.random import seed_all
from mied.utils.ec import ExperimentCoordinator
from mied.problems.analytical_problems import create_problem
from... | 4,651 | 33.977444 | 77 | py |
MIED | MIED-main/tests/fairness_bnn/run.py | import torch
import argparse
from pathlib import Path
import math
import h5py
import wandb
from mied.validators.particle import ParticleValidator
from mied.utils.random import seed_all
from mied.utils.ec import ExperimentCoordinator
from mied.utils.h5_helpers import save_dict_h5
from mied.problems.fairness_bnn import F... | 2,025 | 27.138889 | 60 | py |
MIED | MIED-main/tests/logistics/run.py | import torch
import argparse
from pathlib import Path
import math
import h5py
import wandb
from mied.validators.particle import ParticleValidator
from mied.utils.random import seed_all
from mied.utils.ec import ExperimentCoordinator
from mied.utils.h5_helpers import save_dict_h5
from mied.problems.logistics import Baye... | 4,112 | 32.991736 | 83 | py |
blend | blend-master/tools/libsvm-3.22/tools/easy.py | #!/usr/bin/env python
import sys
import os
from subprocess import *
if len(sys.argv) <= 1:
print('Usage: {0} training_file [testing_file]'.format(sys.argv[0]))
raise SystemExit
# svm, grid, and gnuplot executable files
is_win32 = (sys.platform == 'win32')
if not is_win32:
svmscale_exe = "../svm-scale"
svmtrain_... | 2,699 | 32.75 | 104 | py |
blend | blend-master/tools/libsvm-3.22/tools/checkdata.py | #!/usr/bin/env python
#
# A format checker for LIBSVM
#
#
# Copyright (c) 2007, Rong-En Fan
#
# All rights reserved.
#
# This program is distributed under the same license of the LIBSVM package.
#
from sys import argv, exit
import os.path
def err(line_no, msg):
print("line {0}: {1}".format(line_no, msg))
# works... | 2,479 | 21.752294 | 130 | py |
blend | blend-master/tools/libsvm-3.22/tools/grid.py | #!/usr/bin/env python
__all__ = ['find_parameters']
import os, sys, traceback, getpass, time, re
from threading import Thread
from subprocess import *
if sys.version_info[0] < 3:
from Queue import Queue
else:
from queue import Queue
telnet_workers = []
ssh_workers = []
nr_local_worker = 1
class GridOption:
def _... | 15,316 | 29.572854 | 105 | py |
blend | blend-master/tools/libsvm-3.22/tools/subset.py | #!/usr/bin/env python
import os, sys, math, random
from collections import defaultdict
if sys.version_info[0] >= 3:
xrange = range
def exit_with_help(argv):
print("""\
Usage: {0} [options] dataset subset_size [output1] [output2]
This script randomly selects a subset of the dataset.
options:
-s method : method of... | 3,202 | 25.471074 | 84 | py |
blend | blend-master/tools/libsvm-3.22/python/svm.py | #!/usr/bin/env python
from ctypes import *
from ctypes.util import find_library
from os import path
import sys
if sys.version_info[0] >= 3:
xrange = range
__all__ = ['libsvm', 'svm_problem', 'svm_parameter',
'toPyModel', 'gen_svm_nodearray', 'print_null', 'svm_node', 'C_SVC',
'EPSILON_SVR', 'L... | 9,603 | 28.015106 | 122 | py |
blend | blend-master/tools/libsvm-3.22/python/svmutil.py | #!/usr/bin/env python
import os
import sys
from svm import *
from svm import __all__ as svm_all
__all__ = ['evaluations', 'svm_load_model', 'svm_predict', 'svm_read_problem',
'svm_save_model', 'svm_train'] + svm_all
sys.path = [os.path.dirname(os.path.abspath(__file__))] + sys.path
def svm_read_problem(... | 8,695 | 32.064639 | 113 | py |
blend | blend-master/tools/beer_2.0/lib/platt.py | #!/usr/bin/env python
from sys import argv
#from svm import *
from math import log, exp
from string import atof
from random import randrange
#--[Basic Function]---------------------------------------------------------------------
#input decision_values, real_labels{1,-1}, #positive_instances, #negative_instances
#outpu... | 3,067 | 22.242424 | 88 | py |
blend | blend-master/tools/characTER-master/CharacTER.py | #! /usr/bin/env python2
# -*- coding:utf-8 -*-
"""
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distribute... | 11,034 | 32.038922 | 86 | py |
blend | blend-master/tools/dpmf/tools/stanford-postagger-2013-04-04/addStartTag.py | #!/usr/local/bin/python2.7
import sys
f = open(sys.argv[1]);
line = f.readline()
while line:
print '@START',
print line,
line = f.readline()
f.close()
| 165 | 14.090909 | 27 | py |
blend | blend-master/tools/dpmf/tools/stanford-postagger-2013-04-04/rmPOS.py | #!/usr/bin/python
import sys
import string
info = '''
'''
def filter(input, output):
fin = open(input, 'rU')
fout = open(output, 'w')
count = 0
for line in fin:
newline = ''
list = line.split(' ')
for e in range(0,len(list)):
p = list[e].rfind('/')
wo... | 754 | 18.358974 | 52 | py |
blend | blend-master/tools/dpmf/tools/stanford-postagger-2013-04-04/reback.py | #!/usr/local/bin/python2.7
import sys
f = open(sys.argv[1]);
line = f.readline()
lineAll = ''
while line:
lineAll = lineAll + line.strip('\n') +" "
line = f.readline()
f.close()
strlist = lineAll.split('@START')
for v in strlist:
if(len(v)>1):
v = v.strip()
pos = v.find(' ',0)
newlin... | 517 | 23.666667 | 58 | py |
blend | blend-master/tools/dpmf/scripts/meteorForm-recall.py | #!/usr/local/bin/python2.7
import sys
f = open(sys.argv[1]);
#print sys.argv[1]
line = f.readline()
while line:
if(line.find("Segment ") > -1):
strlist = line.split('\t')
pre = strlist[2]
print pre
if(line.find("Recall:")>-1):
pre = line[24:len(line)]
#print "sys level me... | 367 | 20.647059 | 39 | py |
blend | blend-master/tools/dpmf/scripts/addStartTag.py | #!/usr/local/bin/python2.7
import sys
f = open(sys.argv[1]);
line = f.readline()
while line:
print '@START',
print line,
line = f.readline()
f.close()
| 165 | 14.090909 | 27 | py |
blend | blend-master/tools/dpmf/scripts/2CorreForm.py | #!/usr/local/bin/python2.7
import sys
import math
fin = open(sys.argv[1]);
fseg = open(sys.argv[2],'w');
fsys = open(sys.argv[3],'w');
line = fin.readline()
while line:
line=line.strip()
p1=line.find('.')
p2=line.rfind('.')
year=line[0:p1]
sysname=line[p1+1:p2]
lan=line[p2+1:len(line)]
fintm... | 877 | 24.823529 | 82 | py |
blend | blend-master/tools/dpmf/scripts/rmPOS.py | #!/usr/bin/python
import sys
import string
info = '''
'''
def filter(input, output):
fin = open(input, 'rU')
fout = open(output, 'w')
count = 0
for line in fin:
newline = ''
list = line.split(' ')
for e in range(0,len(list)):
p = list[e].rfind('/')
wo... | 754 | 18.358974 | 52 | py |
blend | blend-master/tools/dpmf/scripts/stfdeptree2form.py | #!/usr/local/bin/python2.7
import sys
f = open(sys.argv[1]);
line = f.readline()
while line:
if(len(line)>1):
p=line.find('(')
rela=line[0:p]
newline=line[p+1:len(line)-2]
strlist = newline.split(', ')
p=strlist[1].rfind('-')
w1=strlist[1][0:p]
posi1=strlist[1... | 566 | 23.652174 | 52 | py |
blend | blend-master/tools/dpmf/scripts/probPreciRecall.py | #!/usr/local/bin/python2.7
import sys
dpm_f = sys.argv[1]
preci_f = sys.argv[2]
recall_f = sys.argv[3]
arg = float(sys.argv[4])
score = 0
dpmL, preciL, recallL = [], [], []
for idx, line in enumerate(open(dpm_f, 'rU')):
dpmL.append(float(line.strip()))
for idx, line in enumerate(open(preci_f, 'rU')):
preciL... | 689 | 21.258065 | 56 | py |
blend | blend-master/tools/dpmf/scripts/meteorForm-precision.py | #!/usr/local/bin/python2.7
import sys
f = open(sys.argv[1]);
#print sys.argv[1]
line = f.readline()
while line:
if(line.find("Segment ") > -1):
strlist = line.split('\t')
pre = strlist[1]
print pre
if(line.find("Precision:")>-1):
pre = line[24:len(line)]
#print "sys level... | 370 | 20.823529 | 39 | py |
blend | blend-master/tools/dpmf/scripts/syscore-prob.py | #!/usr/local/bin/python2.7
import sys
f = open(sys.argv[1]);
line = f.readline()
line = f.readline()
score=0
cnt=1
while line:
score = score + float(line)
line = f.readline()
cnt = cnt+1
print score,
f.close()
fa = open(sys.argv[1],'a');
score = score/float(3000)
fa.write("sys level t2sts "+str(score))
| 317 | 17.705882 | 39 | py |
blend | blend-master/tools/dpmf/scripts/probPreciRecall-sys.py | #!/usr/local/bin/python2.7
import sys
fin1 = open(sys.argv[1]);
fin2 = open(sys.argv[2]);
fin3 = open(sys.argv[3]);
arg = float(sys.argv[4])
line1 = fin1.readline()
line2 = fin2.readline()
line3 = fin3.readline()
dict1={}
while line1:
strlistd = line1.split('\t')
newstr = strlistd[1] + '\t' + strlistd[2] + '... | 1,230 | 23.137255 | 68 | py |
blend | blend-master/tools/dpmf/scripts/reback.py | #!/usr/local/bin/python2.7
import sys
f = open(sys.argv[1]);
line = f.readline()
lineAll = ''
while line:
lineAll = lineAll + line.strip('\n') +" "
line = f.readline()
f.close()
strlist = lineAll.split('@START')
for v in strlist:
if(len(v)>1):
v = v.strip()
pos = v.find(' ',0)
newlin... | 517 | 23.666667 | 58 | py |
blend | blend-master/tools/meteor-1.4/mt-diff/mt-diff.py | #!/usr/bin/env python
import math, os, re, shutil, subprocess, sys, tempfile
# MT-Diff: measure changes in segment-level quality between two systems
# according to BLEU and Meteor
bleu_script = os.path.abspath(os.path.join(os.path.dirname(__file__), \
'files', 'mteval-v13m.pl'))
meteor_jar = os.path.abspath(os.pat... | 6,503 | 31.19802 | 111 | py |
blend | blend-master/tools/meteor-1.4/scripts/build_wordnet_files.py | #!/usr/bin/env python
import os, sys
# Set for WordNet3
excFiles = ["adj.exc", "adv.exc", "noun.exc", "verb.exc"]
senseFile = "index.sense"
nounFile = "data.noun"
verbFile = "data.verb"
adjFile = "data.adj"
nounRelations = ["@", "@i", "~", "~i"] # Hypernym (instance), Hyponym (instance)
verbRelations = ["@", "~",... | 3,141 | 24.136 | 80 | py |
blend | blend-master/tools/meteor-1.4/scripts/combine_segcor_trainset.py | #!/usr/bin/env python
import os, shutil, sys
def main(argv):
if len(argv) < 3:
print "Create a single Meteor training set from HTER test sets"
print "usage:", argv[0], "<outDir> <hterDir1> [hterDir2] ..."
sys.exit(1)
outDir = argv[1]
hterDirs = argv[2:]
if os.path.exists(outDir):
print "File", outDir, ... | 780 | 24.193548 | 70 | py |
blend | blend-master/tools/meteor-1.4/scripts/sgmlize.py | #!/usr/bin/env python
# Convert to and from SGML easily. There exist many SGML/XML standards
# for MT evaulation. This script produces files in a format compatible
# with meteor-*.jar, mteval-v*.pl, and tercom.*.jar
import codecs, re, sys
sys.stdin = codecs.getreader('utf-8')(sys.stdin)
sys.stdout = codecs.getwrit... | 1,881 | 30.366667 | 84 | py |
blend | blend-master/tools/meteor-1.4/scripts/unigram_stats.py | #!/usr/bin/env python
import os, subprocess, sys
# Output line:
# P R f1 frag
# Unigrams, surface forms only
# Params set so frag = (chunks/matches)
def main(argv):
if len(argv) < 2:
print 'usage: {0} hyps refs > f1.out'.format(argv[0])
sys.exit(1)
hyp = argv[1]
ref = argv[2]
... | 1,351 | 23.581818 | 80 | py |
blend | blend-master/tools/meteor-1.4/scripts/armageddon.py | #!/usr/bin/env python
# Tune Meteor parameters quickly using Sun Grid Engine
# Script submits 21 job array, 1 cpu / 3gb each
import os, subprocess, sys
SGE_SCRIPT = '''
### Job name: m.xx
#$ -N "m.{0}"
### Log files go in the log dir
#$ -e {2}/m.err
#$ -o {2}/m.out
### Just one slot
#$ -pe smp 1
### 2g for Java h... | 4,071 | 30.083969 | 253 | py |
blend | blend-master/tools/meteor-1.4/scripts/delete_stray_matches.py | #!/usr/bin/env python
import re, sys
DEFAULT_DIST = 0.0
DEFAULT_LEN = 0
def main(argv):
# Directions
if len(argv[1:]) < 1:
sys.stderr.write('Using defaults - for help, use {0} -h\n'.format(argv[0]))
min_dist = DEFAULT_DIST
min_len = DEFAULT_LEN
words = []
# help or min distance... | 4,642 | 33.909774 | 83 | py |
blend | blend-master/tools/meteor-1.4/scripts/agg.py | #!/usr/bin/env python
# Aggregate: sum input lines by column. Useful for aggregating
# MeteorStats lines as a MERT implementation would.
from sys import argv, exit, stdin
parse = int
if len(argv) > 1:
if argv[1].startswith('-h'):
print 'usage: agg [-f] FILE'
exit()
if argv[1] == '-f':
... | 814 | 19.375 | 63 | py |
blend | blend-master/tools/meteor-1.4/scripts/rm_que.py | #!/usr/bin/env python
import gzip, sys
if len(sys.argv[1:]) < 2:
print 'usage', sys.argv[0], 'original.gz', 'clean.gz'
sys.exit(1)
f_in = gzip.open(sys.argv[1])
f_out = gzip.open(sys.argv[2], 'wb')
while True:
prob = f_in.readline()
if not prob:
break
p1 = f_in.readline()
p2 = f_in.r... | 536 | 17.517241 | 57 | py |
blend | blend-master/tools/meteor-1.4/scripts/freq.py | #!/usr/bin/env python
# Simple word relative frequency counter. Used to create
# function word lists.
from sys import stdin, argv
freq = {}
total = 0
if argv[1:]:
stdin = open(argv[1], 'r')
while True:
line = stdin.readline()
if not line:
break
f = line.split()
for w in f:
freq... | 476 | 18.08 | 57 | py |
blend | blend-master/tools/meteor-1.4/scripts/rm_word_accumulation.py | #!/usr/bin/env python
import gzip, sys
if len(sys.argv[1:]) < 2:
print 'Remove paraphrases with word accumulation:'
print 'Paraphrases where p1 is a substring of p2 or vice versa will be removed'
print ''
print 'usage', sys.argv[0], 'original.gz', 'clean.gz'
sys.exit(1)
f_in = gzip.open(sys.argv[... | 688 | 21.225806 | 83 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.