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 |
|---|---|---|---|---|---|---|
DAAISy | DAAISy-main/src/utils/translate/instantiate.py | #! /usr/bin/env python3
from collections import defaultdict
from . import build_model
from . import pddl_fd as pddl
from . import pddl_to_prolog
from . import timers
def get_fluent_facts(task, model):
fluent_predicates = set()
for action in task.actions:
for effect in action.effects:
fl... | 3,767 | 33.254545 | 86 | py |
DAAISy | DAAISy-main/src/utils/translate/normalize.py | #! /usr/bin/env python3
import copy
from . import pddl_fd as pddl
class ConditionProxy:
def clone_owner(self):
clone = copy.copy(self)
clone.owner = copy.copy(clone.owner)
return clone
class PreconditionProxy(ConditionProxy):
def __init__(self, action):
self.owner = action
... | 16,177 | 36.105505 | 90 | py |
DAAISy | DAAISy-main/src/utils/translate/sas_tasks.py | SAS_FILE_VERSION = 3
DEBUG = False
class SASTask:
"""Planning task in finite-domain representation.
The user is responsible for making sure that the data fits a
number of structural restrictions. For example, conditions should
generally be sorted and mention each variable at most once. See
the v... | 18,068 | 36.64375 | 78 | py |
DAAISy | DAAISy-main/src/utils/translate/sccs.py | """Tarjan's algorithm for maximal strongly connected components.
We provide two versions of the algorithm for different graph
representations.
Since the original recursive version exceeds python's maximal
recursion depth on some planning instances, this is an iterative
version with an explicit recursion stack (iter_s... | 4,837 | 37.704 | 80 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/f_expression.py | class FunctionalExpression:
def __init__(self, parts):
self.parts = tuple(parts)
def dump(self, indent=" "):
print("%s%s" % (indent, self._dump()))
for part in self.parts:
part.dump(indent + " ")
def _dump(self):
return self.__class__.__name__
def instant... | 3,509 | 31.201835 | 91 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/pddl_types.py | # Renamed from types.py to avoid clash with stdlib module.
# In the future, use explicitly relative imports or absolute
# imports as a better solution.
import itertools
def _get_type_predicate_name(type_name):
# PDDL allows mixing types and predicates, but some PDDL files
# have name collisions between types... | 2,290 | 31.267606 | 76 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/effects.py | from . import conditions
def cartesian_product(*sequences):
# TODO: Also exists in tools.py outside the pddl package (defined slightly
# differently). Not good. Need proper import paths.
if not sequences:
yield ()
else:
for tup in cartesian_product(*sequences[1:]):
fo... | 7,057 | 33.262136 | 98 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/functions.py | class Function:
def __init__(self, name, arguments, type_name):
self.name = name
self.arguments = arguments
if type_name != "number":
raise SystemExit("Error: object fluents not supported\n" +
"(function %s has type %s)" % (name, type_name))
s... | 542 | 35.2 | 77 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/actions.py | import copy
from . import conditions
class Action:
def __init__(self, name, parameters, num_external_parameters,
precondition, effects, cost):
assert 0 <= num_external_parameters <= len(parameters)
self.name = name
self.parameters = parameters
# num_external_param... | 5,428 | 39.819549 | 90 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/predicates.py | class Predicate:
def __init__(self, name, arguments):
self.name = name
self.arguments = arguments
def __str__(self):
return "%s(%s)" % (self.name, ", ".join(map(str, self.arguments)))
def get_arity(self):
return len(self.arguments)
| 278 | 24.363636 | 74 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/__init__.py | from .actions import Action
from .actions import PropositionalAction
from .axioms import Axiom
from .axioms import PropositionalAxiom
from .conditions import Atom
from .conditions import Conjunction
from .conditions import Disjunction
from .conditions import ExistentialCondition
from .conditions import Falsity
from .co... | 1,012 | 32.766667 | 52 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/tasks.py | from . import axioms
from . import predicates
class Task:
def __init__(self, domain_name, task_name, requirements,
types, objects, predicates, functions, init, goal,
actions, axioms, use_metric):
self.domain_name = domain_name
self.task_name = task_name
se... | 2,426 | 32.246575 | 74 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/axioms.py | from . import conditions
class Axiom:
def __init__(self, name, parameters, num_external_parameters, condition):
# For an explanation of num_external_parameters, see the
# related Action class. Note that num_external_parameters
# always equals the arity of the derived predicate.
ass... | 2,609 | 32.896104 | 88 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_fd/conditions.py | # Conditions (of any type) are immutable, because they need to
# be hashed occasionally. Immutability also allows more efficient comparison
# based on a precomputed hash value.
#
# Careful: Most other classes (e.g. Effects, Axioms, Actions) are not!
class Condition:
def __init__(self, parts):
self.parts = ... | 11,179 | 29.380435 | 86 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_parser/lisp_parser.py | __all__ = ["ParseError", "parse_nested_list"]
class ParseError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
# Basic functions for parsing PDDL (Lisp) files.
def parse_nested_list(input_file):
tokens = tokenize(input_file)
next_token ... | 1,427 | 27.56 | 78 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_parser/pddl_file.py | from ...translate import options
from . import lisp_parser
from . import parsing_functions
file_open = open
def parse_pddl_file(type, filename):
try:
# The builtin open function is shadowed by this module's open function.
# We use the Latin-1 encoding (which allows a superset of ASCII, of the
... | 1,272 | 37.575758 | 79 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_parser/__init__.py | from .pddl_file import open
from .parsing_functions import *
| 61 | 19.666667 | 32 | py |
DAAISy | DAAISy-main/src/utils/translate/pddl_parser/parsing_functions.py | import sys
from .. import graph
from .. import pddl_fd as pddl
def parse_typed_list(alist, only_variables=False,
constructor=pddl.TypedObject,
default_type="object"):
result = []
while alist:
try:
separator_position = alist.index("-")
excep... | 18,854 | 36.485089 | 123 | py |
DAAISy | DAAISy-main/src/utils/parser/parser.py | """PDDL parsing.
"""
from .structs import (Type, Predicate, LiteralConjunction, LiteralDisjunction,
Not, Anti, ForAll, Exists, TypedEntity, ground_literal)
import re
class Operator:
"""Class to hold an operator.
"""
def __init__(self, name, params, preconds, effects):
self.n... | 18,447 | 38.844492 | 96 | py |
DAAISy | DAAISy-main/src/utils/parser/structs.py | """Python classes for common PDDL structures"""
import itertools
### PDDL Types, Objects, Variables ###
class Type(str):
"""A PDDL type"""
def __call__(self, entity_name):
return TypedEntity.__new__(TypedEntity, entity_name, self)
# Default type
NULLTYPE = Type("null")
class TypedEntity(str):
"... | 12,029 | 27.987952 | 100 | py |
DAAISy | DAAISy-main/src/utils/parser/__init__.py | from .structs import *
from .parser import PDDLDomainParser
| 60 | 19.333333 | 36 | py |
DAAISy | DAAISy-main/src/interrogation/aia.py | #!/usr/local/bin/python3
# encoding: utf-8
import copy
import sys
import importlib
import itertools
import pickle
import pprint
import time
import subprocess
from collections import Counter, OrderedDict
from itertools import combinations
import random
from ..config import *
from ..query import ExecutePlan
from ..latt... | 74,300 | 48.933468 | 216 | py |
DAAISy | DAAISy-main/src/interrogation/__init__.py | from .aia import AgentInterrogation
| 36 | 17.5 | 35 | py |
DAAISy | DAAISy-main/src/query/exec_plan.py | #!/usr/local/bin/python3
# encoding: utf-8
import copy
import os
import sys
from src.config import *
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '../..'))
class ExecutePlan:
"""
This class executes a plan on a model sarting at an initial state.
:param targetModel: an instance of ... | 5,763 | 33.309524 | 101 | py |
DAAISy | DAAISy-main/src/query/po_query.py | #!/usr/local/bin/python3
# encoding: utf-8
import copy
import os
import subprocess
import sys
from itertools import combinations
from ..config import *
from ..utils import FileUtils
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '../..'))
from . import genericQuery as gc
class Query(gc.GenericQu... | 26,021 | 39.786834 | 114 | py |
DAAISy | DAAISy-main/src/query/genericQuery.py | #!/usr/local/bin/python3
# encoding: utf-8
class GenericQuery(object):
"""
This class serves as a template for the queries.
Each query class has to inherit this class.
"""
def __init__(self):
print("Generic Query")
def call_planner(self, domain_file, problem_file, result_file):
... | 349 | 20.875 | 67 | py |
DAAISy | DAAISy-main/src/query/__init__.py | from .genericQuery import GenericQuery
from .po_query import Query
from .exec_plan import ExecutePlan
| 103 | 19.8 | 38 | py |
EZ-VSL | EZ-VSL-main/test.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import utils
import numpy as np
import argparse
from model import EZVSL
from datasets import get_test_dataset, inverse_normalize
import cv2
def get_arguments():
parser = argparse.ArgumentParser()
... | 8,390 | 42.252577 | 185 | py |
EZ-VSL | EZ-VSL-main/audio_io.py | import av
# import torchaudio
import numpy as np
from fractions import Fraction
# def load_audio_torchaudio(fn):
# data, sr = torchaudio.load(fn)
# return data, sr
def open_audio_av(path):
container = av.open(path)
for stream in container.streams.video:
stream.codec_context.thread_type = av.... | 3,295 | 31 | 105 | py |
EZ-VSL | EZ-VSL-main/utils.py | import os
import json
from torch.optim import *
import numpy as np
from sklearn import metrics
class Evaluator(object):
def __init__(self):
super(Evaluator, self).__init__()
self.ciou = []
def cal_CIOU(self, infer, gtmap, thres=0.01):
infer_map = np.zeros((224, 224))
infer_map... | 2,784 | 29.604396 | 90 | py |
EZ-VSL | EZ-VSL-main/model.py | import torch
from torch import nn
import torch.nn.functional as F
from torchvision.models import resnet18
class EZVSL(nn.Module):
def __init__(self, tau, dim):
super(EZVSL, self).__init__()
self.tau = tau
# Vision model
self.imgnet = resnet18(pretrained=True)
self.imgnet.a... | 2,348 | 35.138462 | 107 | py |
EZ-VSL | EZ-VSL-main/datasets.py | import os
import csv
import numpy as np
from torch.utils.data import Dataset
from torchvision import transforms
from PIL import Image
from scipy import signal
import random
import json
import xml.etree.ElementTree as ET
from audio_io import load_audio_av, open_audio_av
def load_image(path):
return Image.open(path... | 8,126 | 33.004184 | 170 | py |
EZ-VSL | EZ-VSL-main/train.py | import os
import argparse
import builtins
import time
import numpy as np
import torch
import torch.nn.functional as F
from torch import multiprocessing as mp
import torch.distributed as dist
import utils
from model import EZVSL
from datasets import get_train_dataset, get_test_dataset
def get_arguments():
parser... | 10,736 | 36.152249 | 138 | py |
CLNet | CLNet-main/main.py | import torch
import torch.nn as nn
from utils.parser import args
from utils import logger, Trainer, Tester
from utils import init_device, init_model, FakeLR, WarmUpCosineAnnealingLR
from dataset import Cost2100DataLoader
def main():
logger.info('=> PyTorch Version: {}'.format(torch.__version__))
# Environme... | 2,892 | 31.505618 | 91 | py |
CLNet | CLNet-main/dataset/cost2100.py | import os
import numpy as np
import scipy.io as sio
import torch
from torch.utils.data import DataLoader, TensorDataset
__all__ = ['Cost2100DataLoader', 'PreFetcher']
class PreFetcher:
r""" Data pre-fetcher to accelerate the data loading
"""
def __init__(self, loader):
self.ori_loader = loader
... | 4,282 | 35.922414 | 85 | py |
CLNet | CLNet-main/dataset/__init__.py | from .cost2100 import Cost2100DataLoader
| 41 | 20 | 40 | py |
CLNet | CLNet-main/models/clnet.py | r""" The proposed CLNet
"""
import torch
import torch.nn as nn
from collections import OrderedDict
import torch.nn.functional as F
from utils import logger
__all__ = ["clnet"]
class ConvBN(nn.Sequential):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, groups=1):
if not isinstance(kern... | 7,266 | 32.957944 | 154 | py |
CLNet | CLNet-main/models/__init__.py | from .clnet import *
| 21 | 10 | 20 | py |
CLNet | CLNet-main/.ipynb_checkpoints/main-checkpoint.py | import torch
import torch.nn as nn
from utils.parser import args
from utils import logger, Trainer, Tester
from utils import init_device, init_model, FakeLR, WarmUpCosineAnnealingLR
from dataset import Cost2100DataLoader
def main():
logger.info('=> PyTorch Version: {}'.format(torch.__version__))
# Environme... | 2,892 | 31.505618 | 91 | py |
CLNet | CLNet-main/utils/parser.py | import argparse
parser = argparse.ArgumentParser(description='CRNet PyTorch Training')
# ========================== Indispensable arguments ==========================
parser.add_argument('--data-dir', type=str, required=True,
help='the path of dataset.')
parser.add_argument('--scenario', type=st... | 2,082 | 45.288889 | 106 | py |
CLNet | CLNet-main/utils/statics.py | import torch
from packaging import version
__all__ = ['AverageMeter', 'evaluator']
class AverageMeter(object):
r"""Computes and stores the average and current value
Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262
"""
def __init__(self, name):
self.re... | 2,882 | 34.158537 | 111 | py |
CLNet | CLNet-main/utils/logger.py | from datetime import datetime
import sys
import traceback
DEBUG = -1
INFO = 0
EMPH = 1
WARNING = 2
ERROR = 3
FATAL = 4
log_level = INFO
line_seg = ''.join(['*'] * 65)
class LoggerFatalError(SystemExit):
pass
def _format(level, messages):
timestr = datetime.strftime(datetime.now(), '%m.%d/%H:%M')
fathe... | 2,765 | 21.128 | 76 | py |
CLNet | CLNet-main/utils/scheduler.py | import math
from torch.optim.lr_scheduler import _LRScheduler
__all__ = ['WarmUpCosineAnnealingLR', 'FakeLR']
class WarmUpCosineAnnealingLR(_LRScheduler):
def __init__(self, optimizer, T_max, T_warmup, eta_min=0, last_epoch=-1):
self.T_max = T_max
self.T_warmup = T_warmup
self.eta_min = e... | 955 | 33.142857 | 104 | py |
CLNet | CLNet-main/utils/init.py | import os
import random
import thop
import torch
from models import clnet
from utils import logger, line_seg
__all__ = ["init_device", "init_model"]
def init_device(seed=None, cpu=None, gpu=None, affinity=None):
# set the CPU affinity
if affinity is not None:
os.system(f'taskset -p {affinity} {os.ge... | 2,102 | 29.926471 | 79 | py |
CLNet | CLNet-main/utils/__init__.py | from . import logger
from .logger import log_level, line_seg
from .init import *
from .scheduler import *
from .solver import *
| 130 | 15.375 | 39 | py |
CLNet | CLNet-main/utils/solver.py | import time
import os
import torch
from collections import namedtuple
from utils import logger
from utils.statics import AverageMeter, evaluator
__all__ = ['Trainer', 'Tester']
field = ('nmse', 'rho', 'epoch')
Result = namedtuple('Result', field, defaults=(None,) * len(field))
class Trainer:
r""" The training... | 9,472 | 34.215613 | 93 | py |
CLNet | CLNet-main/utils/.ipynb_checkpoints/__init__-checkpoint.py | from . import logger
from .logger import log_level, line_seg
from .init import *
from .scheduler import *
from .solver import *
| 130 | 15.375 | 39 | py |
CLNet | CLNet-main/utils/.ipynb_checkpoints/solver-checkpoint.py | import time
import os
import torch
from collections import namedtuple
from utils import logger
from utils.statics import AverageMeter, evaluator
__all__ = ['Trainer', 'Tester']
field = ('nmse', 'rho', 'epoch')
Result = namedtuple('Result', field, defaults=(None,) * len(field))
class Trainer:
r""" The training... | 9,472 | 34.215613 | 93 | py |
CLNet | CLNet-main/utils/.ipynb_checkpoints/parser-checkpoint.py | import argparse
parser = argparse.ArgumentParser(description='CRNet PyTorch Training')
# ========================== Indispensable arguments ==========================
parser.add_argument('--data-dir', type=str, required=True,
help='the path of dataset.')
parser.add_argument('--scenario', type=st... | 2,082 | 45.288889 | 106 | py |
CLNet | CLNet-main/utils/.ipynb_checkpoints/init-checkpoint.py | import os
import random
import thop
import torch
from models import clnet
from utils import logger, line_seg
__all__ = ["init_device", "init_model"]
def init_device(seed=None, cpu=None, gpu=None, affinity=None):
# set the CPU affinity
if affinity is not None:
os.system(f'taskset -p {affinity} {os.ge... | 2,102 | 29.926471 | 79 | py |
modir | modir-master/drivers/run_warmup.py | import sys
sys.path += ["../"]
import pandas as pd
from transformers import glue_compute_metrics as compute_metrics, glue_output_modes as output_modes, glue_processors as processors
from transformers import (
AdamW,
RobertaConfig,
RobertaForSequenceClassification,
RobertaTokenizer,
get_linear_schedu... | 44,416 | 36.045038 | 145 | py |
modir | modir-master/drivers/run_ann_data_gen.py | import sys
sys.path += ['../']
import torch
import os
from collections import defaultdict
import faiss
from utils.util import (
barrier_array_merge,
convert_to_string_id,
is_first_worker,
StreamingDataset,
EmbeddingCache,
get_checkpoint_no,
get_latest_ann_data
)
import csv
import copy
import... | 31,788 | 31.2077 | 121 | py |
modir | modir-master/drivers/run_ann.py | import sys
sys.path += ['../']
import os
import time
import torch
from data.msmarco_data import GetTrainingDataProcessingFn, GetTripletTrainingDataProcessingFn
from utils.util import (
getattr_recursive,
set_seed,
StreamingDataset,
EmbeddingCache,
get_checkpoint_no,
get_latest_ann_data,
is_f... | 46,511 | 35.027885 | 149 | py |
modir | modir-master/utils/eval_mrr.py | import sys
sys.path += ["../"]
from utils.msmarco_eval import quality_checks_qids, compute_metrics, load_reference
import torch.distributed as dist
import gzip
import faiss
import numpy as np
from data.process_fn import dual_process_fn
from tqdm import tqdm
import torch
import os
from utils.util import concat_key, is_f... | 7,984 | 34.807175 | 100 | py |
modir | modir-master/utils/dpr_utils.py | import collections
import sys
sys.path += ['../']
import glob
import logging
import os
from typing import List, Tuple, Dict
import faiss
import pickle
import numpy as np
import unicodedata
import torch
import torch.distributed as dist
from torch import nn
from torch.serialization import default_restore_location
import ... | 12,483 | 35.934911 | 118 | py |
modir | modir-master/utils/modir_utils.py | import os
import sys
import csv
import numpy as np
import faiss
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader
try:
from apex import amp
except ImportError:
print("apex not imported")
from utils.util import (
is_first_worker,
StreamingDataset,
EmbeddingCache,... | 10,586 | 36.676157 | 115 | py |
modir | modir-master/utils/util.py | import sys
sys.path += ['../']
import pandas as pd
from sklearn.metrics import roc_curve, auc
import gzip
import copy
import torch
from torch import nn
import torch.distributed as dist
from tqdm import tqdm, trange
import os
from os import listdir
from os.path import isfile, join
import json
import logging
import rando... | 12,596 | 29.354217 | 126 | py |
modir | modir-master/utils/msmarco_eval.py | """
This is official eval script opensourced on MSMarco site (not written or owned by us)
This module computes evaluation metrics for MSMARCO dataset on the ranking task.
Command line:
python msmarco_eval_ranking.py <path_to_reference_file> <path_to_candidate_file>
Creation Date : 06/12/2018
Last Modified : 1/21/2019... | 7,724 | 40.756757 | 161 | py |
modir | modir-master/utils/lamb.py | """Lamb optimizer."""
import collections
import math
import torch
from tensorboardX import SummaryWriter
from torch.optim import Optimizer
def log_lamb_rs(optimizer: Optimizer, event_writer: SummaryWriter, token_count: int):
"""Log a histogram of trust ratio scalars in across layers."""
results = collection... | 4,887 | 38.419355 | 109 | py |
modir | modir-master/data/process_fn.py | import torch
def pad_ids(input_ids, attention_mask, token_type_ids, max_length, pad_token, mask_padding_with_zero, pad_token_segment_id, pad_on_left=False):
padding_length = max_length - len(input_ids)
if pad_on_left:
input_ids = ([pad_token] * padding_length) + input_ids
attention_mask = ([0 ... | 5,071 | 43.884956 | 167 | py |
modir | modir-master/data/msmarco_data.py | import sys
import os
import torch
sys.path += ['../']
import gzip
import pickle
from utils.util import pad_input_ids, multi_file_process, numbered_byte_file_generator, EmbeddingCache
import csv
from model.models import MSMarcoConfigDict, ALL_MODELS
from torch.utils.data import DataLoader, Dataset, TensorDataset, Iterab... | 16,967 | 29.085106 | 162 | py |
modir | modir-master/data/DPR_data.py | from os.path import join
import sys
sys.path += ['../']
import argparse
import json
import os
import random
import numpy as np
import torch
from torch.utils.data import Dataset, TensorDataset
from model.models import MSMarcoConfigDict, ALL_MODELS
import csv
from utils.util import multi_file_process, numbered_byte_file_... | 14,512 | 34.923267 | 135 | py |
modir | modir-master/data/filter_train_qrel.py | import sys
fname = sys.argv[1]
qrel = []
with open(fname) as fin:
for line in fin:
a = line.strip().split('\t')
if int(a[-1]) > 0:
a[-1] = '1'
qrel.append('\t'.join(a))
with open(fname, 'w') as fout:
for line in qrel:
print(line, file=fout)
| 300 | 17.8125 | 37 | py |
modir | modir-master/model/domain_classifier.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
class DomainClassifier(nn.Module):
def __init__(self,
args,
input_size=768,
n_class=2):
super(DomainClassifier, sel... | 8,906 | 37.227468 | 104 | py |
modir | modir-master/model/models.py | import sys
sys.path += ['../']
import torch
from torch import nn
from transformers import (
RobertaConfig,
RobertaModel,
RobertaForSequenceClassification,
RobertaTokenizer,
BertModel,
BertTokenizer,
BertConfig
)
import torch.nn.functional as F
from data.process_fn import triple_process_fn, t... | 11,058 | 35.863333 | 144 | py |
dsl | dsl-main/lib/haskell/natural4/src/L4/pdpa_read_predicates.py | import pandas as pd
import numpy as np
import re
fields = ['Predicates']
df = pd.read_csv('pdpa_predicates.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
# as a series
sentences_series = df.Predicates
print(type(sentences_series))
# as an array
sentences_arr... | 941 | 24.459459 | 78 | py |
dsl | dsl-main/lib/haskell/natural4/src/L4/treefrom.py | import spacy_udpipe
import sys
spacy_udpipe.download("en")
nlp = spacy_udpipe.load("en")
texts = sys.argv[1:]
def removePunct(ls):
return [l for l in ls if l[2] != 'punct']
def getTree(text):
for token in nlp(text):
trees = []
Tree = {}
if token.dep_.lower() == 'root':
Tree['root'] = [token.te... | 2,101 | 24.02381 | 100 | py |
dsl | dsl-main/lib/haskell/natural4/src/L4/make_GF_files.py | import spacy_udpipe
import sys
import treefrom
import time
import os
import shutil
from pathlib import Path
filename = sys.argv[-2]
print('load ', filename)
abstractGrammar = sys.argv[-1]
print('load abstract ', abstractGrammar)
# massage the ud_relations to only have the labels
def extractUDLabels(line):
words = l... | 3,240 | 24.519685 | 67 | py |
dsl | dsl-main/lib/haskell/natural4/src/L4/sentence.py | import spacy
import spacy_udpipe
import sys
#nlp = spacy.load("en_core_web_sm")
nlp = spacy_udpipe.load("en")
from spacy import displacy
from spacy_conll import init_parser
con = init_parser(
"en", "udpipe", include_headers=True
)
def getConll(x):
conll = x._.conll_str
return conll
text = sys.argv[1:]
do... | 1,515 | 24.694915 | 117 | py |
container | container-main/main.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import argparse
import datetime
import numpy as np
import time
import torch
import torch.backends.cudnn as cudnn
import json
from pathlib import Path
from timm.data import Mixup
from timm.models import create_model
from timm.loss import LabelSmoothin... | 20,346 | 47.330166 | 119 | py |
container | container-main/losses.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Implements the knowledge distillation loss
"""
import torch
from torch.nn import functional as F
class DistillationLoss(torch.nn.Module):
"""
This module wraps a standard criterion and adds an extra knowledge distillation loss by
taki... | 2,771 | 41.646154 | 114 | py |
container | container-main/engine.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Train and eval functions used in main.py
"""
import math
import sys
from typing import Iterable, Optional
import torch
from timm.data import Mixup
from timm.utils import accuracy, ModelEma
from losses import DistillationLoss
import utils
def t... | 3,508 | 35.175258 | 98 | py |
container | container-main/hubconf.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
from models import *
dependencies = ["torch", "torchvision", "timm"]
| 138 | 22.166667 | 47 | py |
container | container-main/run_with_submitit.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
A script to run multinode training with submitit.
"""
import argparse
import os
import uuid
from pathlib import Path
import main as classification
import submitit
def parse_args():
classification_parser = classification.get_args_parser()
... | 4,075 | 31.094488 | 103 | py |
container | container-main/utils.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Misc functions, including distributed helpers.
Mostly copy-paste from torchvision references.
"""
import io
import os
import time
from collections import defaultdict, deque
import datetime
import torch
import torch.distributed as dist
class Smo... | 7,067 | 28.573222 | 94 | py |
container | container-main/datasets.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import os
import json
from torchvision import datasets, transforms
from torchvision.datasets.folder import ImageFolder, default_loader
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import create_transform
... | 4,114 | 36.409091 | 105 | py |
container | container-main/models.py | import torch
import torch.nn as nn
from functools import partial
import math
from timm.models.vision_transformer import VisionTransformer, _cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_, DropPath, to_2tuple
import pdb
__all__ = [
'deit_tiny_patch16_224', 'deit_sma... | 18,794 | 44.071942 | 164 | py |
container | container-main/samplers.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.distributed as dist
import math
class RASampler(torch.utils.data.Sampler):
"""Sampler that restricts data loading to a subset of the dataset for distributed,
with repeated augmentation.
It ensures that different ... | 2,292 | 37.216667 | 103 | py |
MAgent | MAgent-master/examples/train_against.py | """
Train a model to against existing benchmark
"""
import argparse
import time
import os
import logging as log
import math
import numpy as np
import magent
from magent.builtin.rule_model import RandomActor
def generate_map(env, map_size, handles):
width = height = map_size
init_num = map_size * map_size *... | 9,190 | 35.328063 | 117 | py |
MAgent | MAgent-master/examples/train_arrange.py | """
Train agents to arrange themselves into a specific message
"""
import argparse
import logging as log
import time
import random
import numpy as np
import magent
from magent.builtin.tf_model import DeepQNetwork as RLModel
from magent.utility import FontProvider
def remove_wall(d, cur_pos, wall_set, unit):
if ... | 17,415 | 34.398374 | 159 | py |
MAgent | MAgent-master/examples/train_multi.py | """
A battle contains four types of agents
"""
import argparse
import time
import logging as log
import math
import numpy as np
import magent
def load_config(map_size):
gw = magent.gridworld
cfg = gw.Config()
cfg.set({"map_width": map_size, "map_height": map_size})
cfg.set({"minimap_mode": True})... | 10,600 | 34.454849 | 110 | py |
MAgent | MAgent-master/examples/train_battle_game.py | """
Train script of the battle game
"""
import argparse
import time
import logging as log
import math
import numpy as np
import magent
from magent.builtin.tf_model import DeepQNetwork, DeepRecurrentQNetwork
def generate_map(env, map_size, handles):
width = map_size
height = map_size
init_num = 20
... | 9,203 | 32.714286 | 109 | py |
MAgent | MAgent-master/examples/train_tiger.py | """
Double attack, tigers get reward when they attack a same deer
"""
import argparse
import time
import logging as log
import numpy as np
import magent
from magent.builtin.rule_model import RandomActor
def generate_map(env, map_size, handles):
env.add_walls(method="random", n=map_size*map_size*0.04)
env.a... | 6,540 | 33.792553 | 120 | py |
MAgent | MAgent-master/examples/train_single.py | """
Train a single model by self-play
"""
import argparse
import time
import os
import logging as log
import math
import numpy as np
import magent
def generate_map(env, map_size, handles):
""" generate a map, which consists of two squares of agents"""
width = height = map_size
init_num = map_size * ma... | 7,237 | 33.303318 | 109 | py |
MAgent | MAgent-master/examples/show_battle_game.py | """
Interactive game, Pygame are required.
Act like a general and dispatch your solders.
"""
import os
import magent
from magent.renderer import PyGameRenderer
from magent.renderer.server import BattleServer as Server
if __name__ == "__main__":
magent.utility.check_model('battle-game')
PyGameRenderer().star... | 332 | 19.8125 | 57 | py |
MAgent | MAgent-master/examples/train_pursuit.py | """
Pursuit: predators get reward when they attack prey.
"""
import argparse
import time
import logging as log
import numpy as np
import magent
from magent.builtin.tf_model import DeepQNetwork
def play_a_round(env, map_size, handles, models, print_every, train=True, render=False, eps=None):
env.reset()
en... | 5,713 | 32.22093 | 109 | py |
MAgent | MAgent-master/examples/show_arrange.py | """
Show arrange, pygame are required.
Type messages and let agents to arrange themselves to form these characters
"""
import os
import sys
import argparse
import magent
from magent.renderer import PyGameRenderer
from magent.renderer.server import ArrangeServer as Server
if __name__ == "__main__":
parser = argpa... | 699 | 29.434783 | 99 | py |
MAgent | MAgent-master/examples/api_demo.py | """
First demo, show the usage of API
"""
import magent
# try:
# from magent.builtin.mx_model import DeepQNetwork
# except ImportError as e:
from magent.builtin.tf_model import DeepQNetwork
if __name__ == "__main__":
map_size = 100
# init the game "pursuit" (config file are stored in python/magent/built... | 2,019 | 27.055556 | 88 | py |
MAgent | MAgent-master/examples/train_battle.py | """
Train battle, two models in two processes
"""
import argparse
import time
import logging as log
import math
import numpy as np
import magent
leftID, rightID = 0, 1
def generate_map(env, map_size, handles):
""" generate a map, which consists of two squares of agents"""
width = height = map_size
init_... | 7,958 | 32.868085 | 110 | py |
MAgent | MAgent-master/examples/train_gather.py | """
Train agents to gather food
"""
import argparse
import logging as log
import time
import magent
from magent.builtin.mx_model import DeepQNetwork as RLModel
# change this line to magent.builtin.tf_model to use tensorflow
def load_config(size):
gw = magent.gridworld
cfg = gw.Config()
cfg.set({"map_wi... | 12,437 | 40.738255 | 151 | py |
MAgent | MAgent-master/examples/train_trans.py | """
train agents to walk through some walls, avoiding collide
"""
import argparse
import time
import os
import logging as log
import math
import random
import numpy as np
import magent
from magent.builtin.tf_model import DeepQNetwork, DeepRecurrentQNetwork
def get_config(map_size):
gw = magent.gridworld
cf... | 8,723 | 30.723636 | 109 | py |
MAgent | MAgent-master/python/magent/environment.py | """ base class for environment """
class Environment:
"""see subclass for detailed comment"""
def __init__(self):
pass
def reset(self):
pass
# ====== RUN ======
def get_observation(self, handle):
pass
def set_action(self, handle, actions):
pass
def step(... | 702 | 14.977273 | 43 | py |
MAgent | MAgent-master/python/magent/utility.py | """ some utilities """
import math
import collections
import platform
import numpy as np
import logging
import collections
import os
from magent.builtin.rule_model import RandomActor
class EpisodesBufferEntry:
"""Entry for episode buffer"""
def __init__(self):
self.views = []
self.features ... | 8,715 | 27.48366 | 122 | py |
MAgent | MAgent-master/python/magent/gridworld.py | """gridworld interface"""
from __future__ import absolute_import
import ctypes
import os
import importlib
import numpy as np
from .c_lib import _LIB, as_float_c_array, as_int32_c_array
from .environment import Environment
class GridWorld(Environment):
# constant
OBS_INDEX_VIEW = 0
OBS_INDEX_HP = 1
... | 27,843 | 33.761548 | 123 | py |
MAgent | MAgent-master/python/magent/model.py | """ base model classes"""
try:
import thread
except ImportError:
import _thread as thread
import multiprocessing
import multiprocessing.connection
import sys
import numpy as np
class BaseModel:
def __init__(self, env, handle, *args, **kwargs):
""" init
Parameters
----------
... | 10,411 | 28.91954 | 95 | py |
MAgent | MAgent-master/python/magent/discrete_snake.py | """ Deprecated!! """
from __future__ import absolute_import
import ctypes
import os
import importlib
import numpy as np
from .c_lib import _LIB, as_float_c_array, as_int32_c_array
from .environment import Environment
class DiscreteSnake(Environment):
"""deprecated"""
OBS_VIEW_INDEX = 0
OBS_FEATURE_IND... | 7,151 | 33.057143 | 107 | py |
MAgent | MAgent-master/python/magent/__init__.py | from . import model
from . import utility
from . import gridworld
# some alias
GridWorld = gridworld.GridWorld
ProcessingModel = model.ProcessingModel
round = utility.rec_round
| 178 | 18.888889 | 39 | py |
MAgent | MAgent-master/python/magent/c_lib.py | """ some utility for call C++ code"""
from __future__ import absolute_import
import os
import ctypes
import platform
import multiprocessing
def _load_lib():
""" Load library in build/lib. """
cur_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
lib_path = os.path.join(cur_path, "../... | 1,200 | 26.930233 | 77 | py |
MAgent | MAgent-master/python/magent/builtin/common.py | """Replay buffer for deep q network"""
import numpy as np
class ReplayBuffer:
"""a circular queue based on numpy array, supporting batch put and batch get"""
def __init__(self, shape, dtype=np.float32):
self.buffer = np.empty(shape=shape, dtype=dtype)
self.head = 0
self.capacity =... | 1,165 | 24.347826 | 83 | py |
MAgent | MAgent-master/python/magent/builtin/__init__.py | 0 | 0 | 0 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.