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 |
|---|---|---|---|---|---|---|
pegnn | pegnn-master/src/datasets/csv_dataset.py | from typing import Iterator
from torch_geometric.data import InMemoryDataset, Data
from torch_geometric.loader import DataLoader
import torch
import pandas as pd
import numpy as np
from pymatgen.core.structure import Structure
from pymatgen.io.ase import AseAtomsAdaptor
from ase.neighborlist import neighbor_list
from ... | 4,203 | 28.194444 | 172 | py |
pegnn | pegnn-master/src/utils/scaler.py | import torch
import torch.nn as nn
import numpy as np
from torch_geometric.loader import DataLoader
import tqdm
from src.utils.geometry import Geometry
from typing import Tuple
class LatticeScaler(nn.Module):
def __init__(self):
super(LatticeScaler, self).__init__()
self.mean = nn.Parameter(... | 6,553 | 32.269036 | 128 | py |
pegnn | pegnn-master/src/utils/shape.py | import torch
from typing import Tuple, List, Union, Dict
from collections import namedtuple
class shape:
def __init__(self, *dim: Union[int, str], dtype=None):
assert isinstance(dim, tuple)
for d in dim:
assert (type(d) == int and -1 <= d) or type(d) == str
assert (dtype is N... | 2,051 | 27.901408 | 100 | py |
pegnn | pegnn-master/src/utils/polar.py | import torch
import unittest
__all__ = ["polar"]
def polar(a: torch.FloatTensor, side: str = "right"):
if side not in ["right", "left"]:
raise ValueError("`side` must be either 'right' or 'left'")
assert a.ndim == 3 and a.shape[1] == a.shape[2]
w, s, vh = torch.linalg.svd(a, full_matrices=False... | 3,936 | 25.782313 | 83 | py |
pegnn | pegnn-master/src/utils/timeout.py | import signal
class Timeout(Exception):
pass
class timeout:
def __init__(self, seconds, error_message=None):
if error_message is None:
error_message = "test timed out after {}s.".format(seconds)
self.seconds = seconds
self.error_message = error_message
def handle_tim... | 585 | 23.416667 | 71 | py |
pegnn | pegnn-master/src/utils/encoder.py | import torch
import json
import numpy as np
from ase.spacegroup import Spacegroup
__all__ = ["CrystalEncoder"]
class CrystalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, torch.Tensor):
return obj.t... | 561 | 27.1 | 59 | py |
pegnn | pegnn-master/src/utils/replay.py | import torch
class Replay:
def __init__(self, batch_size: int, max_depth: int = 32, proba_in: float = 0.1):
self.batch_size = batch_size
self.max_depth = max_depth
self.proba_in = proba_in
self.cell = torch.zeros(0, 3, 3, dtype=torch.float32)
self.pos = torch.zeros(0, 3, d... | 2,510 | 36.477612 | 88 | py |
pegnn | pegnn-master/src/utils/geometry.py | import torch
import torch.nn.functional as F
from .shape import build_shapes, assert_tensor_match, shape
from .timeout import timeout
from dataclasses import dataclass
import crystallographic_graph
@dataclass(init=False)
class Geometry:
batch: torch.LongTensor
batch_edges: torch.LongTensor
batch_triple... | 11,649 | 30.233244 | 79 | py |
pegnn | pegnn-master/src/utils/io.py | from ctypes import Structure
import torch
import torch.nn.functional as F
from ase.spacegroup import crystal
import ase.io as io
import pandas as pd
from src.utils.visualize import select
import os
def write_cif(file_name, idx, cell, pos, z, num_atoms):
cell, pos, z = select(idx, cell, pos, z, num_atoms)
... | 2,197 | 27.179487 | 75 | py |
pegnn | pegnn-master/src/utils/elements.py | elements = {
"H": 1,
"He": 2,
"Li": 3,
"Be": 4,
"B": 5,
"C": 6,
"N": 7,
"O": 8,
"F": 9,
"Ne": 10,
"Na": 11,
"Mg": 12,
"Al": 13,
"Si": 14,
"P": 15,
"S": 16,
"Cl": 17,
"Ar": 18,
"K": 19,
"Ca": 20,
"Sc": 21,
"Ti": 22,
"V": 23,
... | 1,663 | 12.752066 | 14 | py |
pegnn | pegnn-master/src/utils/debug.py | def check_grad(model, verbose=True, debug=False):
must_break = False
for k, p in model.named_parameters():
if (p.grad is not None) and (p.grad != p.grad).any():
must_break = True
break
if must_break:
if verbose:
print("grad")
for k, p in model... | 544 | 27.684211 | 85 | py |
pegnn | pegnn-master/src/utils/visualize.py | import torch
from ase.spacegroup import crystal
from ase.visualize.plot import plot_atoms
import matplotlib.pyplot as plt
from src.utils.elements import elements
from src.models.operator.utils import lattice_params_to_matrix_torch
def select(idx, cell, pos, z, num_atoms):
struct_idx = torch.arange(num_atoms.shap... | 3,558 | 28.172131 | 80 | py |
T2TL | T2TL-main/src/T2TL.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from context_model import ContextACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
## G... | 17,759 | 50.32948 | 296 | py |
T2TL | T2TL-main/src/ltl_progression.py | """
This code allows to progress LTL formulas. It requires installing the SPOT library:
- https://spot.lrde.epita.fr/install.html
To encode LTL formulas, we use tuples, e.g.,
(
'and',
('until','True', ('and', 'd', ('until','True','c'))),
('until','True', ('and', 'a', ('until','True', ('a... | 7,821 | 33.008696 | 161 | py |
T2TL | T2TL-main/src/T1TL_pretrain.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from recurrent_model import RecurrentACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
... | 16,899 | 50.057402 | 265 | py |
T2TL | T2TL-main/src/context_model.py | """
This is the description of the deep NN currently being used.
It is a small CNN for the features with an GRU encoding of the LTL task.
The features and LTL are preprocessed by utils.format.get_obss_preprocessor(...) function:
- In that function, I transformed the LTL tuple representation into a text representati... | 24,186 | 42.817029 | 122 | py |
T2TL | T2TL-main/src/T2TL_pretrain.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from context_model import ContextACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
## G... | 18,009 | 51.354651 | 313 | py |
T2TL | T2TL-main/src/ltl_wrappers.py | """
This is a simple wrapper that will include LTL goals to any given environment.
It also progress the formulas as the agent interacts with the envirionment.
However, each environment must implement the followng functions:
- *get_events(...)*: Returns the propositions that currently hold on the environment.
-... | 7,689 | 38.84456 | 167 | py |
T2TL | T2TL-main/src/env_model.py | import torch
import torch.nn as nn
from envs import *
from gym.envs.classic_control import PendulumEnv
def getEnvModel(env, obs_space):
env = env.unwrapped
if isinstance(env, ZonesEnv):
return ZonesEnvModel(obs_space)
# Add your EnvModel here...
# The default case (No environment observati... | 4,146 | 28.204225 | 98 | py |
T2TL | T2TL-main/src/model.py | """
This is the description of the deep NN currently being used.
It is a small CNN for the features with an GRU encoding of the LTL task.
The features and LTL are preprocessed by utils.format.get_obss_preprocessor(...) function:
- In that function, I transformed the LTL tuple representation into a text representati... | 22,185 | 42.247563 | 136 | py |
T2TL | T2TL-main/src/train_PreGNNAgent.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from recurrent_model import RecurrentACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
... | 16,595 | 49.443769 | 265 | py |
T2TL | T2TL-main/src/transEncoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
class ContextTransformer(nn.Module):
def __init__(self, obs_size, obsr_dim, d_model, d_out, pool, args, context=False):
super(ContextTransformer, self).__init__()
self.context = context
self.obsr_dim = obsr_dim
... | 15,896 | 43.90678 | 121 | py |
T2TL | T2TL-main/src/test_safety.py | import argparse
import time
import sys
import numpy as np
import glfw
import utils
import torch
import gym
import safety_gym
import ltl_wrappers
import ltl_progression
from gym import wrappers, logger
from envs.safety import safety_wrappers
class RandomAgent(object):
"""This agent picks actions randomly"""
de... | 4,800 | 33.292857 | 153 | py |
T2TL | T2TL-main/src/manual_control.py | #!/usr/bin/env python3
import time
import argparse
import numpy as np
import gym
import gym_minigrid
import ltl_wrappers
from gym_minigrid.wrappers import *
from gym_minigrid.window import Window
from envs.minigrid.adversarial import *
def redraw(img):
if not args.agent_view:
img = base_env.render(mode=... | 2,563 | 20.546218 | 93 | py |
T2TL | T2TL-main/src/run_openai.py | """
This code uses the OpenAI baselines to learn the policies.
However, the current implementation ignores the LTL formula.
I left this code here as a reference and for debugging purposes.
"""
try:
from mpi4py import MPI
except ImportError:
MPI = None
import numpy as np
import tensorflow as tf
import gym, mult... | 5,164 | 30.882716 | 125 | py |
T2TL | T2TL-main/src/ltl_samplers.py | """
This class is responsible for sampling LTL formulas typically from
given template(s).
@ propositions: The set of propositions to be used in the sampled
formula at random.
"""
import random
class LTLSampler():
def __init__(self, propositions):
self.propositions = propositions
def ... | 8,122 | 39.615 | 234 | py |
T2TL | T2TL-main/src/recurrent_model.py | """
This is the description of the deep NN currently being used.
It is a small CNN for the features with an GRU encoding of the LTL task.
The features and LTL are preprocessed by utils.format.get_obss_preprocessor(...) function:
- In that function, I transformed the LTL tuple representation into a text representati... | 6,302 | 37.2 | 134 | py |
T2TL | T2TL-main/src/policy_network.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical, Normal
from gym.spaces import Box, Discrete
class PolicyNetwork(nn.Module):
def __init__(self, in_dim, action_space, hiddens=[], scales=None, activation=nn.Tanh()):
super().__init__()
... | 2,026 | 33.355932 | 92 | py |
T2TL | T2TL-main/src/T1TL.py |
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import glob
from math import floor
import utils
from model import ACModel
from recurrent_model import RecurrentACModel
if __name__ == '__main__':
# Parse arguments
parser = argparse.ArgumentParser()
... | 16,666 | 49.506061 | 268 | py |
T2TL | T2TL-main/src/torch_ac/format.py | import torch
def default_preprocess_obss(obss, device=None):
return torch.tensor(obss, device=device) | 106 | 25.75 | 47 | py |
T2TL | T2TL-main/src/torch_ac/model.py | from abc import abstractmethod, abstractproperty
import torch.nn as nn
import torch.nn.functional as F
class ACModel:
recurrent = False
@abstractmethod
def __init__(self, obs_space, action_space):
pass
@abstractmethod
def forward(self, obs):
pass
class RecurrentACModel(ACModel):
... | 485 | 17.692308 | 48 | py |
T2TL | T2TL-main/src/torch_ac/__init__.py | from torch_ac.algos import A2CAlgo, PPOAlgo
from torch_ac.model import ACModel, RecurrentACModel
from torch_ac.utils import DictList | 132 | 43.333333 | 52 | py |
T2TL | T2TL-main/src/torch_ac/algos/base.py | from abc import ABC, abstractmethod
import torch
from torch_ac.format import default_preprocess_obss
from torch_ac.utils import DictList, ParallelEnv
import numpy as np
from collections import deque
class BaseAlgo(ABC):
"""The base class for RL algorithms."""
def __init__(self, envs, acmodel, device, num_fr... | 17,512 | 49.469741 | 152 | py |
T2TL | T2TL-main/src/torch_ac/algos/a2c.py | import numpy
import torch
import torch.nn.functional as F
from torch_ac.algos.base import BaseAlgo
class A2CAlgo(BaseAlgo):
"""The Advantage Actor-Critic algorithm."""
def __init__(self, envs, acmodel, device=None, num_frames_per_proc=None, discount=0.99, lr=0.01, gae_lambda=0.95,
entropy_co... | 3,659 | 31.972973 | 117 | py |
T2TL | T2TL-main/src/torch_ac/algos/ppo.py | import numpy
import torch
import torch.nn.functional as F
from torch_ac.algos.base import BaseAlgo
class PPOAlgo(BaseAlgo):
"""The Proximal Policy Optimization algorithm
([Schulman et al., 2015](https://arxiv.org/abs/1707.06347))."""
def __init__(self, envs, acmodel, device=None, num_frames_per_proc=None... | 6,682 | 39.50303 | 125 | py |
T2TL | T2TL-main/src/torch_ac/algos/__init__.py | from torch_ac.algos.a2c import A2CAlgo
from torch_ac.algos.ppo import PPOAlgo | 77 | 38 | 38 | py |
T2TL | T2TL-main/src/torch_ac/utils/penv.py | from multiprocessing import Process, Pipe
import gym
def worker(conn, env):
'''
conn = <multiprocessing.connection.Connection object at 0x7f9aacbb5d68>
env = <LTLEnv<ZonesEnv5<Zones-5-v0>>>
'''
while True:
cmd, data = conn.recv()
if cmd == "step":
obs, reward, done, info... | 2,035 | 31.83871 | 93 | py |
T2TL | T2TL-main/src/torch_ac/utils/dictlist.py | class DictList(dict):
"""A dictionnary of lists of same size. Dictionnary items can be
accessed using `.` notation and list items using `[]` notation.
Example:
>>> d = DictList({"a": [[1, 2], [3, 4]], "b": [[5], [6]]})
>>> d.a
[[1, 2], [3, 4]]
>>> d[0]
DictList({"a":... | 737 | 29.75 | 79 | py |
T2TL | T2TL-main/src/torch_ac/utils/__init__.py | from torch_ac.utils.dictlist import DictList
from torch_ac.utils.penv import ParallelEnv | 88 | 43.5 | 44 | py |
T2TL | T2TL-main/src/envs/__init__.py | from gym.envs.registration import register
from envs.safety.zones_env import ZonesEnv
__all__ = ["ZonesEnv"]
### Safety Envs
register(
id='Zones-25-v1',
entry_point='envs.safety.zones_env:ZonesEnv25Fixed') | 218 | 17.25 | 56 | py |
T2TL | T2TL-main/src/envs/safety/safety_wrappers.py | import gym
import glfw
from mujoco_py import MjViewer, const
"""
A simple wrapper for SafetyGym envs. It uses the PlayViewer that listens to key_pressed events
and passes the id of the pressed key as part of the observation to the agent.
(used to control the agent via keyboard)
Should NOT be used for training!
"""
cl... | 3,260 | 30.970588 | 102 | py |
T2TL | T2TL-main/src/envs/safety/zones_env.py | import numpy as np
import enum
import gym
from safety_gym.envs.engine import Engine
class zone(enum.Enum):
JetBlack = 0
White = 1
Blue = 2
Green = 3
Red = 4
Yellow = 5
Cyan = 6
Magenta = 7
def __lt__(self, sth):
return self.value < sth.value
def ... | 10,968 | 39.032847 | 168 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/setup.py | #!/usr/bin/env python
from setuptools import setup
import sys
assert sys.version_info.major == 3 and sys.version_info.minor >= 6, \
"Safety Gym is designed to work with Python 3.6 and greater. " \
+ "Please install it before proceeding."
setup(
name='safety_gym',
packages=['safety_gym'],
install_... | 473 | 21.571429 | 69 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/random_agent.py | #!/usr/bin/env python
import argparse
import gym
import safety_gym # noqa
import numpy as np # noqa
def run_random(env_name):
env = gym.make(env_name)
obs = env.reset()
done = False
ep_ret = 0
ep_cost = 0
while True:
if done:
print('Episode Return: %.3f \t Episode Cost: %... | 906 | 24.914286 | 81 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/__init__.py | import safety_gym.envs | 22 | 22 | 22 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/envs/engine.py | #!/usr/bin/env python
import gym
import gym.spaces
import numpy as np
from PIL import Image
from copy import deepcopy
from collections import OrderedDict
import mujoco_py
from mujoco_py import MjViewer, MujocoException, const, MjRenderContextOffscreen
from safety_gym.envs.world import World, Robot
import sys
# Dis... | 72,634 | 46.880686 | 126 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/envs/mujoco.py | #!/usr/bin/env python
# This file is just to get around a baselines import hack.
# env_type is set based on the final part of the entry_point module name.
# In the regular gym mujoco envs this is 'mujoco'.
# We want baselines to treat these as mujoco envs, so we redirect from here,
# and ensure the registry entries a... | 399 | 39 | 76 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/envs/world.py | #!/usr/bin/env python
import os
import xmltodict
import numpy as np
from copy import deepcopy
from collections import OrderedDict
from mujoco_py import const, load_model_from_path, load_model_from_xml, MjSim, MjViewer, MjRenderContextOffscreen
import safety_gym
import sys
'''
Tools that allow the Safety Gym Engine t... | 18,394 | 43.21875 | 113 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/envs/__init__.py | import safety_gym.envs.suite | 28 | 28 | 28 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/envs/suite.py | #!/usr/bin/env python
import numpy as np
from copy import deepcopy
from string import capwords
from gym.envs.registration import register
import numpy as np
VERSION = 'v0'
ROBOT_NAMES = ('Point', 'Car', 'Doggo')
ROBOT_XMLS = {name: f'xmls/{name.lower()}.xml' for name in ROBOT_NAMES}
BASE_SENSORS = ['accelerometer', ... | 11,276 | 30.412256 | 100 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/test/test_bench.py | #!/usr/bin/env python
import re
import unittest
import numpy as np
import gym
import gym.spaces
from safety_gym.envs.engine import Engine
class TestBench(unittest.TestCase):
def test_goal(self):
''' Point should run into and get a goal '''
config = {
'robot_base': 'xmls/point.xml',
... | 6,951 | 37.622222 | 93 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/test/test_envs.py | #!/usr/bin/env python
import unittest
import gym
import safety_gym.envs # noqa
class TestEnvs(unittest.TestCase):
def check_env(self, env_name):
''' Run a single environment for a single episode '''
print('running', env_name)
env = gym.make(env_name)
env.reset()
done = Fa... | 660 | 22.607143 | 63 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/test/test_goal.py | #!/usr/bin/env python
import unittest
import numpy as np
from safety_gym.envs.engine import Engine, ResamplingError
class TestGoal(unittest.TestCase):
def rollout_env(self, env):
''' roll an environment until it is done '''
done = False
while not done:
_, _, done, _ = env.ste... | 1,480 | 28.62 | 80 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/test/test_determinism.py | #!/usr/bin/env python
import unittest
import numpy as np
import gym
import safety_gym # noqa
class TestDeterminism(unittest.TestCase):
def check_qpos(self, env_name):
''' Check that a single environment is seed-stable at init '''
for seed in [0, 1, 123456789]:
print('running', env_na... | 1,873 | 32.464286 | 94 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/test/test_button.py | #!/usr/bin/env python
import unittest
import numpy as np
from safety_gym.envs.engine import Engine, ResamplingError
class TestButton(unittest.TestCase):
def rollout_env(self, env, gets_goal=False):
'''
Roll an environment out to the end, return final info dict.
If gets_goal=True, then al... | 1,916 | 30.42623 | 76 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/test/test_obs.py | #!/usr/bin/env python
import unittest
import numpy as np
import joblib
import os
import os.path as osp
import gym
import safety_gym
from safety_gym.envs.engine import Engine
class TestObs(unittest.TestCase):
def test_rotate(self):
''' Point should observe compass/lidar differently for different rotations... | 2,366 | 36.571429 | 94 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/test/test_engine.py | #!/usr/bin/env python
import unittest
import numpy as np
import gym.spaces
from safety_gym.envs.engine import Engine
class TestEngine(unittest.TestCase):
def test_timeout(self):
''' Test that episode is over after num_steps '''
p = Engine({'num_steps': 10})
p.reset()
for _ in ran... | 2,257 | 33.738462 | 71 | py |
T2TL | T2TL-main/src/envs/safety/safety-gym/safety_gym/bench/bench_utils.py | import numpy as np
import json
SG6 = [
'cargoal1',
'doggogoal1',
'pointbutton1',
'pointgoal1',
'pointgoal2',
'pointpush1',
]
SG18 = [
'carbutton1',
'carbutton2',
'cargoal1',
'cargoal2',
'carpush1',
'carpush2',
'doggobutton1',
'doggobutton2',
... | 1,887 | 24.173333 | 81 | py |
T2TL | T2TL-main/src/utils/ast_builder.py | import ring
import numpy as np
import torch
import dgl
import networkx as nx
from sklearn.preprocessing import OneHotEncoder
edge_types = {k:v for (v, k) in enumerate(["self", "arg", "arg1", "arg2"])}
"""
A class that can take an LTL formula and generate the Abstract Syntax Tree (AST) of it. This
code can generate tr... | 5,910 | 37.383117 | 197 | py |
T2TL | T2TL-main/src/utils/storage.py | import csv
import os
import torch
import logging
import sys
import pickle
import utils
def create_folders_if_necessary(path):
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
os.makedirs(dirname)
def get_storage_dir():
if "RL_STORAGE" in os.environ:
return os.environ["RL_S... | 1,978 | 22.282353 | 105 | py |
T2TL | T2TL-main/src/utils/format.py | """
These functions preprocess the observations.
When trying more sophisticated encoding for LTL, we might have to modify this code.
"""
import os
import json
import re
import torch
import torch_ac
import gym
import numpy as np
import utils
from envs import *
from ltl_wrappers import LTLEnv
def get_obss_preprocessor... | 4,698 | 35.710938 | 161 | py |
T2TL | T2TL-main/src/utils/evaluator.py | import time
import torch
from torch_ac.utils.penv import ParallelEnv
#import tensorboardX
import utils
import argparse
import datetime
class Eval:
def __init__(self, env, model_name, ltl_sampler,
seed=0, device="cpu", argmax=False,
num_procs=1, ignoreLTL=False, progression_mode=Tru... | 6,373 | 42.067568 | 189 | py |
T2TL | T2TL-main/src/utils/agent.py | import torch
import utils
from model import ACModel
from recurrent_model import RecurrentACModel
class Agent:
"""An agent.
It is able:
- to choose an action given an observation,
- to analyze the feedback (i.e. reward and done state) of its action."""
def __init__(self, env, obs_space, action_sp... | 2,374 | 33.926471 | 104 | py |
T2TL | T2TL-main/src/utils/__init__.py | from .agent import *
from .env import *
from .format import *
from .other import *
from .storage import *
from .evaluator import *
from .ast_builder import *
| 158 | 18.875 | 26 | py |
T2TL | T2TL-main/src/utils/env.py | """
This class defines the environments that we are going to use.
Note that this is the place to include the right LTL-Wrapper for each environment.
"""
import gym
import ltl_wrappers
def make_env(env_key, progression_mode, ltl_sampler, seed=None, intrinsic=0, noLTL=False):
env = gym.make(env_key)
env.seed(s... | 506 | 25.684211 | 90 | py |
T2TL | T2TL-main/src/utils/other.py | import random
import numpy
import torch
import collections
def seed(seed):
random.seed(seed)
numpy.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def synthesize(array):
d = collections.OrderedDict()
d["mean"] = numpy.mean(arra... | 941 | 21.97561 | 75 | py |
T2TL | T2TL-main/src/gnns/graph_registry.py | gnn_registry = {}
def get_class( kls ):
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
for comp in parts[1:]:
m = getattr(m, comp)
return m
def register(id="", entry_point=None, **kwargs):
gnn_registry[id] = {
"class": get_class(entry_point),
... | 401 | 19.1 | 48 | py |
T2TL | T2TL-main/src/gnns/__init__.py | from gnns.graph_registry import *
from gnns.graphs.GNN import *
register(id="GCN_2x32_MEAN", entry_point="gnns.graphs.GCN.GCN", hidden_dims=[32, 32])
register(id="GCN_4x32_MEAN", entry_point="gnns.graphs.GCN.GCN", hidden_dims=[32, 32, 32, 32])
register(id="GCN_32_MEAN", entry_point="gnns.graphs.GCN.GCN", hidden_dims... | 1,544 | 45.818182 | 114 | py |
T2TL | T2TL-main/src/gnns/graphs/GCN.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.nn.pytorch.conv import GraphConv
from gnns.graphs.GNN import GNN
class GCN(GNN):
def __init__(self, input_dim, output_dim, **kwargs):
super().__init__(input_dim, output_dim)
hidden_dims = kw... | 2,927 | 31.898876 | 103 | py |
T2TL | T2TL-main/src/gnns/graphs/RGCN.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.nn.pytorch.conv import RelGraphConv
from gnns.graphs.GNN import GNN
from utils.ast_builder import edge_types
class RGCN(GNN):
def __init__(self, input_dim, output_dim, **kwargs):
super().__init__(in... | 3,153 | 32.913978 | 103 | py |
T2TL | T2TL-main/src/gnns/graphs/GNN.py | import torch
import torch.nn as nn
from gnns import *
class GNN(nn.Module):
def __init__(self, input_dim, output_dim):
super().__init__()
def forward(self, g):
raise NotImplementedError
def GNNMaker(gnn_type, input_dim, output_dim): # 'RGCN_8x32_ROOT_SHARED'; 22; 33
clazz = lookup(gnn_t... | 393 | 23.625 | 81 | py |
toulbar2 | toulbar2-master/setup.py | import os
import re
import sys
import platform
import subprocess
from setuptools import setup
from setuptools.extension import Extension
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from distutils.version import LooseVersion
python_Path = sys.executable
python_Root = sys.... | 3,772 | 36.356436 | 138 | py |
toulbar2 | toulbar2-master/pytoulbar2/__init__.py | from .pytoulbar2 import *
| 26 | 12.5 | 25 | py |
toulbar2 | toulbar2-master/pytoulbar2/pytoulbar2.py | """Help on module pytoulbar2:
NAME
pytoulbar2 - Python3 interface of toulbar2.
DESCRIPTION
"""
from math import isinf
try :
import pytoulbar2.pytb2 as tb2
except :
pass
class CFN:
"""pytoulbar2 base class used to manipulate and solve a cost function network.
Constructor Args:
ubini... | 49,929 | 48.484638 | 372 | py |
toulbar2 | toulbar2-master/pytoulbar2/tests/test_pytoulbar2.py | from unittest import TestCase
import pytoulbar2
class TestExtension(TestCase):
def test_1(self):
myCFN = pytoulbar2.CFN(2)
res = myCFN.Solve()
self.assertEqual(res[0],[])
self.assertEqual(res[1],0.0)
self.assertEqual(res[2],1)
| 263 | 21 | 34 | py |
toulbar2 | toulbar2-master/pytoulbar2/tests/__init__.py | 0 | 0 | 0 | py | |
toulbar2 | toulbar2-master/src/pytoulbar2testinc.py | """
Test incremental-solving pytoulbar2 API.
Generates a random binary cost function network and solves a randomly-selected modified subproblem (without taking into account the rest of the problem).
"""
import sys
import random
random.seed()
import pytoulbar2
# total maximum CPU time
T=3
# number of variables
N=10... | 2,870 | 34.8875 | 170 | py |
toulbar2 | toulbar2-master/src/pytoulbar2test.py | """
Test basic pytoulbar2 API.
"""
import sys
import random
random.seed()
import pytoulbar2
# create a new empty cost function network with 2-digit precision and initial upper bound of 100
Problem = pytoulbar2.CFN(100., resolution=2)
# add three Boolean variables and a 4-value variable
x = Problem.AddVariable('x',... | 3,717 | 52.884058 | 201 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/bicriteria_latinsquare.py | import sys
from random import seed, randint
seed(123456789)
import pytoulbar2
from matplotlib import pyplot as plt
N = int(sys.argv[1])
top = N**3 +1
# printing a solution as a grid
def print_solution(sol, N):
grid = [0 for _ in range(N*N)]
for k,v in sol.items():
grid[ int(k[5])*N+int(k[7]) ] = int(v[1:]... | 4,079 | 28.142857 | 115 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/rcpsp.py |
# Resource-Constrained Project Scheduling Problem
# Example taken from PyCSP3 COP model RCPSP
# http://pycsp.org/documentation/models/COP/RCPSP
import sys
import pytoulbar2
horizon = 158
capacities = [12, 13, 4, 12]
job_durations = [0, 8, 4, 6, 3, 8, 5, 9, 2, 7, 9, 2, 6, 3, 9, 10, 6, 5, 3, 7, 2, 7, 2, 3, 3, 7, 8, 3... | 2,370 | 38.516667 | 150 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/blockmodel2.py |
import sys
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, str) and not isinstance(el, tuple) and not isinstance(el, dict):
result.extend(flatten(el))
else:
result.append(el)
return result
def cfn(problem, isMinimization, ... | 6,646 | 47.518248 | 299 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/blockmodel.py | import sys
import pytoulbar2
#read adjency matrix of graph G
Lines = open(sys.argv[1], 'r').readlines()
GMatrix = [[int(e) for e in l.split(' ')] for l in Lines]
N = len(Lines)
Top = N*N + 1
K = int(sys.argv[2])
#give names to node variables
Var = [(chr(65 + i) if N < 28 else "x" + str(i)) for i in range(N)] # Poli... | 3,036 | 34.729412 | 250 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/mendel.py | import sys
import pytoulbar2
class Data:
def __init__(self, ped):
self.id = list()
self.father = {}
self.mother = {}
self.allelesId = {}
self.ListAlle = list()
self.obs = 0
stream = open(ped)
for line in stream:
(locus, id, father, mother, sex, allele1, allele2) = line.split()[:]
self.id.append... | 2,569 | 30.341463 | 122 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/airland.py | import sys
import pytoulbar2
f = open(sys.argv[1], 'r').readlines()
tokens = []
for l in f:
tokens += l.split()
pos = 0
def token():
global pos, tokens
if (pos == len(tokens)):
return None
s = tokens[pos]
pos += 1
return int(float(s))
N = token()
token() # skip freeze time
LT = []
... | 1,599 | 22.188406 | 84 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/rlfap.py | import sys
import pytoulbar2
class Data:
def __init__(self, var, dom, ctr, cst):
self.var = list()
self.dom = {}
self.ctr = list()
self.cost = {}
self.nba = {}
self.nbb = {}
self.top = 1
self.Domain = {}
stream = open(var)
for line in stream:
if len(line.split())>=4:
(varnum, vardom, value... | 2,662 | 28.921348 | 96 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/weightedqueens.py | import sys
from random import seed, randint
seed(123456789)
import pytoulbar2
N = int(sys.argv[1])
top = N**2 +1
Problem = pytoulbar2.CFN(top)
for i in range(N):
Problem.AddVariable('Q' + str(i+1), ['row' + str(a+1) for a in range(N)])
for i in range(N):
for j in range(i+1,N):
#Two queens cannot ... | 1,594 | 23.166667 | 77 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/warehouse.py | import sys
import pytoulbar2
f = open(sys.argv[1], 'r').readlines()
precision = int(sys.argv[2]) # in [0,9], used to convert cost values from float to integer (by 10**precision)
tokens = []
for l in f:
tokens += l.split()
pos = 0
def token():
global pos, tokens
if pos == len(tokens):
return No... | 1,844 | 23.6 | 110 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/golomb.py | import sys
import pytoulbar2
N = int(sys.argv[1])
top = N**2 + 1
Problem = pytoulbar2.CFN(top)
#create a variable for each mark
for i in range(N):
Problem.AddVariable('X' + str(i), range(N**2))
#ternary constraints to link new variables of difference with the original variables
for i in range(N):
for j in ... | 1,285 | 27.577778 | 99 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/square.py | import sys
from random import randint, seed
seed(123456789)
import pytoulbar2
try:
N = int(sys.argv[1])
S = int(sys.argv[2])
assert N <= S
except:
print('Two integers need to be given as arguments: N and S')
exit()
#pure constraint satisfaction problem
Problem = pytoulbar2.CFN(1)
#create a variable for each s... | 2,078 | 26 | 117 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/boardcoloration.py | import sys
from random import randint, seed
seed(123456789)
import pytoulbar2
try:
n = int(sys.argv[1])
m = int(sys.argv[2])
except:
print('Two integer need to be in arguments: number of rows n, number of columns m')
exit()
top = n*m + 1
Problem = pytoulbar2.CFN(top)
#create a variable for each cell... | 2,496 | 33.680556 | 205 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/fapp.py | import sys
import pytoulbar2
class Data:
def __init__(self, filename, k):
self.var = {}
self.dom = {}
self.ctr = list()
self.softeq = list()
self.softne = list()
self.nbsoft = 0
stream = open(filename)
for line in stream:
if len(line.split())==3 and line.split()[0]=="DM":
(DM, dom, freq) = lin... | 4,169 | 30.590909 | 115 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/magicsquare.py | import sys
import pytoulbar2
N = int(sys.argv[1])
magic = N * (N * N + 1) // 2
top = 1
Problem = pytoulbar2.CFN(top)
for i in range(N):
for j in range(N):
#Create a variable for each square
Problem.AddVariable('Cell(' + str(i) + ',' + str(j) + ')', range(1,N*N+1))
Problem.AddAllDifferent(['Cell(' + str(i) + ... | 1,373 | 33.35 | 125 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/squaresoft.py | import sys
from random import randint, seed
seed(123456789)
import pytoulbar2
try:
N = int(sys.argv[1])
S = int(sys.argv[2])
assert N <= S
except:
print('Two integers need to be given as arguments: N and S')
exit()
Problem = pytoulbar2.CFN(N**4 + 1)
#create a variable for each square
for i in range(N):
Probl... | 2,244 | 28.155844 | 117 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/latinsquare.py | import sys
from random import seed, randint
seed(123456789)
import pytoulbar2
N = int(sys.argv[1])
top = N**3 +1
Problem = pytoulbar2.CFN(top)
for i in range(N):
for j in range(N):
#Create a variable for each square
Problem.AddVariable('Cell(' + str(i) + ',' + str(j) + ')', range(N))
for i in r... | 1,257 | 28.952381 | 111 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/sudoku/MNIST_train.py | from __future__ import print_function
import argparse
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import... | 6,939 | 40.065089 | 97 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/sudoku/sudoku.py | import pytoulbar2
import numpy as np
import itertools
import pandas as pd
# Adds a clique of differences with violation "cost" on "varList"
def addCliqueAllDiff(theCFN, varList, cost):
different = (cost*np.identity(size, dtype=np.int64)).flatten()
for vp in itertools.combinations(varList,2):
theCFN.Add... | 1,783 | 28.733333 | 88 | py |
toulbar2 | toulbar2-master/web/TUTORIALS/sudoku/MNIST_sudoku.py | import pytoulbar2
import math, numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pickle
import torch
from torchvision import datasets, transforms
import itertools
import pandas as pd
import hashlib
##########################################################################
# Image output rout... | 5,697 | 33.325301 | 98 | py |
toulbar2 | toulbar2-master/docker/toulbar2/using/problem.py |
from pytoulbar2 import CFN
import numpy
myCFN = CFN(1)
myCFN.Solve()
print("problem end OK")
| 98 | 8 | 26 | py |
toulbar2 | toulbar2-master/docker/pytoulbar2/using/problem.py |
from pytoulbar2 import CFN
import numpy
myCFN = CFN(1)
myCFN.Solve()
print("problem end OK")
| 98 | 8 | 26 | py |
toulbar2 | toulbar2-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 7,750 | 28.471483 | 79 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.