index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
56,804 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/wrapper/utils.py |
from easydict import EasyDict as edict
def get_user_data(env):
env = env.unwrapped
ud = getattr(env, '__userdata__', None)
if ud is None:
ud = edict()
env.__userdata__ = ud
env.__class__.userdata = property(lambda self: self.__userdata__)
return ud | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,805 | tornadoyi/rl-lab | refs/heads/master | /rllab/rl/profiling/__init__.py |
from .profiling import Profiling, indicator | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,806 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/nn/functional/__init__.py |
from torch.nn.functional import *
from .loss import * | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,807 | tornadoyi/rl-lab | refs/heads/master | /rllab/rl/features/mlp.py | from collections import OrderedDict
import numpy as np
from torch import nn
from .features import register
@register("mlp")
class mlp(nn.Sequential):
def __init__(self, input_shape, num_layers=2, num_hidden=64, activation=None, layer_norm=False):
"""
Stack of fully-connected layers to be used in a policy / q-function approximator
Parameters:
----------
input_shape: tuple should be a shape with format (batch, feature length)
num_layers: int number of fully-connected layers (default: 2)
num_hidden: int size of fully-connected layers (default: 64)
activation: activation function (default: tf.tanh)
Returns:
-------
Sequential build by fully connected network
"""
self.output_shape = (input_shape[0], num_hidden)
# calculate in features
in_features = 1
for d in input_shape[1:]: in_features *= d
l = [nn.Flatten()]
for i in range(num_layers):
# fc
x = nn.Linear(in_features, num_hidden)
nn.init.orthogonal_(x.weight.data, gain=np.sqrt(2))
nn.init.constant_(x.bias.data, 0.0)
l.append(x)
in_features = num_hidden
# normalize
if layer_norm: l.append(nn.LayerNorm([in_features]))
# activation
l.append(nn.Tanh() if activation is None else activation)
layers = [('{}_{}'.format(l[i].__class__.__name__.lower(), i), l[i]) for i in range(len(l))]
super(mlp, self).__init__(OrderedDict(layers))
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,808 | tornadoyi/rl-lab | refs/heads/master | /test/game.py |
import gym
from rllab import envs
import pygame
env = gym.make('ShuttleRun-100m-hard-v0')
#env = gym.make('Race-100m-hard-v0')
env.reset()
while True:
env.render()
keys = pygame.key.get_pressed()
action = -1
if keys[pygame.K_SPACE]: action = 0
elif keys[pygame.K_LEFT]: action = 1
elif keys[pygame.K_RIGHT]: action = 2
if action > 0:
_, _, t, _ = env.step(action)
if t: break
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,809 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/distributed/optimizer.py | from torch import distributed as dist
class Optimizer(object):
def __init__(self, optimizer, params=None):
self._optimizer = optimizer
self._params = params or [p for grp in self._optimizer.param_groups for p in grp['params']]
def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError("attempted to get missing private attribute '{}'".format(name))
return getattr(self._optimizer, name)
def step(self, closure=None):
self._optimizer.step(closure)
class GradientReducer(Optimizer):
def __init__(self, optimizer, params=None, reduce='mean'):
super(GradientReducer, self).__init__(optimizer, params)
self._reduce = reduce
assert reduce in ['mean', 'sum']
def step(self, closure=None):
if self._reduce == 'mean': self._reudce_mean()
elif self._reduce == 'sum': self._reudce_sum()
super(GradientReducer, self).step(closure)
def _reudce_sum(self):
handlers = [dist.all_reduce(p.grad.data, dist.ReduceOp.SUM, async_op=True) for p in self._params]
for h in handlers: h.wait()
def _reudce_mean(self):
size = float(dist.get_world_size())
self._reudce_sum()
for p in self._params:
p.grad.data = p.grad.data / size
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,810 | tornadoyi/rl-lab | refs/heads/master | /rllab/rl/features/__init__.py |
from .features import *
from . import mlp, cnn
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,811 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/nn/modules/__init__.py |
from .tensor import *
from .conv import * | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,812 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/__init__.py |
import gym
# import envs
from . import race as _
_make = gym.make
def make(id, **kwargs):
from .wrapper import Profiling, RewardRatio, atari
env = _make(id)
# check env type
k = kind(env)
if k == 'atari': env = atari.wrap(env, **kwargs)
# add profiling wrapper
env = Profiling(env)
return env
gym.make = make
def kind(env):
packs = env.unwrapped.__class__.__module__.split('.')
if '.'.join(packs[:3]) == 'gym.envs.atari': return 'atari'
elif '.'.join(packs[:3]) == 'gym.envs.classic_control': return 'classic_control'
return 'other' | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,813 | tornadoyi/rl-lab | refs/heads/master | /rllab/algorithms/deepq/__init__.py |
from .trainer import train
def execute(args):
if args.command == 'train':
train(**args.arguments)()
else:
pass
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,814 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/__init__.py |
# expose public objects from torch
from torch import *
from .core import *
from . import cuda
from . import distributed
from . import nn
from . import optim
from . import profiling
from . import utils
# export others from torch
import torch as _torch
utils.exposer.expose(_torch, globals(), filter=lambda k: k.startswith('_')) | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,815 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/utils/__init__.py |
from . import exposer
from . import shell | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,816 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/distributed/__init__.py |
from torch.distributed import *
from .launcher import *
from .optimizer import * | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,817 | tornadoyi/rl-lab | refs/heads/master | /rllab/algorithms/deepq/deepq.py | from rllab import torchlab as tl
from rllab.torchlab import nn
from rllab.torchlab.nn import functional as F
from rllab.rl.profiling import indicator
from .network import QFunc
class DeepQ(nn.Module):
def __init__(
self,
ob_space,
ac_space,
feature_creator,
double_q=False,
grad_norm_clipping=None,
gamma=1.0,
qfunc={},
**_,
):
super(DeepQ, self).__init__()
# config
self.ob_space = ob_space
self.ac_space = ac_space
self.double_q = double_q
self.gamma = gamma
self.grad_norm_clipping = grad_norm_clipping
# q function
self.net_q_eval = QFunc(ac_space, feature_creator, **qfunc)
self.net_q_target = QFunc(ac_space, feature_creator, **qfunc)
@property
def trained_parameters(self): return self.net_q_eval.parameters()
def act(self, ob, eps):
obs = ob.reshape(*[(-1, ) + self.ob_space.shape])
# todo noise action
deterministic_actions = tl.argmax(self.net_q_eval(obs), 1)
random_actions = deterministic_actions.float().uniform_(0.0, float(self.ac_space.n)).long()
conditions = deterministic_actions.float().uniform_(0, 1) < eps
final_actions = tl.where(conditions, random_actions, deterministic_actions)
return final_actions.squeeze()
def learn(self, optimizer, obs, acs, rews, obs_n, dones, weights=None):
# calculate q evaluation
q_eval = self.net_q_eval(obs)
# calculate q target and stop gradients
q_target = self.net_q_target(obs_n).detach()
# q scores for actions which we know were selected in the given state.
q_eval_selected = tl.sum(q_eval * F.one_hot(acs, self.ac_space.n), 1)
# double q
if self.double_q:
q_eval_n = self.net_q_eval(obs_n)
max_q_ac_n = tl.argmax(q_eval_n, 1)
q_best = tl.sum(q_target * F.one_hot(max_q_ac_n, self.ac_space.n), 1)
else:
q_best = q_target.max(1)[0]
# mask terminal
q_best = (1.0 - dones) * q_best
# compute RHS of bellman equation
q_target_selected = rews + self.gamma * q_best
# compute the error (potentially clipped)
td_error = q_eval_selected - q_target_selected
# loss
errors = F.huber_loss(td_error)
errors = tl.mean(weights * errors)
# compute gradients (potentially with gradient clipping)
optimizer.zero_grad()
errors.backward()
if self.grad_norm_clipping is not None:
for p in self.net_q_eval.parameters(): nn.utils.clip_grad_norm(p, self.grad_norm_clipping)
optimizer.step()
# profiling
indicators = {
'deepq/loss': (errors, lambda: indicator('scalar').cond('update')),
'deepq/td_error': (tl.mean(td_error), lambda: indicator('scalar').cond('update')),
'deepq/q_eval_selected': (tl.mean(q_eval_selected), lambda: indicator('scalar').cond('update')),
'deepq/q_target_selected': (tl.mean(q_target_selected), lambda: indicator('scalar').cond('update')),
}
# gradients profiling
for k, v in self.net_q_eval.state_dict().items():
indicators['gradients/{}'.format(k)] = (v.abs().mean(), lambda: indicator('scalar').cond('update'))
return indicators
def update_target_network(self):
self.net_q_target.load_state_dict(self.net_q_eval.state_dict())
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,818 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/wrapper/__init__.py |
from .profiling import Profiling
from .reward_ratio import RewardRatio | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,819 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/race/race.py |
from .runway import RunwayEnv
class RaceEnv(RunwayEnv):
def __init__(self, score_mode='normal', **kwargs):
# config
self._score_mode = score_mode
super(RaceEnv, self).__init__(**kwargs)
def step(self, action):
ob, r, d, info = super(RaceEnv, self).step(action)
# reward
if self._score_mode == 'sparse':
r = 0.0 if self._pos < self._length - 1 else 1.0
elif self._score_mode == 'guide':
if action == 0: r = 0.0
elif action == 1: r = -1.0
else: r = 1.0
else:
r = -1.0 if self._pos < self._length - 1 else 1.0
# terminate
if self._pos >= self._length - 1: d = True
return ob, r, d, info
import numpy as np
from gym.envs.registration import register
register(
id='Race-100m-easy-v0',
entry_point='rllab.envs.race:RaceEnv',
kwargs={'length': 100, 'move_success_rate': 1.0, 'score_mode': 'guide'},
max_episode_steps=np.inf,
reward_threshold=1.0,
)
register(
id='Race-100m-medium-v0',
entry_point='rllab.envs.race:RaceEnv',
kwargs={'length': 100, 'move_success_rate': 0.9, 'score_mode': 'normal'},
max_episode_steps=int(3 * 100 / 0.9),
reward_threshold=1.0,
)
register(
id='Race-100m-hard-v0',
entry_point='rllab.envs.race:RaceEnv',
kwargs={'length': 100, 'move_success_rate': 0.8, 'score_mode': 'sparse'},
max_episode_steps=int(2 * 100 / 0.8),
reward_threshold=1.0,
) | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,820 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/wrapper/reward_ratio.py |
import gym
class RewardRatio(gym.Wrapper):
def step(self, action):
ob, r, d, info = super(RewardRatio, self).step(action)
r = r * self.spec.reward_threshold
return ob, r, d, info
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,821 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/profiling/profiling.py | import os
from collections import OrderedDict
from torch.utils.tensorboard import SummaryWriter
from . import indicator
class Profiling(object):
def __init__(
self,
log_dir,
step_func,
):
self._log_dir = log_dir
self._writer = SummaryWriter(self.log_dir)
self._indicators = OrderedDict()
self._step_func = step_func
# create log path
os.makedirs(self._log_dir, exist_ok=True)
@property
def log_dir(self): return self._log_dir
@property
def steps(self): return self._step_func()
@property
def writer(self): return self._writer
def __contains__(self, tag): return tag in self._indicators
def add(self, tag, *args, **kwargs):
if tag in self._indicators: raise Exception('repeated indicator {}'.format(tag))
self._indicators[tag] = indicator(tag, *args, **kwargs).profiling(self)
def remove(self, tag):
if tag not in self._indicators: return
del self._indicators[tag]
def update(self, tag, value, signals=(), creator=None):
id = self._indicators.get(tag, None)
if id is None:
if creator is None: raise Exception('can not find indicator {}'.format(tag))
id = self._indicators[tag] = creator().name(tag).profiling(self)
id.update(value, signals)
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,822 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/profiling/__init__.py |
from .profiling import Profiling
from .indicator import create as indicator | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,823 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/optim/__init__.py |
from torch.optim import *
from .optim import * | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,824 | tornadoyi/rl-lab | refs/heads/master | /rllab/algorithms/deepq/experiments/cartpole.py | import sys
import os
from rllab import cli
from rllab import define
if __name__ == '__main__':
cmd, extras = sys.argv[1], sys.argv[2:]
if cmd == 'train':
argv = [
'env.id="CartPole-v0"',
'total_steps=int(1e5)',
'optimizer.lr=1e-3',
'rb.size=50000',
'explore.fraction=0.1', 'explore.final=0.02',
]
elif cmd == 'play':
argv = [
]
else: raise Exception('Invalid command {}'.format(cmd))
sys.argv = [sys.argv[0], define.module(os.path.realpath(__file__)), cmd] + argv + extras
cli.main() | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,825 | tornadoyi/rl-lab | refs/heads/master | /setup.py | from os.path import dirname, join
from setuptools import setup, find_packages
# Project name
NAME = 'rl-lab'
# Define version information
with open(join(dirname(__file__), 'rllab/VERSION'), 'rb') as f:
VERSION = f.read().decode('ascii').strip()
setup(name=NAME,
version=VERSION,
description="Laboratory of reinforcement learning includes games and algorithms.",
author='yi gu',
author_email='390512308@qq.com',
license='License :: OSI Approved :: Apache Software License',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
python_requires='>=3.6',
install_requires = [
'argparse',
'easydict',
'gym',
'opencv-python',
'pyhumps',
],
entry_points={
'console_scripts': [
'rl-lab = rllab.cli:main',
],
},
) | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,826 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/profiling/condition.py |
__CONDITIONS = {}
def register(name):
global __CONDITIONS
def _thunk(func):
__CONDITIONS[name] = func
return func
return _thunk
def create(type, *args, **kwargs):
if type not in __CONDITIONS: raise Exception('Unknown condition {}'.format(type))
return __CONDITIONS[type](*args, **kwargs)
class Condition(object):
def __init__(self):
self.indicator = None
def __call__(self, *args, **kwargs): raise NotImplementedError('__call__ is not implemented')
@register('none')
class Unconditional(Condition):
def __call__(self, *args, **kwargs): return False
@register('update')
class Updates(Condition):
def __init__(self, updates=1):
super(Updates, self).__init__()
self.updates = updates
def __call__(self, *args, **kwargs): return self.indicator.updates % self.updates == 0
@register('signal')
class Signal(Condition):
def __init__(self, *signals):
super(Signal, self).__init__()
self.signals = set(signals)
def __call__(self, signals, **kwargs):
for s in signals:
if s in self.signals: return True
return False
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,827 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/distributed/launcher.py | import os
from torch.multiprocessing import Process
import torch.distributed as dist
def _on_process_launch(
rank, world_size, backend, init_method, timeout, store, group_name,
target, args, kwargs
):
# init process group
grp_args = {
'rank': rank,
'backend': backend,
'world_size': world_size,
'init_method': init_method,
'store': store,
}
if timeout is not None: grp_args['timeout'] = timeout
if group_name is not None: grp_args['group_name'] = group_name
dist.init_process_group(**grp_args)
# call target
target(*args, **kwargs)
def launch(
world_size=-1,
rank_start=0,
rank_end=None,
backend='gloo',
method=None,
timeout=None,
store=None,
group_name=None,
target=None,
args=(),
kwargs={},
):
# check
if not dist.is_available(): raise Exception('Distributed is not available')
if method == None or method == 'env://':
address, port = os.environ.get('MASTER_ADDR', None), os.environ.get('MASTER_PORT', None)
if address is None: raise Exception('MASTER_ADDR should be set in environment')
if port is None: raise Exception('MASTER_PORT should be set in environment')
if world_size < 0: world_size = os.environ.get('WORLD_SIZE', -1)
if world_size < 0: raise Exception('Invalid world size {}'.format(world_size))
rank_end = rank_end or world_size
if rank_start >= rank_end: raise Exception('invalid rank range {}'.format((rank_start, rank_end)))
if target is None: raise Exception('invalid target {}'.format(target))
if backend == 'gloo':
if not dist.is_gloo_available(): raise Exception('backend gloo is not available')
elif backend == 'nccl':
if not dist.is_nccl_available(): raise Exception('backend nccl is not available')
elif backend == 'mpi':
if not dist.is_mpi_available(): raise Exception('backend mpi is not available')
else:
raise Exception('invalid backend {}'.format(backend))
# launch process
processes = []
for rank in range(rank_start, rank_end, 1):
p = Process(
target=_on_process_launch,
args=(
rank, world_size, backend, method, timeout, store, group_name,
target, args, kwargs,
)
)
p.start()
processes.append(p)
# join
for p in processes:
p.join() | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,828 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/race/__init__.py |
from .race import RaceEnv
from .shuttle_run import ShuttleRunEnv | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,829 | tornadoyi/rl-lab | refs/heads/master | /rllab/algorithms/deepq/experiments/breakout.py | import sys
import os
from rllab import cli
from rllab import define
if __name__ == '__main__':
cmd, extras = sys.argv[1], sys.argv[2:]
if cmd == 'train':
argv = [
'env.id="BreakoutNoFrameskip-v0"', 'env.frame_stack=True',
'deepq.gamma=0.99',
'total_steps=int(1e7)',
'learning_starts=10000',
'optimizer={"name":"Adam","lr":1e-4}',
'rb.size=50000',
'explore.fraction=0.1', 'explore.final=0.01',
]
elif cmd == 'play':
argv = [
]
else: raise Exception('Invalid command {}'.format(cmd))
sys.argv = [sys.argv[0], define.module(os.path.realpath(__file__)), cmd] + argv + extras
cli.main() | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,830 | tornadoyi/rl-lab | refs/heads/master | /rllab/rl/profiling/profiling.py |
from rllab.torchlab import profiling
from rllab.torchlab.profiling import indicator
from rllab import define
class Profiling(profiling.Profiling):
def __init__(self, env, **kwargs):
super(Profiling, self).__init__(define.profiling_path(), **kwargs)
self.env = env
def __call__(self, *args, **kwargs):
ud = self.env.userdata
if ud.reward is not None:
self.update('env/mean_reward_100s', ud.reward, creator=lambda: indicator('scalar').cond('update', 100))
if ud.done == True:
self.update('env/round_steps', ud.steps, creator=lambda: indicator('scalar').cond('signal', 'done'))
self.update('env/round_reward',ud.total_reward, creator=lambda: indicator('scalar').cond('signal', 'done'))
def update(self, tag, value, signals=(), creator=None):
signals = set(signals)
if self.env.userdata.done: signals.add('done')
super(Profiling, self).update(tag, value, signals, creator)
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,831 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/cuda/cuda.py | import os
import sys
from easydict import EasyDict as edict
from rllab.torchlab.utils import shell
def nvsmi_query(*fileds, tree_format=False):
# get primitive information
cmd = 'nvidia-smi --format=csv,noheader,nounits --query-gpu={}'.format(','.join(fileds))
lines = shell.run(cmd).split('\n')[:-1]
# parse infos
status = []
for i in range(len(lines)):
s = edict()
texts = lines[i].split(',')
assert len(texts) == len(fileds), "len(texts):{} != len(fileds):{}".format(len(texts), len(fileds))
for j in range(len(fileds)):
f = fileds[j]
t = texts[j].strip(' ')
if tree_format:
d = s
keys = f.split('.')
for k in range(len(keys)):
key = keys[k]
if k == len(keys)-1: d[key] = t
else:
if key in d: d = d[key]
else:
d[key] = edict()
d = d[key]
else:
s[f] = t
status.append(s)
# mapping
if 'CUDA_VISIBLE_DEVICES' in os.environ:
vis_status = [status[int(id)] for id in os.environ['CUDA_VISIBLE_DEVICES'].split(',')]
status = vis_status
return status
def nvsmi_sort(filed, reverse=True):
values = [int(s[filed]) for s in nvsmi_query(filed)]
ids = list(range(len(values)))
return sorted(ids, key=lambda id: int(values[id]), reverse=reverse)
_CUDA_AVAILABLE = None
def detect_available():
"""
torch.cuda.is_available() is going to initialize all cuda device. To the disadvantage of multiprocessing,
cause an runtime error "Cannot re-initialize CUDA in forked subprocess" would be raised.
:return: bool cuda available
"""
global _CUDA_AVAILABLE
if _CUDA_AVAILABLE is not None: return _CUDA_AVAILABLE
_CUDA_AVAILABLE = shell.run('{} -c "import torch;print(torch.cuda.is_available())"'.format(sys.executable)).strip('\n') == 'True'
return _CUDA_AVAILABLE | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,832 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/race/render.py |
from rllab.envs import render
class Render(render.Render):
def __init__(self, *args, **kwargs):
super(Render, self).__init__(*args, **kwargs)
def on_render(self):
w, h = self.screen.get_width(), self.screen.get_height()
# clear screen
self.screen.fill(render.Color('white'))
# draw way
way_rect = render.Rect(0.1 * w, 0.6 * h, 0.8 * w, 0.1 * h)
render.draw.lines(self.screen, render.Color('black'), False, [
way_rect.topleft,
way_rect.bottomleft,
way_rect.bottomright,
way_rect.topright
], 5)
# draw player
ratio = (self._env._pos + 1) / self._env._length
player_x = way_rect.topleft[0] + way_rect.width * ratio
render.draw.line(self.screen, render.Color('red'), (player_x, way_rect.topleft[1]), (player_x, way_rect.bottomleft[1]), 5)
# episodes
infos = []
ud = self._env.userdata
if 'steps' in ud:
if self._env.spec.max_episode_steps is not None:
infos.append('episodes: {}/{}'.format(ud.steps, self._env.spec.max_episode_steps))
else:
infos.append('episodes: {}'.format(ud.steps))
# reward
if 'total_reward' in ud:
infos.append('rewards: {}'.format(ud.total_reward))
# location
infos.append('location: {}/{}'.format(self._env._pos + 1, self._env._length))
# extra
infos += self._env.render_infos()
# draw informations
render.font.blit_text(self.screen, '\n'.join(infos), (0, 0), render.font.Font(render.font.get_default_font(), 20), )
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,833 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/cuda/__init__.py |
from torch.cuda import *
from .cuda import * | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,834 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/wrapper/profiling.py | import gym
from .utils import get_user_data
class Profiling(gym.Wrapper):
def __init__(self, *args, **kwargs):
super(Profiling, self).__init__(*args, **kwargs)
self.ud = get_user_data(self)
self.ud.num_resets = 0
def reset(self):
ob = super(Profiling, self).reset()
self.ud.num_resets += 1
self.ud.steps = 0
self.ud.observation = ob
self.ud.action = None
self.ud.reward = None
self.ud.total_reward = 0
self.ud.info = None
self.ud.done = False
return ob
def step(self, action):
ob, r, d, info = super(Profiling, self).step(action)
self.ud.steps += 1
self.ud.action = action
self.ud.reward = r
self.ud.observation = ob
self.ud.info = info
self.ud.total_reward += r
self.ud.done = d
return ob, r, d, info
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,835 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/nn/modules/tensor.py | from inspect import ismethoddescriptor
import torch
from torch import nn
import humps
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
nn.Module.__init__(self)
def _create_module_class(name, func):
return type(
name,
(nn.Module, ),
{
"__init__": __init__,
"forward": lambda self, x: func(x, *self.args, **self.kwargs)
}
)
for name in dir(torch.Tensor):
if name.startswith('_') or name.endswith('_'): continue
f = getattr(torch.Tensor, name)
if not ismethoddescriptor(f): continue
name = humps.pascalize(name)
if hasattr(nn, name): continue
globals()[name] = _create_module_class(name, f)
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,836 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/profiling/indicator.py | import numpy as np
import torch
from . import condition
__INDICATORS = {}
def register(name):
global __INDICATORS
def _thunk(func):
__INDICATORS[name] = func
return func
return _thunk
def create(type, name=None):
if type not in __INDICATORS: raise Exception('Unknown indicator type {}'.format(type))
return __INDICATORS[type]().name(name)
class Indicator(object):
def __init__(self):
self._name = None
self._profiling = None
self._conditions = []
self._updates = 0
self._reset()
@property
def updates(self): return self._updates
def __call__(self): pass
def name(self, name):
self._name = name
return self
def profiling(self, profiling):
self._profiling = profiling
return self
def cond(self, t, *args, **kwargs):
c = condition.create(t, *args, **kwargs)
c.indicator = self
self._conditions.append(c)
return self
def update(self, v, signals=(), **kwargs):
self._updates += 1
self._update(v, signals=signals, **kwargs)
for c in self._conditions:
if not c(signals): continue
self.save()
break
def save(self):
self._save()
self._reset()
def _write(self, fname, *args, **kwargs): getattr(self._profiling.writer, fname)(self._name, *args, global_step=self._profiling.steps, **kwargs)
def _update(self, *args, **kwargs): raise NotImplementedError('_update is not implemented')
def _save(self): raise NotImplementedError('_save is not implemented')
def _reset(self): raise NotImplementedError('_reset is not implemented')
@register('scalar')
class Scalar(Indicator):
def __init__(self):
self._vfunc = _vfunc('mean')
self._walltime = None
super(Scalar, self).__init__()
def __call__(self): return self._vfunc(self._values)
def vtype(self, type):
self._vfunc = _vfunc(type)
return self
def walltime(self, walltime):
self._walltime = walltime
return self
def _reset(self): self._values = []
def _update(self, v, **kwargs):
self._values.append(_scalar(v))
def _save(self):
self._write('add_scalar', self(), walltime=self._walltime)
@register('scalars')
class Scalars(Indicator):
def __init__(self):
self._scalars = {}
self._walltime = None
super(Scalars, self).__init__()
def __call__(self): return dict([(n, s()) for n, s in self._scalars.items()])
def profiling(self, profiling):
super(Scalars, self).profiling(profiling)
for _, s in self._scalars.items(): s.profiling(profiling)
return self
def walltime(self, walltime):
self._walltime = walltime
return self
def scalar(self, name):
s = create('scalar', name)
self._scalars[name] = s
return self
def _reset(self):
for _, s in self._scalars.items(): s._reset()
def _update(self, vdict, *args, **kwargs):
for k, v in vdict.items():
s = self._scalars[k]
s.update(v, *args, **kwargs)
def _save(self):
self._write('add_scalars', self(), walltime=self._walltime)
@register('histogram')
class Histogram(Scalar):
def __init__(self):
super(Histogram, self).__init__()
self._bins = 'tensorflow'
self._max_bins = None
self._vfunc = _vfunc(None)
def vtype(self, type): raise Exception('can not set vtype for histogram')
def bins(self, bins):
self._bins = bins
return self
def max_bins(self, max_bins):
self._max_bins = max_bins
return self
def _save(self):
self._write('add_histogram', self(), bins=self._bins, max_bins=self._max_bins, walltime=self._walltime)
def _scalar(v):
if isinstance(v, torch.Tensor):
v = v.cpu().data.numpy()
elif isinstance(v, (np.ndarray, float, int)):
pass
else:
raise Exception('Invalid indicator type {}'.format(type(v)))
if len(np.shape(v)) != 0: raise Exception('Invalid indicator value shape: {}'.format(np.shape(v)))
return v
def _vfunc(t):
d = {
None: lambda x: x,
'min': lambda x: np.min(x),
'max': lambda x: np.max(x),
'mean': lambda x: np.mean(x),
'sum': lambda x: np.sum(x),
}
if t not in d: raise Exception('invalid value type {}'.format(t))
return d[t] | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,837 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/core/__init__.py |
from .device import *
del device | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,838 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/nn/modules/conv.py | import numpy as np
def eval_conv_output_size(conv, input_size):
'''
:param conv: convolution kernel
:param input_size: int or tuple with format size / (H, W) / (D, H, W)
:return:
'''
input_size = np.asarray(input_size)
kernel_size = np.asarray(conv.kernel_size)
dilation = np.asarray(conv.dilation)
padding = np.asarray(conv.padding)
stride = np.asarray(conv.stride)
def _conv1d():
"""
https://pytorch.org/docs/stable/nn.html#conv1d
"""
numerator = input_size + 2 * padding - dilation * (kernel_size - 1)
return tuple(np.ceil(numerator / stride + 1).astype(np.int))
def _conv2d():
"""
https://pytorch.org/docs/stable/nn.html#conv2d
"""
numerator = input_size + 2 * padding - dilation * (kernel_size - 1) - 1
return tuple(np.ceil(numerator / stride + 1).astype(np.int))
def _conv3d():
"""
https://pytorch.org/docs/stable/nn.html#conv3d
"""
numerator = input_size + 2 * padding - dilation * (kernel_size - 1) - 1
return tuple(np.ceil(numerator / stride + 1).astype(np.int))
shape = np.shape(conv.kernel_size)
if len(shape) == 0: return _conv1d()
elif shape[0] == 2: return _conv2d()
elif shape[0] == 3: return _conv3d()
raise Exception('Invalid conv kernel {}'.format(conv.kernel_size))
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,839 | tornadoyi/rl-lab | refs/heads/master | /rllab/rl/features/cnn.py | import numpy as np
from collections import OrderedDict
from rllab.torchlab import nn
from .features import register
@register("conv_only")
class conv_only(nn.Sequential):
def __init__(self, input_shape, input_format='NCHW', convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)], **conv_kwargs):
'''
convolutions-only net
Parameters:
----------
input_shape: 4 dims tuple with format NCHW
conv: list of triples (filter_number, filter_size, stride) specifying parameters for each layer.
Returns:
function that takes tensorflow tensor as input and returns the output of the last convolutional layer
'''
assert input_format == 'NCHW' or 'NHWC'
l = []
if input_format == 'NHWC':
l.append(nn.Permute((0, 3, 1, 2)))
input_shape = (input_shape[0], input_shape[3], input_shape[1], input_shape[2])
l.append(nn.Float()),
l.append(nn.TrueDivide(255.))
output_size = input_shape[2:4]
in_channels = input_shape[1]
for out_channels, kernel_size, stride in convs:
# conv2d
conv = nn.Conv2d(in_channels, out_channels, (kernel_size, kernel_size), stride=stride)
l.append(conv)
in_channels = out_channels
# activation
l.append(nn.ReLU())
# evaluate output shape
output_size = nn.eval_conv_output_size(conv, output_size)
layers = [('{}_{}'.format(l[i].__class__.__name__.lower(), i), l[i]) for i in range(len(l))]
super(conv_only, self).__init__(OrderedDict(layers))
self.output_shape = (input_shape[0], in_channels) + output_size
class nature_cnn(nn.Sequential):
def __init__(self, input_shape, input_format='NCHW'):
"""
CNN from Nature paper.
"""
def Conv2d(in_channels, out_channels, kernel_size, stride, init_scale=1.0):
conv2d = nn.Conv2d(in_channels, out_channels, (kernel_size, kernel_size), stride=stride)
nn.init.orthogonal_(conv2d.weight.data, gain=init_scale)
nn.init.constant_(conv2d.bias.data, 0.0)
return conv2d
assert input_format == 'NCHW' or 'NHWC'
l = []
if input_format == 'NHWC':
l.append(nn.Permute((0, 3, 1, 2)))
input_shape = (input_shape[0], input_shape[3], input_shape[1], input_shape[2])
l.append(nn.Float()),
l.append(nn.TrueDivide(255.))
# conv layers
in_channels = input_shape[1]
output_size = input_shape[2:4]
conv = Conv2d(in_channels, 32, 8, 4, init_scale=np.sqrt(2))
output_size = nn.eval_conv_output_size(conv, output_size)
l.append(conv)
l.append(nn.ReLU)
conv = Conv2d(32, 64, 4, 2, init_scale=np.sqrt(2))
output_size = nn.eval_conv_output_size(conv, output_size)
l.append(conv)
l.append(nn.ReLU)
conv = Conv2d(64, 64, 3, 1, init_scale=np.sqrt(2))
output_size = nn.eval_conv_output_size(conv, output_size)
l.append(conv)
l.append(nn.ReLU)
conv_output_shape = (input_shape[0], 64) + output_size
# fc
l.append(nn.Flatten())
flatten_features = int(np.prod(conv_output_shape[1:]))
x = nn.Linear(flatten_features, 512)
nn.init.orthogonal_(x.weight.data, gain=np.sqrt(2))
nn.init.constant_(x.bias.data, 0.0)
l.append(x)
l.append(nn.ReLU)
layers = [('{}_{}'.format(l[i].__class__.__name__.lower(), i), l[i]) for i in range(len(l))]
super(nature_cnn, self).__init__(OrderedDict(layers))
self.output_shape = (input_shape[0], flatten_features)
@register('cnn')
class cnn(nature_cnn):
pass
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,840 | tornadoyi/rl-lab | refs/heads/master | /rllab/define.py |
import os
_ROOT_PATH = os.path.expanduser('~/.rl-lab')
_MODEL_PATH = 'models'
_PROFILING_PATH = 'profiling'
_EXPERIMENT_PATH = None
def root_path(): return _ROOT_PATH
def set_root_path(p):
global _ROOT_PATH
_ROOT_PATH = p
def model_path():
if os.path.isabs(_MODEL_PATH): return _MODEL_PATH
return os.path.join(experiment_path(), _MODEL_PATH)
def set_model_path(p):
global _MODEL_PATH
_MODEL_PATH = p
def profiling_path():
if os.path.isabs(_PROFILING_PATH): return _PROFILING_PATH
return os.path.join(experiment_path(), _PROFILING_PATH)
def set_profiling_path(p):
global _PROFILING_PATH
_PROFILING_PATH = p
def module_path(): return os.path.join(root_path(), which_module())
def experiment_path():
if _EXPERIMENT_PATH is None: raise Exception('empty experiment path')
if os.path.isabs(_EXPERIMENT_PATH): return _EXPERIMENT_PATH
return os.path.join(module_path(), _EXPERIMENT_PATH)
def set_experiment_path(p):
global _EXPERIMENT_PATH
_EXPERIMENT_PATH = p
_MODULE_NAME = None
def which_module():
import traceback
global _MODULE_NAME
if _MODULE_NAME is not None: return _MODULE_NAME
stacks = traceback.extract_stack()
if len(stacks) < 2: raise Exception('can not get module from stack {}'.format(stacks))
for i in range(len(stacks)-2, -1 ,-1):
f = stacks[i].filename
try:
return module(f)
except: continue
raise Exception('can not get module from stack {}'.format(stacks))
def module(f):
__MODULE_MATCH_HEADER = os.path.join('rllab', 'algorithms', '').replace('\\', '/')
f = f.replace('\\', '/')
index = f.rfind(__MODULE_MATCH_HEADER)
if index < 0: raise Exception('Can not get module from file {}'.format(f))
st = index + len(__MODULE_MATCH_HEADER)
ed = f.find('/', st)
if ed < 0: raise Exception('Can not get module from file {}'.format(f))
return f[st:ed]
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,841 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/render/render.py | import pygame
class Render(object):
def __init__(self, env, caption=None, win_size=(640, 480)):
self._env = env
# init
if not pygame.get_init(): pygame.init()
if not pygame.font.get_init(): pygame.font.init()
pygame.display.set_caption(caption or str(env))
pygame.display.set_mode(win_size)
@property
def screen(self): return pygame.display.get_surface()
def __call__(self, *args, **kwargs): self.update()
def update(self):
# process event
for event in pygame.event.get():
self.on_event(event)
# render
self.on_render()
pygame.display.flip()
def on_event(self, event): pass
def on_render(self): pass | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,842 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/utils/exposer.py |
def expose(src, dst, override=False, filter=None):
if filter is None: filter = lambda _: False
for k in dir(src):
v = getattr(src, k)
if (not override and k in dst) or filter(k): continue
dst[k] = v | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,843 | tornadoyi/rl-lab | refs/heads/master | /rllab/cli.py | import signal
import argparse
from easydict import EasyDict as edict
from rllab import algorithms as modules
from rllab import define
MODULES = dict([(n, getattr(modules, n)) for n in dir(modules) if hasattr(getattr(modules, n), 'execute')])
def initialize_path(args, dargs):
# set path
if args.root_path is not None: define.set_root_path(args.root_path)
if args.model_path is not None: define.set_model_path(args.model_path)
if args.profiling_path is not None: define.set_profiling_path(args.profiling_path)
define.set_experiment_path(dargs.arguments.env.id if args.exp_path is None else args.exp_path)
def parse_args():
parser = argparse.ArgumentParser(prog='rl-lab', description="Laboratory of reinforcement learning includes games and algorithms.")
parser.add_argument("module", choices=list(MODULES.keys()), help='supported modules')
parser.add_argument("command", help='command of module')
parser.add_argument('arguments', nargs='*', default=[], help='arguments of command')
parser.add_argument('--root-path', type=str, default=None, help='root path')
parser.add_argument('--model-path', type=str, default=None, help='model path')
parser.add_argument('--profiling-path', type=str, default=None, help='profiling path')
parser.add_argument('--exp-path', type=str, default=None, help='experiment path')
args = parser.parse_args()
# parse parameters
dargs = edict()
dargs['module'] = args.module
dargs['command'] = args.command
dargs['arguments'] = {}
# get env keys
mods, vals = [], []
for a in args.arguments:
m, v = a.split('=')
mods.append(m.split('.'))
vals.append(v)
# exec code
code_dict = {}
exec("parameters = [{}]".format(','.join(vals)), code_dict)
values = code_dict['parameters']
for i in range(len(mods)):
smods = mods[i]
d = dargs['arguments']
for j in range(len(smods)):
n = smods[j]
if j >= len(smods) - 1: d[n] = values[i]
else:
if n not in d: d[n] = {}
d = d[n]
# initialize path
initialize_path(args, dargs)
return dargs
def main():
# catch exit signals
def handle_signals(signum, frame):
exit(0)
signal.signal(signal.SIGINT, handle_signals)
signal.signal(signal.SIGTERM, handle_signals)
# parse args
args = parse_args()
mod = MODULES.get(args.module, None)
# execute mod
mod.execute(args)
if __name__ == '__main__':
main()
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,844 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/optim/optim.py | import inspect
from torch import optim
def build(**kwargs):
name = kwargs.get('name', None)
if name is None: raise Exception('Build optimizer without name')
# get optimizer
opt = getattr(optim, name)
if opt is None: raise Exception('Can not find optimizer {}'.format(name))
# filter args
opt_args = set(inspect.getfullargspec(opt).args)
args = dict([(k, v) for k, v in kwargs.items() if k in opt_args])
return opt(**args) | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,845 | tornadoyi/rl-lab | refs/heads/master | /rllab/rl/features/features.py | from gym.spaces import Box
__FEATURES = {}
def register(name):
global __FEATURES
def _thunk(func):
__FEATURES[name] = func
return func
return _thunk
def build(ob_space, name=None, **feature_kwargs):
# specific feature
input_shape = (None, ) + ob_space.shape
if name is not None: return __FEATURES[name](input_shape, **feature_kwargs)
# build from ob
if not isinstance(ob_space, Box): raise Exception('Invalid ob space {}'.format(ob_space))
if len(ob_space.shape) == 1:
return __FEATURES['mlp'](input_shape, **feature_kwargs)
elif len(ob_space.shape) == 3:
return __FEATURES['conv_only'](input_shape, input_format='NHWC', **feature_kwargs)
else:
raise Exception('Unsupported shape of ob space {}'.format(input_shape)) | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,846 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/race/shuttle_run.py | from .runway import RunwayEnv
class ShuttleRunEnv(RunwayEnv):
def __init__(self, score_mode='normal', **kwargs):
# config
self._score_mode = score_mode
super(ShuttleRunEnv, self).__init__(**kwargs)
def reset(self):
ob = super(ShuttleRunEnv, self).reset()
self._half_finish = False
return [float(self._half_finish)] + ob
def step(self, action):
ob, r, d, info = super(ShuttleRunEnv, self).step(action)
# reward
r = 0
if self._score_mode == 'sparse':
if self._half_finish and self._pos == 0:
r = 1.0
elif self._score_mode == 'guide':
if not self._half_finish:
if action == 1: r = -1.0
elif action == 2: r = 1.0
else:
if action == 1: r = 1.0
elif action == 2: r = -1.0
else:
r = -1.0
if not self._half_finish:
if self._pos == self._length - 1: r = 1.0
else:
if self._pos == 0: r = 1.0
# half finish and terminal
if self._pos == self._length - 1: self._half_finish = True
if self._half_finish and self._pos == 0: d = True
# observation
ob = [float(self._half_finish)] + ob
return ob, r, d, info
def render_infos(self):
return ['half goal: {}'.format('ok' if self._half_finish else 'no')]
import numpy as np
from gym.envs.registration import register
register(
id='ShuttleRun-100m-easy-v0',
entry_point='rllab.envs.race:ShuttleRunEnv',
kwargs={'length': 100, 'move_success_rate': 1.0, 'score_mode': 'guide'},
max_episode_steps=np.inf,
reward_threshold=1.0,
)
register(
id='ShuttleRun-100m-medium-v0',
entry_point='rllab.envs.race:ShuttleRunEnv',
kwargs={'length': 100, 'move_success_rate': 0.9, 'score_mode': 'normal'},
max_episode_steps=int(3 * 200 / 0.9),
reward_threshold=1.0,
)
register(
id='ShuttleRun-100m-hard-v0',
entry_point='rllab.envs.race:ShuttleRunEnv',
kwargs={'length': 100, 'move_success_rate': 0.8, 'score_mode': 'sparse'},
max_episode_steps=int(2 * 200 / 0.8),
reward_threshold=1.0,
) | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,847 | tornadoyi/rl-lab | refs/heads/master | /rllab/algorithms/deepq/network.py | from collections import OrderedDict
from rllab import torchlab as tl
from rllab.torchlab import nn
class QFunc(nn.Module):
def __init__(
self,
ac_space,
feature_creator,
hiddens=(256, ),
dueling=True,
layer_norm=False,
**_,
):
super(QFunc, self).__init__()
self.dueling = dueling
# create feature extractor
self.net_features = feature_creator()
# create action score network
l = []
in_features = 1
for d in self.net_features.output_shape[1:]: in_features *= d
l.append(nn.Flatten())
for hidden in list(hiddens):
l.append(nn.Linear(in_features, hidden))
in_features = hidden
if layer_norm: l.append(nn.LayerNorm([in_features]))
l.append(nn.ReLU())
l.append(nn.Linear(in_features, ac_space.n))
layers = [('{}_{}'.format(l[i].__class__.__name__.lower(), i), l[i]) for i in range(len(l))]
self.net_action_score = nn.Sequential(OrderedDict(layers))
# dueling
if dueling:
l = []
in_features = 1
for d in self.net_features.output_shape[1:]: in_features *= d
l.append(nn.Flatten())
for hidden in list(hiddens):
l.append(nn.Linear(in_features, hidden))
in_features = hidden
if layer_norm: l.append(nn.LayerNorm([in_features]))
l.append(nn.ReLU())
l.append(nn.Linear(in_features, 1))
layers = [('{}_{}'.format(l[i].__class__.__name__.lower(), i), l[i]) for i in range(len(l))]
self.net_state_score = nn.Sequential(OrderedDict(layers))
def forward(self, ob):
ob = self.net_features(ob)
self.action_score = self.net_action_score(ob)
# calculate advantage for dueling network
if self.dueling:
self.state_score = self.net_state_score(ob)
self.action_scores_mean = tl.mean(self.action_score, 1)
self.action_scores_centered = self.action_score - self.action_scores_mean.unsqueeze(1)
self.q = self.state_score + self.action_scores_centered
else:
self.q = self.action_score
return self.q
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,848 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/utils/shell.py | import subprocess
def run(cmd, shell=True, timeout=None):
with subprocess.Popen(cmd, shell=shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
p.wait(timeout)
if p.returncode == 0: return p.stdout.read().decode()
else: raise Exception('Command run error\n{}'.format(p.stderr.read().decode()))
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,849 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/render/__init__.py |
from pygame import *
from .render import Render
del font
from . import font
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,850 | tornadoyi/rl-lab | refs/heads/master | /rllab/envs/race/runway.py | import numpy as np
import gym
from gym import spaces
class RunwayEnv(gym.Env):
def __init__(
self,
length=1,
init_pos=0,
move_success_rate=1.0,
**kwargs
):
super(RunwayEnv, self).__init__(**kwargs)
# config
self._length = length
self._init_pos = init_pos
self._move_success_rate = move_success_rate
# gym
self.action_space = spaces.Discrete(3) # 0: wait 1: move left 2: move right
self.observation_space = spaces.Box(0.0, 1.0, (self._length, ))
# state
self._pos = self._init_pos
# render
self._render = None
def reset(self):
self._pos = self._init_pos
ob = [0.0] * self._length
ob[int(self._pos)] = 1.0
return ob
def step(self, action):
# move
if action != 0 and np.random.rand() < self._move_success_rate:
if action == 1:
self._pos = np.clip(self._pos - 1, 0, self._length - 1)
elif action == 2:
self._pos = np.clip(self._pos + 1, 0, self._length - 1)
# save ob
ob = [0.0] * self._length
ob[int(self._pos)] = 1.0
return ob, 0, False, {}
def render(self, mode='human'):
from .render import Render
if self._render is None: self._render = Render(self)
self._render()
def render_infos(self): return []
| {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,851 | tornadoyi/rl-lab | refs/heads/master | /rllab/algorithms/deepq/trainer.py | from rllab import torchlab as tl
from rllab.torchlab import optim, distributed
from rllab import envs
from rllab.rl import features
from rllab.rl.profiling import Profiling, indicator
from rllab.rl.common.schedule import LinearSchedule
from . import replay_buffer
from .deepq import DeepQ
class Trainer(object):
def __init__(
self,
env,
deepq={},
rb={},
explore={},
optimizer={},
feature={},
total_steps=int(1e6),
learning_starts=1000,
train_freq=1,
target_network_update_freq=500,
profiling={},
batch_size=32,
device=None,
rank=-1,
**_,
):
# arguments
self.total_steps = total_steps
self.learning_starts = learning_starts
self.train_freq = train_freq
self.batch_size = batch_size
self.target_network_update_freq = target_network_update_freq
self.device = device
self.rank = rank
# env
self.env = envs.make(**env)
# features
feature_creator = lambda: features.build(self.env.observation_space, **feature)
# algorithm
self.deepq = DeepQ(
self.env.observation_space,
self.env.action_space,
feature_creator,
**deepq
).to(self.device)
# optimizer
opt = dict({'name':'Adam', 'lr':1e-3}, **optimizer)
self.optimizer = optim.build(params=self.deepq.trained_parameters, **opt)
if rank >= 0: self.optimizer = distributed.GradientReducer(self.optimizer)
# replay buffer
self.replay_buffer = replay_buffer.build(**rb)
# create the schedule for exploration starting from 1.
self.exploration = LinearSchedule(
schedule_timesteps=int(explore.get('fraction', 0.1) * total_steps),
initial_p=explore.get('init', 1.0),
final_p=explore.get('final', 0.02)
)
# steps
self.steps = 0
# profiling
if self.rank <= 0:
self.profiling = Profiling(self.env, step_func=lambda: self.steps, **profiling)
def __call__(self, *args, **kwargs):
ob = self.env.reset()
while self.steps < self.total_steps:
self.steps += 1
# self.env.render()
# evaluate action
eps = self.exploration.value(self.steps)
action = self.deepq.act(
tl.as_tensor(ob, dtype=tl.float32, device=self.device),
eps
).cpu().data.numpy()
# exec action
ob_n, rew, done, _ = self.env.step(action)
# store transition in the replay buffer.
self.replay_buffer.add(ob, action, rew, ob_n, float(done))
# train once
learn_info = None
if self.steps > self.learning_starts and self.steps % self.train_freq == 0:
obs, acs, rews, obs_n, dones = self.replay_buffer.sample(self.batch_size)
learn_info = self.deepq.learn(
self.optimizer,
tl.as_tensor(obs, dtype=tl.float32, device=self.device),
tl.as_tensor(acs, dtype=tl.long, device=self.device),
tl.as_tensor(rews, dtype=tl.float32, device=self.device),
tl.as_tensor(obs_n, dtype=tl.float32, device=self.device),
tl.as_tensor(dones, dtype=tl.float32, device=self.device),
tl.as_tensor([1.0] * obs.shape[0], dtype=tl.float32, device=self.device),
)
# update target network
if self.steps > self.learning_starts and self.steps % self.target_network_update_freq == 0:
self.deepq.update_target_network()
# profiling
if self.rank <= 0:
self.profile({'explore_epsilon': eps}, learn_info)
# next
ob = ob_n
if done: ob = self.env.reset()
def profile(self, hps, learn_info):
p = self.profiling
# hyper parameters
for k, v in hps.items():
p.update('hp/{}'.format(k), v, creator=lambda: indicator('scalar').cond('update', 100))
# profile learn info
learn_info = learn_info or {}
for k, (v, creator) in learn_info.items():
p.update(k, v, creator=creator)
# step for profiling
p()
def train(dist=None, device=None, **kwargs):
# select device
device = tl.select_device(device)
# single process
if dist is None: return Trainer(device=device, **kwargs)()
distributed.launch(target=dist_train, kwargs={'device':device, 'kwargs': kwargs}, **dist)
# distributed
def dist_train(device, kwargs):
rank = distributed.get_rank()
# set device
dist_device = device
if device.type == 'cuda':
index = rank % tl.cuda.device_count()
dist_device = tl.device('cuda:{}'.format(index))
Trainer(rank=rank, device=dist_device, **kwargs)() | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,852 | tornadoyi/rl-lab | refs/heads/master | /rllab/torchlab/nn/__init__.py | from torch.nn import *
from .modules import *
del functional
from . import functional | {"/rllab/torchlab/core/device.py": ["/rllab/torchlab/__init__.py"], "/rllab/rl/profiling/__init__.py": ["/rllab/rl/profiling/profiling.py"], "/rllab/rl/features/mlp.py": ["/rllab/rl/features/features.py"], "/rllab/rl/features/__init__.py": ["/rllab/rl/features/features.py"], "/rllab/torchlab/nn/modules/__init__.py": ["/rllab/torchlab/nn/modules/tensor.py", "/rllab/torchlab/nn/modules/conv.py"], "/rllab/envs/__init__.py": ["/rllab/envs/wrapper/__init__.py"], "/rllab/algorithms/deepq/__init__.py": ["/rllab/algorithms/deepq/trainer.py"], "/rllab/torchlab/__init__.py": ["/rllab/torchlab/core/__init__.py"], "/rllab/torchlab/distributed/__init__.py": ["/rllab/torchlab/distributed/launcher.py", "/rllab/torchlab/distributed/optimizer.py"], "/rllab/algorithms/deepq/deepq.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/nn/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/network.py"], "/rllab/envs/wrapper/__init__.py": ["/rllab/envs/wrapper/profiling.py", "/rllab/envs/wrapper/reward_ratio.py"], "/rllab/envs/race/race.py": ["/rllab/envs/race/runway.py"], "/rllab/torchlab/profiling/profiling.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/profiling/__init__.py": ["/rllab/torchlab/profiling/profiling.py", "/rllab/torchlab/profiling/indicator.py"], "/rllab/torchlab/optim/__init__.py": ["/rllab/torchlab/optim/optim.py"], "/rllab/envs/race/__init__.py": ["/rllab/envs/race/race.py", "/rllab/envs/race/shuttle_run.py"], "/rllab/rl/profiling/profiling.py": ["/rllab/torchlab/__init__.py", "/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/cuda/cuda.py": ["/rllab/torchlab/utils/__init__.py"], "/rllab/envs/race/render.py": ["/rllab/envs/__init__.py"], "/rllab/torchlab/cuda/__init__.py": ["/rllab/torchlab/cuda/cuda.py"], "/rllab/envs/wrapper/profiling.py": ["/rllab/envs/wrapper/utils.py"], "/rllab/torchlab/profiling/indicator.py": ["/rllab/torchlab/profiling/__init__.py"], "/rllab/torchlab/core/__init__.py": ["/rllab/torchlab/core/device.py"], "/rllab/rl/features/cnn.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/features/features.py"], "/rllab/envs/race/shuttle_run.py": ["/rllab/envs/race/runway.py"], "/rllab/algorithms/deepq/network.py": ["/rllab/torchlab/__init__.py"], "/rllab/envs/render/__init__.py": ["/rllab/envs/render/render.py"], "/rllab/envs/race/runway.py": ["/rllab/envs/race/render.py"], "/rllab/algorithms/deepq/trainer.py": ["/rllab/torchlab/__init__.py", "/rllab/rl/profiling/__init__.py", "/rllab/algorithms/deepq/__init__.py", "/rllab/algorithms/deepq/deepq.py"], "/rllab/torchlab/nn/__init__.py": ["/rllab/torchlab/nn/modules/__init__.py"]} |
56,868 | msh5/escher | refs/heads/master | /escher/__init__.py | import os
import sys
from escher.__version__ import __version__
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
PROJECT_VENDOR = os.sep.join([PROJECT_ROOT, 'vendor'])
sys.path.insert(0, PROJECT_VENDOR)
| {"/escher/cmd/esdsl.py": ["/escher/__init__.py"], "/escher/cmd/escat.py": ["/escher/__init__.py"], "/escher/cmd/essearch.py": ["/escher/__init__.py"]} |
56,869 | msh5/escher | refs/heads/master | /escher/cmd/esdsl.py | '''
Define subcommands for 'esdsl'.
'''
import json
import click
from escher import __version__
@click.group()
@click.option('--pretty', '-p', is_flag=True)
@click.option('--indent', '-n', type=int)
@click.version_option(version=__version__, message='escher %(version)s')
@click.pass_context
def cli(ctx, pretty, indent):
if pretty:
indent = 4
if indent:
ctx.obj['indent_size'] = indent
def echo_query(ctx, query):
indent_size = None
if 'indent_size' in ctx.obj:
indent_size = ctx.obj['indent_size']
resp = json.dumps(query, indent=indent_size)
click.echo(resp)
@click.command()
@click.option('--boost', '-b', type=float)
@click.pass_context
def match_all(ctx, boost):
query = {'match_all': {}}
if boost:
query['match_all']['boost'] = boost
echo_query(ctx, query)
@click.command()
@click.pass_context
def match_none(ctx):
echo_query(ctx, {"match_none": {}})
cli.add_command(match_all, name="match-all")
cli.add_command(match_none, name="match-none")
def main():
cli(obj={})
| {"/escher/cmd/esdsl.py": ["/escher/__init__.py"], "/escher/cmd/escat.py": ["/escher/__init__.py"], "/escher/cmd/essearch.py": ["/escher/__init__.py"]} |
56,870 | msh5/escher | refs/heads/master | /escher/cmd/escat.py | '''
Define subcommands for 'escat'.
'''
import json
import click
from elasticsearch import Elasticsearch
from escher import __version__
from tabulate import tabulate
ALLOCATION_BYTES_OPTIONS = [
'b', 'k', 'kb', 'm', 'mb', 'g', 'gb', 't', 'tb', 'p', 'pb'
]
@click.group()
@click.option('--host', '-h', default='localhost')
@click.option('--port', '-p', type=int, default=80)
@click.option('--ssl/--no-ssl', default=False)
@click.version_option(version=__version__, message='escher %(version)s')
@click.pass_context
def cli(ctx, host, port, ssl):
ctx.obj['host_spec'] = {'host': host, 'port': port, 'use_ssl': ssl}
@click.command()
@click.option('--format', '-f', 'response_format')
@click.option('--local', is_flag=True, default=None)
@click.option('--master-timeout', 'timeout')
@click.option('--hint', '-h', 'hints', multiple=True)
@click.option('--help-api', 'help_api', is_flag=True, default=None)
@click.option('--sort', '-s', 'sort_hints', multiple=True)
@click.option('--verbose', '-v', is_flag=True, default=None)
@click.argument('names', nargs=-1)
@click.pass_context
def aliases(ctx, response_format, local, timeout, hints, help_api, sort_hints,
verbose, names):
host = ctx.obj['host_spec']
client = Elasticsearch(hosts=[host])
params = {}
if response_format:
params['format'] = response_format
if local:
params['local'] = local
if timeout:
params['master_timeout'] = timeout
if hints:
params['h'] = ','.join(hints)
if help_api:
params['help'] = help_api
if sort_hints:
params['s'] = ','.join(sort_hints)
if verbose:
params['v'] = verbose
if names:
params['name'] = ','.join(names)
resp_str = client.cat.aliases(**params)
resp = json.loads(resp_str) if resp_str else {}
click.echo(tabulate(resp.items()))
@click.command()
@click.option('--format', '-f', 'response_format')
@click.option('--local', is_flag=True, default=None)
@click.option('--master-timeout', 'timeout')
@click.option('--node-id', 'node_ids', multiple=True)
@click.option(
'--bytes', 'bytes_unit', type=click.Choice(ALLOCATION_BYTES_OPTIONS))
@click.option('--hint', '-h', 'hints', multiple=True)
@click.option('--help-api', 'help_api', is_flag=True, default=None)
@click.option('--sort', '-s', 'sort_hints', multiple=True)
@click.option('--verbose', '-v', is_flag=True, default=None)
@click.pass_context
def allocation(ctx, response_format, local, timeout, node_ids, bytes_unit,
hints, help_api, sort_hints, verbose):
host = ctx.obj['host_spec']
client = Elasticsearch(hosts=[host])
params = {}
if response_format:
params['format'] = response_format
if local:
params['local'] = local
if timeout:
params['master_timeout'] = timeout
if node_ids:
params['node_id'] = ','.join(node_ids)
if timeout:
params['bytes'] = bytes_unit
if hints:
params['h'] = ','.join(hints)
if help_api:
params['help'] = help_api
if sort_hints:
params['s'] = ','.join(sort_hints)
if verbose:
params['v'] = verbose
resp_str = client.cat.allocation(**params)
click.echo(resp_str)
cli.add_command(aliases)
cli.add_command(allocation)
def main():
cli(obj={})
| {"/escher/cmd/esdsl.py": ["/escher/__init__.py"], "/escher/cmd/escat.py": ["/escher/__init__.py"], "/escher/cmd/essearch.py": ["/escher/__init__.py"]} |
56,871 | msh5/escher | refs/heads/master | /escher/cmd/essearch.py | '''
Define subcommands for 'essearch'.
'''
import json
import click
from elasticsearch import Elasticsearch
from escher import __version__
def build_request_body(queries, aggs):
body = {}
if queries:
body['query'] = []
for query in queries:
query_dict = json.dumps(query)
body['query'].append(query_dict)
if aggs:
body['aggs'] = []
for agg in aggs:
agg_dict = json.dumps(agg)
body['aggs'].append(agg_dict)
return body
@click.command()
@click.option('--host', '-h', default='localhost')
@click.option('--port', '-p', type=int, default=80)
@click.option('--ssl/--no-ssl', default=False)
@click.option('--index', '-i', 'indices', multiple=True)
@click.option('--query', '-q', 'queries', multiple=True)
@click.option('--agg', '-a', 'aggs', multiple=True)
@click.option('--pretty', '-p', is_flag=True)
@click.option('--indent', '-n', 'indent_size', type=int)
@click.version_option(version=__version__, message='escher %(version)s')
def search(host, port, ssl, indices, queries, aggs, pretty, indent_size):
host_spec = {'host': host, 'port': port, 'use_ssl': ssl}
client = Elasticsearch(hosts=[host_spec])
params = {}
params['index'] = ','.join(indices)
params['body'] = build_request_body(queries, aggs)
response = client.search(**params)
if pretty:
indent_size = 4
resp = json.dumps(response, indent=indent_size)
click.echo(resp)
def main():
search()
| {"/escher/cmd/esdsl.py": ["/escher/__init__.py"], "/escher/cmd/escat.py": ["/escher/__init__.py"], "/escher/cmd/essearch.py": ["/escher/__init__.py"]} |
56,872 | Mal-lol-git/Total_Scanner | refs/heads/master | /settings.py | #VIRUS_TOTAL_SCANNER SETTINGS
from urllib.parse import urljoin
#VIRUS_TOTAL
#URL, API_KEY
API_KEY = '[API]'
API_URL = 'https://www.virustotal.com/api/v3/'
API_SEARCH = urljoin(API_URL, 'intelligence/search')
API_ATTACH = urljoin(API_URL, 'files/')
#SEARCH_OPTION
OPTION_DAYS = []
OPTION_SCAN_TYPE = []
#SEARCH_PARAMS
descriptors_only = False
cursor = None
s_limit = 300
#LIST_INDEX
MD5 = []
RESULT = []
#SAVE_PATH
HASH_SAVE_PATH = '[PATH.txt]'
CSV_PATH = '[PATH.csv]'
| {"/TotalScan/TotalScan_class.py": ["/settings.py"], "/TotalScan/Save.py": ["/settings.py"], "/main.py": ["/Data/Keyword.py", "/TotalScan/Save.py", "/TotalScan/Search.py", "/thread.py"], "/TotalScan/Search.py": ["/TotalScan/Option_filter.py", "/TotalScan/TotalScan_class.py"]} |
56,873 | Mal-lol-git/Total_Scanner | refs/heads/master | /TotalScan/Option_filter.py | import chardet
#Arg number
def _Option_filter(option, data, row):
try:
if option == '1':
if chardet.detect(''.join(data['data'][row]['attributes']['names'][0]).encode())['encoding'] == 'utf-8':
return True
if option == '2':
if chardet.detect(''.join(data['data'][row]['attributes']['names'][0]).encode())['encoding'] == 'utf-8' or data['data'][row]['attributes']['type_extension'] == 'eml':
return True
if option == '3':
return True
except Exception as e:
return False
| {"/TotalScan/TotalScan_class.py": ["/settings.py"], "/TotalScan/Save.py": ["/settings.py"], "/main.py": ["/Data/Keyword.py", "/TotalScan/Save.py", "/TotalScan/Search.py", "/thread.py"], "/TotalScan/Search.py": ["/TotalScan/Option_filter.py", "/TotalScan/TotalScan_class.py"]} |
56,874 | Mal-lol-git/Total_Scanner | refs/heads/master | /thread.py | # -*- coding:utf-8 -*-
from concurrent.futures import ThreadPoolExecutor
def Tasker(f, number, *args):
with ThreadPoolExecutor(max_workers=number) as executor:
executor.map(f, *args)
return True
| {"/TotalScan/TotalScan_class.py": ["/settings.py"], "/TotalScan/Save.py": ["/settings.py"], "/main.py": ["/Data/Keyword.py", "/TotalScan/Save.py", "/TotalScan/Search.py", "/thread.py"], "/TotalScan/Search.py": ["/TotalScan/Option_filter.py", "/TotalScan/TotalScan_class.py"]} |
56,875 | Mal-lol-git/Total_Scanner | refs/heads/master | /TotalScan/TotalScan_class.py | #-*- coding: utf-8 -*-
import json
import requests
from settings import *
class TotalScanner():
def __init__(self):
super().__init__()
def _Connect(self):
try:
session = requests.Session()
session.headers = {'X-Apikey': API_KEY}
return session
except Exception as e:
return False
def _SearchQuery(self, con, url, keyword):
try:
params = {"query": keyword, "descriptors_only": descriptors_only, "cursor": cursor, "limit": s_limit}
with con.get(url, params=params) as res:
return res
except Exception as e:
return False
def _AttachQuery(self, con, url, md5):
try:
api_attach = urljoin(url, md5 + '/' + relationship)
params = {"limit": a_limit}
with con.get(api_attach, params=params) as res:
return res
except Exception as e:
return False
def _JsonData(self, data):
try:
return data.json()
except Exception as e:
return False
def _GetStartKey(self, data):
KEY = []
try:
if type(data) is dict:
for row in data:
KEY.append(row)
return KEY
except Exception as e:
return False
def _KeyFind(self, data, f_key):
try:
for row in data:
if str(row) == f_key:
return row
except Exception as e:
return False
| {"/TotalScan/TotalScan_class.py": ["/settings.py"], "/TotalScan/Save.py": ["/settings.py"], "/main.py": ["/Data/Keyword.py", "/TotalScan/Save.py", "/TotalScan/Search.py", "/thread.py"], "/TotalScan/Search.py": ["/TotalScan/Option_filter.py", "/TotalScan/TotalScan_class.py"]} |
56,876 | Mal-lol-git/Total_Scanner | refs/heads/master | /TotalScan/Save.py | from settings import *
def hash_save():
with open(HASH_SAVE_PATH, 'w') as f:
for row in list(set(MD5)):
f.write('%s\n' % row)
| {"/TotalScan/TotalScan_class.py": ["/settings.py"], "/TotalScan/Save.py": ["/settings.py"], "/main.py": ["/Data/Keyword.py", "/TotalScan/Save.py", "/TotalScan/Search.py", "/thread.py"], "/TotalScan/Search.py": ["/TotalScan/Option_filter.py", "/TotalScan/TotalScan_class.py"]} |
56,877 | Mal-lol-git/Total_Scanner | refs/heads/master | /Data/Keyword.py |
#Keyword
keywords = {'tag:macros doc run-file',
'tag:doc exploit',
'tag:email',
'tag:peexe',
'tag:vba url-pattern exe-pattern create-ole'}
| {"/TotalScan/TotalScan_class.py": ["/settings.py"], "/TotalScan/Save.py": ["/settings.py"], "/main.py": ["/Data/Keyword.py", "/TotalScan/Save.py", "/TotalScan/Search.py", "/thread.py"], "/TotalScan/Search.py": ["/TotalScan/Option_filter.py", "/TotalScan/TotalScan_class.py"]} |
56,878 | Mal-lol-git/Total_Scanner | refs/heads/master | /main.py | #-*- coding: utf-8 -*-
import csv
from time import time
from Data.Keyword import keywords
from TotalScan.Save import hash_save
from TotalScan.Search import *
from thread import *
#========Main========
day = input('ex)2020-01-01, Date :')
OPTION_DAYS.append(" fs:"+day+"00:00:00+ fs:"+day+"23:59:59-")
print('''
[+] [Scan Type]
[+] 1) UTF-8(filename) Type Scan
[+] 2) UTF-8 Type + All EML File Type Scan
[+] 3) All Scan
''')
OPTION_SCAN_TYPE.append(input('[+] Select Number : '))
#Start_Timer
start = time()
#Thead
Tasker(KeywordSearch, 8, keywords)
#End_Timer
end = time()
print('%.3f seconds' % (end-start))
#Hash Save(.txt)
hash_save()
#Meta Save(.csv)
f_csv = open(CSV_PATH,'w', encoding='utf-8-sig', newline='')
w_csv = csv.writer(f_csv)
for row in RESULT:
w_csv.writerow(row)
f_csv.close()
print('\nend...')
#====================
| {"/TotalScan/TotalScan_class.py": ["/settings.py"], "/TotalScan/Save.py": ["/settings.py"], "/main.py": ["/Data/Keyword.py", "/TotalScan/Save.py", "/TotalScan/Search.py", "/thread.py"], "/TotalScan/Search.py": ["/TotalScan/Option_filter.py", "/TotalScan/TotalScan_class.py"]} |
56,879 | Mal-lol-git/Total_Scanner | refs/heads/master | /TotalScan/Search.py | #-*- coding: utf-8 -*-
import re
import chardet
from urllib import parse
from TotalScan.Option_filter import _Option_filter
from TotalScan.TotalScan_class import *
def KeywordSearch(keyword):
try:
#Total Query
key_enc = parse.quote(keyword)
query = keyword + OPTION_DAYS[0]
#TotalScan_class
test = TotalScanner()
#Total connect
con = test._Connect()
result = test._SearchQuery(con, API_SEARCH, query)
#Check Status_code
if result.status_code != 200:
print(result, ' Check virustotal connection.')
return
#Create Json Data
data = test._JsonData(result)
for row in range(len(data['data'])):
if bool(''.join(data['data'][row]['attributes']['names'])):
if _Option_filter(OPTION_SCAN_TYPE[0], data, row):
RESULT.append(_Result(data, row, test))
except Exception as e:
print(e)
def _Result(data, row, test):
md5 = data['data'][row]['attributes']['md5']
MD5.append(data['data'][row]['attributes']['md5'])
filename = ''.join(data['data'][row]['attributes']['names'][0])
encoding = chardet.detect(''.join(data['data'][row]['attributes']['names'][0]).encode())['encoding']
ahnlab = data['data'][row]['attributes']['last_analysis_results']['AhnLab-V3']['category']
alyac = data['data'][row]['attributes']['last_analysis_results']['ALYac']['category']
virobot = data['data'][row]['attributes']['last_analysis_results']['ViRobot']['category']
filetype = data['data'][row]['attributes']['type_extension'] if test._KeyFind(data['data'][row]['attributes'], 'type_extension') else '-'
ratio = str(data['data'][row]['attributes']['last_analysis_stats']['malicious'])
return md5, filename, encoding, ahnlab, alyac, virobot, filetype, ratio
| {"/TotalScan/TotalScan_class.py": ["/settings.py"], "/TotalScan/Save.py": ["/settings.py"], "/main.py": ["/Data/Keyword.py", "/TotalScan/Save.py", "/TotalScan/Search.py", "/thread.py"], "/TotalScan/Search.py": ["/TotalScan/Option_filter.py", "/TotalScan/TotalScan_class.py"]} |
56,888 | Suguru36/raspizero_sensor | refs/heads/master | /TestSourceCode/get_ip.py | #!/usr/bin/env python
#pythonの標準ライブラリですね
import socket
try:
#socket.AF_INET:IVv4のアドレス, socket.SOCK_DGRAM:UDPネットワークの
#IPv6の場合はAF_INET→IF_INET6
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#タイムアウトを10秒
s.settimeout(10)
#ipアドレス8.8.8.8:80に接続します。
# 8.8.8.8はgoogle Public DNSPCのIP。
# 外のアドレスなら何でもいいです。
s.connect(("8.8.8.8", 80))
#今の接続のソケット名を取得します。
ip=s.getsockname()[0]
#IPアドレス表示
print(ip)
except socket.error:
print('No Internet') | {"/EnvionmentSensorLogger.py": ["/papirus_cont.py", "/Bme280Cnt.py"]} |
56,889 | Suguru36/raspizero_sensor | refs/heads/master | /TestSourceCode/PapirusTest.py | #!/usr/bin/env python
from papirus import PapirusTextPos
papi = PapirusTextPos()
papi.AddText("00-00 00:00", 0 ,0 ,Id="date-time")
papi.AddText("00.000", 0 ,20 ,Id="temp")
#papi.Add
papi.UpdateText("Start", "New Text") | {"/EnvionmentSensorLogger.py": ["/papirus_cont.py", "/Bme280Cnt.py"]} |
56,890 | Suguru36/raspizero_sensor | refs/heads/master | /EnvionmentSensorLogger.py | #!/usr/bin/env python
from papirus_cont import papirus_cont
from Bme280Cnt import Bme280Cnt
from time import sleep
import ambient
#
# Ambient Livraryが必要です。
# https://ambidata.io/refs/python/
#
class EnvionmentSensorLogger(object):
def __init__(self):
self.papi = papirus_cont()
self.Bme280 = Bme280Cnt()
self.ambi = ambient.Ambient(4779, "95a3ddcb3130ffe7")
def get_bme280_data(self):
self.Bme280.readDataFromBme280()
self.humid = self.Bme280.getHumData()
self.temp = self.Bme280.getTempData()
self.press = self.Bme280.getPresData()
def disp_data(self):
self.papi.set_new_datetime()
self.papi.set_hum(self.humid)
self.papi.set_temp(self.temp)
self.papi.set_press(self.press)
self.papi.set_ipaddress()
self.papi.update()
def sendDataToAmbient(self):
self.r = self.ambi.send({"d1": self.temp, "d2": self.humid ,"d3": self.press})
def network_state(self):
#print(self.papi.get_network_state())
if ((self.papi.get_network_state()) == 'No Internet'):
return False
else:
return True
#------------------------------------------
if __name__ == "__main__":
Sens = EnvionmentSensorLogger()
while(True):
Sens.get_bme280_data()
sleep(3)
Sens.disp_data()
sleep(3)
if (Sens.network_state()):
#print('ON')
Sens.sendDataToAmbient()
else:
#print('OFF')
pass
sleep(4)
| {"/EnvionmentSensorLogger.py": ["/papirus_cont.py", "/Bme280Cnt.py"]} |
56,891 | Suguru36/raspizero_sensor | refs/heads/master | /VL53L1Xcnt.py | import sys
sys.path.insert(0,"build/lib.linux-armv7l-2.7/")
import VL53L1X
import time
from datetime import datetime
tof = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=0x29)
tof.open() # Initialise the i2c bus and configure the sensor
tof.start_ranging(1) # Start ranging, 1 = Short Range, 2 = Medium Range, 3 = Long Range
distance_in_mm = tof.get_distance() # Grab the range in mm
try:
while True:
distance_mm = tof.get_distance()
print("Time: {} Distance: {}mm".format(datetime.utcnow().strftime("%S.%f"), distance_mm))
time.sleep(0.001)
except KeyboardInterrupt:
tof.stop_ranging()
tof.stop_ranging() # Stop ranging | {"/EnvionmentSensorLogger.py": ["/papirus_cont.py", "/Bme280Cnt.py"]} |
56,892 | Suguru36/raspizero_sensor | refs/heads/master | /TestSourceCode/temptest.py | import smbus
from time import sleep
bus = smbus.SMBus(1)
Temp = []
Pres = []
Humi = []
tt = 0.0
# Write Sensor I2C
def writeSensor(reg_addr, data):
bus.write_byte_data(0x76, reg_addr, data)
# Get Calibration Data
def getCalibration():
calib = []
for i in range(0x88, 0x88+24):
calib.append(bus.read_byte_data(0x76, i))
calib.append(bus.read_byte_data(0x76, 0xA1))
for i in range(0xE1, 0xE1+7):
calib.append(bus.read_byte_data(0x76, i))
Temp.append((calib[1] << 8) | calib[0])
Temp.append((calib[3] << 8) | calib[2])
Temp.append((calib[5] << 8) | calib[4])
Pres.append((calib[7] << 8) | calib[6])
Pres.append((calib[9] << 8) | calib[8])
Pres.append((calib[11]<< 8) | calib[10])
Pres.append((calib[13]<< 8) | calib[12])
Pres.append((calib[15]<< 8) | calib[14])
Pres.append((calib[17]<< 8) | calib[16])
Pres.append((calib[19]<< 8) | calib[18])
Pres.append((calib[21]<< 8) | calib[20])
Pres.append((calib[23]<< 8) | calib[22])
Humi.append( calib[24] )
Humi.append((calib[26]<< 8) | calib[25])
Humi.append( calib[27] )
Humi.append((calib[28]<< 4) | (0x0F & calib[29]))
Humi.append((calib[30]<< 4) | ((calib[29] >> 4) & 0x0F))
Humi.append( calib[31] )
for i in range(1,2):
if Temp[i] & 0x8000:
Temp[i] = (-Temp[i] ^ 0xFFFF) + 1
for i in range(1,8):
if Pres[i] & 0x8000:
Pres[i] = (-Pres[i] ^ 0xFFFF) + 1
for i in range(0,6):
if Humi[i] & 0x8000:
Humi[i] = (-Humi[i] ^ 0xFFFF) + 1
# Read Now Temperature,Pressure,Humidity
def readData():
data = []
for i in range(0xF7, 0xF7+8):
data.append(bus.read_byte_data(0x76, i))
pres = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4)
temp = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4)
humi = (data[6] << 8) | data[7]
t2 = adjustTemp(temp)
p2 = adjustPres(pres)
h2 = adjustHumi(humi)
print "temp : %6.2f C" % t2
print "pressure : %7.2f hPa" % p2
print "hum : %6.2f %%" % h2
print ""
# Adjust Pressure by Calibration
def adjustPres(nowpres):
global tt
pressure = 0.0
v1 = (tt / 2.0) - 64000.0
v2 = (((v1 / 4.0) * (v1 / 4.0)) / 2048) * Pres[5]
v2 = v2 + ((v1 * Pres[4]) * 2.0)
v2 = (v2 / 4.0) + (Pres[3] * 65536.0)
v1 = (((Pres[2] * (((v1 / 4.0) * (v1 / 4.0)) / 8192)) / 8) \
+ ((Pres[1] * v1) / 2.0)) / 262144
v1 = ((32768 + v1) * Pres[0]) / 32768
if v1 == 0:
return 0
pressure = ((1048576 - nowpres) - (v2 / 4096)) * 3125
if pressure < 0x80000000:
pressure = (pressure * 2.0) / v1
else:
pressure = (pressure / v1) * 2
v1 = (Pres[8] * (((pressure / 8.0) * (pressure / 8.0)) \
/ 8192.0)) / 4096
v2 = ((pressure / 4.0) * Pres[7]) / 8192.0
pressure = pressure + ((v1 + v2 + Pres[6]) / 16.0)
return pressure/100
# Adjust Temperature by Calibration
def adjustTemp(nowtemp):
global tt
v1 = (nowtemp / 16384.0 - Temp[0] / 1024.0) * Temp[1]
v2 = (nowtemp / 131072.0 - Temp[0] / 8192.0) \
* (nowtemp / 131072.0 - Temp[0] / 8192.0) * Temp[2]
tt = v1 + v2
temperature = tt / 5120.0
return temperature
# Adjust Humidity by Calibration
def adjustHumi(nowhumi):
global tt
var_h = tt - 76800.0
if var_h != 0:
var_h = (nowhumi - (Humi[3] * 64.0 + Humi[4]/16384.0 \
* var_h)) * (Humi[1] / 65536.0 * (1.0 \
+ Humi[5] / 67108864.0 * var_h * (1.0 \
+ Humi[2] / 67108864.0 * var_h)))
else:
return 0
var_h = var_h * (1.0 - Humi[0] * var_h / 524288.0)
if var_h > 100.0:
var_h = 100.0
elif var_h < 0.0:
var_h = 0.0
return var_h
# Initialize Sensor
def setup():
Tovs = 1 # Temperature oversampling x 1
Povs = 1 # Pressure oversampling x 1
Hovs = 1 # Humidity oversampling x 1
mode = 3 # Normal mode
stby = 5 # Tstandby 1000ms
filter = 0 # Filter off
spion = 0 # 3-wire SPI Disable
ctrl_meas_reg = (Tovs << 5) | (Povs << 2) | mode
config_reg = (stby << 5) | (filter << 2) | spion
ctrl_hum_reg = Hovs
writeSensor(0xF2, ctrl_hum_reg)
writeSensor(0xF4, ctrl_meas_reg)
writeSensor(0xF5, config_reg)
# Main
setup()
getCalibration()
try:
while True:
readData()
sleep(3.0)
except KeyboardInterrupt:
pass | {"/EnvionmentSensorLogger.py": ["/papirus_cont.py", "/Bme280Cnt.py"]} |
56,893 | Suguru36/raspizero_sensor | refs/heads/master | /TestSourceCode/papi_ipaddr.py | #!/usr/bin/env python
import os
import sys
import socket
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import datetime
import time
from papirus import Papirus
import RPi.GPIO as GPIO
# Assume Papirus Zero
SW1 = 21
# Check EPD_SIZE is defined
EPD_SIZE=0.0
if os.path.exists('/etc/default/epd-fuse'):
execfile('/etc/default/epd-fuse')
if EPD_SIZE == 0.0:
print("Please select your screen size by running 'papirus-config'.")
sys.exit()
# Running as root only needed for older Raspbians without /dev/gpiomem
if not (os.path.exists('/dev/gpiomem') and os.access('/dev/gpiomem', os.R_OK | os.W_OK)):
user = os.getuid()
if user != 0:
print("Please run script as root")
sys.exit()
WHITE = 1
BLACK = 0
# fonts are in different places on Raspbian/Angstrom so search
possible_fonts = [
'/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-Bold.ttf', # R.Pi
'/usr/share/fonts/truetype/freefont/FreeMono.ttf', # R.Pi
'/usr/share/fonts/truetype/LiberationMono-Bold.ttf', # B.B
'/usr/share/fonts/truetype/DejaVuSansMono-Bold.ttf', # B.B
'/usr/share/fonts/TTF/FreeMonoBold.ttf', # Arch
'/usr/share/fonts/TTF/DejaVuSans-Bold.ttf' # Arch
]
FONT_FILE = ''
for f in possible_fonts:
if os.path.exists(f):
FONT_FILE = f
break
if '' == FONT_FILE:
raise 'no font file found'
CLOCK_FONT_SIZE = 16
MAX_START = 0xffff
def main(argv):
"""main program - draw and display a test image"""
GPIO.setmode(GPIO.BCM)
GPIO.setup(SW1, GPIO.IN)
papirus = Papirus()
print('panel = {p:s} {w:d} x {h:d} version={v:s} COG={g:d} FILM={f:d}'.format(p=papirus.panel, w=papirus.width, h=papirus.height, v=papirus.version, g=papirus.cog, f=papirus.film))
papirus.clear()
demo(papirus)
def demo(papirus):
"""simple partial update demo - draw draw a clock"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(10)
try:
s.connect(("8.8.8.8", 80))
ip=s.getsockname()[0]
print ip
socketok = 1
except socket.error, e:
print 'IP Address Error.'
socketok = 0
# initially set all white background
image = Image.new('1', papirus.size, WHITE)
# prepare for drawing
draw = ImageDraw.Draw(image)
width, height = image.size
clock_font = ImageFont.truetype(FONT_FILE, CLOCK_FONT_SIZE)
# clear the display buffer
draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE)
previous_second = 0
eee = 0
while True:
while True:
now = datetime.datetime.today()
if now.second != previous_second:
break
time.sleep(0.1)
if GPIO.input(SW1) == False:
eee = 1
time.sleep(0.2)
draw.rectangle((2, 2, width - 2, height - 2), fill=WHITE, outline=BLACK)
if socketok == 1:
draw.text((5, 10), ip, fill=BLACK, font=clock_font)
else:
draw.text((5, 10), 'Network Error !', fill=BLACK, font=clock_font)
draw.text((5, 30), '{y:04d}-{m:02d}-{d:02d} {h:02d}:{f:02d}:{s:02d}'.format(y=now.year, m=now.month, d=now.day, h=now.hour, f=now.minute, s=now.second), fill=BLACK, font=clock_font)
if eee == 0:
draw.text((5, 50), 'SW1 : Shut Down', fill=BLACK, font=clock_font)
else:
draw.text((5, 50), 'System Shut Down...', fill=BLACK, font=clock_font)
# display image on the panel
papirus.display(image)
if now.second < previous_second:
papirus.update() # full update every minute
else:
papirus.partial_update()
previous_second = now.second
if eee == 1:
os.system("sudo shutdown -h now")
sys.exit()
eee = 2
# main
if "__main__" == __name__:
if len(sys.argv) < 1:
sys.exit('usage: {p:s}'.format(p=sys.argv[0]))
try:
main(sys.argv[1:])
except KeyboardInterrupt:
sys.exit('interrupted')
pass
| {"/EnvionmentSensorLogger.py": ["/papirus_cont.py", "/Bme280Cnt.py"]} |
56,894 | Suguru36/raspizero_sensor | refs/heads/master | /Bme280Cnt.py | #!/usr/bin/env python
import smbus
from time import sleep
class Bme280Cnt(object):
_slave_addres = 0x76
Temp = []
Pres = []
Humi = []
tt = 0.0
# Initialize Sensor
def __init__(self):
self.bus = smbus.SMBus(1)
self.Tovs = 1 # Temperature oversampling x 1
self.Povs = 1 # Pressure oversampling x 1
self.Hovs = 1 # Humidity oversampling x 1
self.mode = 3 # Normal mode
self.stby = 5 # Tstandby 1000ms
self.filter = 0 # Filter off
self.spion = 0 # 3-wire SPI Disable
self.ctrl_meas_reg = (self.Tovs << 5) | (self.Povs << 2) | self.mode
self.config_reg = (self.stby << 5) | (self.filter << 2) | self.spion
self.ctrl_hum_reg = self.Hovs
self.writeI2C(0xF2, self.ctrl_hum_reg)
self.writeI2C(0xF4, self.ctrl_meas_reg)
self.writeI2C(0xF5, self.config_reg)
self.getCalibration()
self.readDataFromBme280()
# Write Sensor I2C
def writeI2C(self, reg_addr, data):
self.bus.write_byte_data(self._slave_addres, reg_addr, data)
# Get Calibration Data
def getCalibration(self):
self.calib = []
for i in range(0x88, 0x88+24):
self.calib.append(self.bus.read_byte_data(self._slave_addres, i))
self.calib.append(self.bus.read_byte_data(self._slave_addres, 0xA1))
for i in range(0xE1, 0xE1+7):
self.calib.append(self.bus.read_byte_data(self._slave_addres, i))
self.Temp.append((self.calib[1] << 8) | self.calib[0])
self.Temp.append((self.calib[3] << 8) | self.calib[2])
self.Temp.append((self.calib[5] << 8) | self.calib[4])
self.Pres.append((self.calib[7] << 8) | self.calib[6])
self.Pres.append((self.calib[9] << 8) | self.calib[8])
self.Pres.append((self.calib[11]<< 8) | self.calib[10])
self.Pres.append((self.calib[13]<< 8) | self.calib[12])
self.Pres.append((self.calib[15]<< 8) | self.calib[14])
self.Pres.append((self.calib[17]<< 8) | self.calib[16])
self.Pres.append((self.calib[19]<< 8) | self.calib[18])
self.Pres.append((self.calib[21]<< 8) | self.calib[20])
self.Pres.append((self.calib[23]<< 8) | self.calib[22])
self.Humi.append( self.calib[24] )
self.Humi.append((self.calib[26]<< 8) | self.calib[25])
self.Humi.append( self.calib[27] )
self.Humi.append((self.calib[28]<< 4) | (0x0F & self.calib[29]))
self.Humi.append((self.calib[30]<< 4) | ((self.calib[29] >> 4) & 0x0F))
self.Humi.append( self.calib[31] )
for i in range(1,2):
if self.Temp[i] & 0x8000:
self.Temp[i] = (-self.Temp[i] ^ 0xFFFF) + 1
for i in range(1,8):
if self.Pres[i] & 0x8000:
self.Pres[i] = (-self.Pres[i] ^ 0xFFFF) + 1
for i in range(0,6):
if self.Humi[i] & 0x8000:
self.Humi[i] = (-self.Humi[i] ^ 0xFFFF) + 1
# Read Now Temperature,Pressure,Humidity
def readDataFromBme280(self):
self.data = []
for i in range(0xF7, 0xF7+8):
self.data.append(self.bus.read_byte_data(self._slave_addres, i))
self.pres = (self.data[0] << 12) | (self.data[1] << 4) | (self.data[2] >> 4)
self.temp = (self.data[3] << 12) | (self.data[4] << 4) | (self.data[5] >> 4)
self.humi = (self.data[6] << 8) | self.data[7]
self.t2 = self.adjustTemp(self.temp)
self.p2 = self.adjustPres(self.pres)
self.h2 = self.adjustHumi(self.humi)
# Adjust Pressure by Calibration
def adjustPres(self, nowpres):
# global tt
self.pressure = 0.0
self.v1 = (self.tt / 2.0) - 64000.0
self.v2 = (((self.v1 / 4.0) * (self.v1 / 4.0)) / 2048) * self.Pres[5]
self.v2 = self.v2 + ((self.v1 * self.Pres[4]) * 2.0)
self.v2 = (self.v2 / 4.0) + (self.Pres[3] * 65536.0)
self.v1 = (((self.Pres[2] * (((self.v1 / 4.0) * (self.v1 / 4.0)) / 8192)) / 8) \
+ ((self.Pres[1] * self.v1) / 2.0)) / 262144
self.v1 = ((32768 + self.v1) * self.Pres[0]) / 32768
if self.v1 == 0:
return 0
self.pressure = ((1048576 - nowpres) - (self.v2 / 4096)) * 3125
if self.pressure < 0x80000000:
self.pressure = (self.pressure * 2.0) / self.v1
else:
self.pressure = (self.pressure / self.v1) * 2
self.v1 = (self.Pres[8] * (((self.pressure / 8.0) * (self.pressure / 8.0)) \
/ 8192.0)) / 4096
self.v2 = ((self.pressure / 4.0) * self.Pres[7]) / 8192.0
self.pressure = self.pressure + ((self.v1 + self.v2 + self.Pres[6]) / 16.0)
return self.pressure/100
# Adjust Temperature by Calibration
def adjustTemp(self, nowtemp):
# global tt
self.v1 = (nowtemp / 16384.0 - self.Temp[0] / 1024.0) * self.Temp[1]
self.v2 = (nowtemp / 131072.0 - self.Temp[0] / 8192.0) \
* (nowtemp / 131072.0 - self.Temp[0] / 8192.0) * self.Temp[2]
self.tt = self.v1 + self.v2
self.temperature = self.tt / 5120.0
return self.temperature
# Adjust Humidity by Calibration
def adjustHumi(self, nowhumi):
# global tt
self.var_h = self.tt - 76800.0
if self.var_h != 0:
self.var_h = (nowhumi - (self.Humi[3] * 64.0 + self.Humi[4]/16384.0 \
* self.var_h)) * (self.Humi[1] / 65536.0 * (1.0 \
+ self.Humi[5] / 67108864.0 * self.var_h * (1.0 \
+ self.Humi[2] / 67108864.0 * self.var_h)))
else:
return 0
self.var_h = self.var_h * (1.0 - self.Humi[0] * self.var_h / 524288.0)
if self.var_h > 100.0:
self.var_h = 100.0
elif self.var_h < 0.0:
self.var_h = 0.0
return self.var_h
#-----------------------------------------------
def getTempData(self):
return (self.t2)
def getPresData(self):
return (self.p2)
def getHumData(self):
return (self.h2)
#------------------------------------------------------
if __name__ == '__main__':
sens1 = Bme280Cnt()
sens1.readDataFromBme280()
print(sens1.getTempData())
print(sens1.getPresData())
print(sens1.getHumData())
| {"/EnvionmentSensorLogger.py": ["/papirus_cont.py", "/Bme280Cnt.py"]} |
56,895 | Suguru36/raspizero_sensor | refs/heads/master | /papirus_cont.py |
#!/usr/bin/env python
from papirus import PapirusTextPos
from datetime import datetime
import time
import socket
class papirus_cont(object):
def __init__(self):
self.papi = PapirusTextPos(False)
self.papi.Clear()
self.papi.AddText("DATE:", 0 ,0 ,Id="datetext")
self.papi.AddText("00-00 00:00", 60 ,0 ,Id="date-time")
self.papi.AddText("TEMP:", 0 ,20 ,Id="temptext")
self.papi.AddText("00.000", 60 ,20 ,Id="temp")
self.papi.AddText("HUME:",0,40,Id="humtext")
self.papi.AddText("00.000",60,40,Id="hum")
self.papi.AddText("PRES:",0,60,Id="presstxt")
self.papi.AddText("0000",60,60,Id="press")
self.papi.AddText("Initializing",0,80,Id="ip")
self.papi.WriteAll()
def set_new_datetime(self):
self.now_time = datetime.now()
self.papi.UpdateText("date-time",(self.now_time.strftime('%m-%d %H:%M')))
def set_temp(self, temp):
self.papi.UpdateText("temp","{0:.3f}".format(temp)+"[deg]")
def set_hum(self, hum):
self.papi.UpdateText("hum","{0:.3f}".format(hum)+"[%]")
def set_press(self, press):
self.papi.UpdateText("press","{0:.1f}".format(press)+"[hpa]")
def set_ipaddress(self):
self.ip = "0.0.0.0"
try:
#socket.AF_INET:IVv4のアドレス, socket.SOCK_DGRAM:UDPネットワークの
#IPv6の場合はAF_INET→IF_INET6
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#タイムアウトを10秒
self.s.settimeout(10)
#ipアドレス8.8.8.8:80に接続します。
# 8.8.8.8はgoogle Public DNSPCのIP。
# 外のアドレスなら何でもいいです。
self.s.connect(("8.8.8.8", 80))
#今の接続のソケット名を取得します。
self.ip=self.s.getsockname()[0]
#IPアドレス表示
#print(self.ip)
except socket.error: #ネットワークがエラーだったり無かったら
self.ip = 'No Internet'
#print('No Internet')
#print(type(self.ip))
self.papi.UpdateText("ip", self.ip)
def get_network_state(self):
return self.ip
def update(self):
self.papi.WriteAll()
#papi.Add
#papi.UpdateText("Start", "New Text")
if __name__=='__main__':
papi1 = papirus_cont()
papi1.set_new_datetime()
papi1.set_temp(12.345)
papi1.set_hum(99.999)
papi1.set_press(1234)
papi1.set_ipaddress()
papi1.update()
| {"/EnvionmentSensorLogger.py": ["/papirus_cont.py", "/Bme280Cnt.py"]} |
56,900 | Incanus3/dynamic-rest-deferred-many-relations-test | refs/heads/master | /related_ids_test/serializers.py | from dynamic_rest.serializers import DynamicModelSerializer, DynamicRelationField
from .models import Parent, Child
class ChildSerializer(DynamicModelSerializer):
class Meta:
model = Child
fields = '__all__'
class ParentSerializer(DynamicModelSerializer):
class Meta:
model = Parent
fields = '__all__'
children = DynamicRelationField(ChildSerializer, many = True, deferred = True)
| {"/related_ids_test/serializers.py": ["/related_ids_test/models.py"], "/related_ids_test/views.py": ["/related_ids_test/models.py", "/related_ids_test/serializers.py"], "/related_ids_test/urls.py": ["/related_ids_test/views.py"]} |
56,901 | Incanus3/dynamic-rest-deferred-many-relations-test | refs/heads/master | /related_ids_test/migrations/0001_initial.py | # Generated by Django 2.0.8 on 2018-11-09 15:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Child',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32)),
],
options={
'db_table': 'children',
},
),
migrations.CreateModel(
name='Parent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32)),
],
options={
'db_table': 'parents',
},
),
migrations.AddField(
model_name='child',
name='parent',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='children', to='related_ids_test.Parent'),
),
]
| {"/related_ids_test/serializers.py": ["/related_ids_test/models.py"], "/related_ids_test/views.py": ["/related_ids_test/models.py", "/related_ids_test/serializers.py"], "/related_ids_test/urls.py": ["/related_ids_test/views.py"]} |
56,902 | Incanus3/dynamic-rest-deferred-many-relations-test | refs/heads/master | /related_ids_test/models.py | from django.db.models import Model, CharField, ForeignKey, PROTECT
class Parent(Model):
class Meta:
db_table = 'parents'
name = CharField(max_length = 32)
class Child(Model):
class Meta:
db_table = 'children'
name = CharField(max_length = 32)
parent = ForeignKey(Parent, related_name = 'children', on_delete = PROTECT)
| {"/related_ids_test/serializers.py": ["/related_ids_test/models.py"], "/related_ids_test/views.py": ["/related_ids_test/models.py", "/related_ids_test/serializers.py"], "/related_ids_test/urls.py": ["/related_ids_test/views.py"]} |
56,903 | Incanus3/dynamic-rest-deferred-many-relations-test | refs/heads/master | /related_ids_test/views.py | from dynamic_rest.viewsets import DynamicModelViewSet
from .models import Parent, Child
from .serializers import ParentSerializer, ChildSerializer
class ChildViewSet(DynamicModelViewSet):
queryset = Child.objects
serializer_class = ChildSerializer
class ParentViewSet(DynamicModelViewSet):
queryset = Parent.objects
serializer_class = ParentSerializer
| {"/related_ids_test/serializers.py": ["/related_ids_test/models.py"], "/related_ids_test/views.py": ["/related_ids_test/models.py", "/related_ids_test/serializers.py"], "/related_ids_test/urls.py": ["/related_ids_test/views.py"]} |
56,904 | Incanus3/dynamic-rest-deferred-many-relations-test | refs/heads/master | /related_ids_test/urls.py | from django.conf.urls import url, include
from dynamic_rest.routers import DynamicRouter
from .views import ParentViewSet, ChildViewSet
crud_router = DynamicRouter()
crud_router.register_resource(ParentViewSet)
crud_router.register_resource(ChildViewSet)
urlpatterns = [
url(r'^crud/', include(crud_router.urls)),
]
| {"/related_ids_test/serializers.py": ["/related_ids_test/models.py"], "/related_ids_test/views.py": ["/related_ids_test/models.py", "/related_ids_test/serializers.py"], "/related_ids_test/urls.py": ["/related_ids_test/views.py"]} |
56,905 | andreslearns/andres_helper | refs/heads/master | /networkauto.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'guipy.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(841, 465)
MainWindow.setFixedSize(818, 478)
MainWindow.setWindowIcon(QtGui.QIcon('logo.ico'))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.dhcpbox = QtWidgets.QGroupBox(self.centralwidget)
self.dhcpbox.setGeometry(QtCore.QRect(20, 50, 241, 151))
self.dhcpbox.setFlat(True)
self.dhcpbox.setObjectName("dhcpbox")
self.dhcp_generatebtn = QtWidgets.QPushButton(self.dhcpbox)
self.dhcp_generatebtn.setGeometry(QtCore.QRect(80, 120, 75, 23))
self.dhcp_generatebtn.setFlat(False)
self.dhcp_generatebtn.setObjectName("dhcp_generatebtn")
self.officenametxt = QtWidgets.QLineEdit(self.dhcpbox)
self.officenametxt.setGeometry(QtCore.QRect(20, 30, 113, 20))
self.officenametxt.setObjectName("officenametxt")
self.networkaddresstxt = QtWidgets.QLineEdit(self.dhcpbox)
self.networkaddresstxt.setGeometry(QtCore.QRect(20, 60, 113, 20))
self.networkaddresstxt.setObjectName("networkaddresstxt")
self.dhcp_slider = QtWidgets.QSlider(self.dhcpbox)
self.dhcp_slider.setGeometry(QtCore.QRect(40, 90, 160, 22))
self.dhcp_slider.setMinimum(1)
self.dhcp_slider.setMaximum(31)
self.dhcp_slider.setProperty("value", 24)
self.dhcp_slider.setOrientation(QtCore.Qt.Horizontal)
self.dhcp_slider.setObjectName("dhcp_slider")
self.dhcp_spinbox = QtWidgets.QSpinBox(self.dhcpbox)
self.dhcp_spinbox.setGeometry(QtCore.QRect(160, 60, 42, 20))
self.dhcp_spinbox.setMinimum(1)
self.dhcp_spinbox.setMaximum(31)
self.dhcp_spinbox.setProperty("value", 24)
self.dhcp_spinbox.setObjectName("dhcp_spinbox")
self.label = QtWidgets.QLabel(self.dhcpbox)
self.label.setGeometry(QtCore.QRect(140, 60, 16, 16))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.output_plaintext = QtWidgets.QPlainTextEdit(self.centralwidget)
self.output_plaintext.setGeometry(QtCore.QRect(270, 50, 531, 331))
self.output_plaintext.setFrameShadow(QtWidgets.QFrame.Plain)
self.output_plaintext.setDocumentTitle("")
self.output_plaintext.setReadOnly(True)
self.output_plaintext.setBackgroundVisible(True)
self.output_plaintext.setCenterOnScroll(False)
self.output_plaintext.setObjectName("output_plaintext")
self.qosbox = QtWidgets.QGroupBox(self.centralwidget)
self.qosbox.setGeometry(QtCore.QRect(580, 540, 241, 151))
self.qosbox.setFlat(False)
self.qosbox.setObjectName("qosbox")
self.qos_generatebtn = QtWidgets.QPushButton(self.qosbox)
self.qos_generatebtn.setGeometry(QtCore.QRect(80, 110, 81, 23))
self.qos_generatebtn.setFlat(False)
self.qos_generatebtn.setObjectName("qos_generatebtn")
self.policynametxt = QtWidgets.QLineEdit(self.qosbox)
self.policynametxt.setGeometry(QtCore.QRect(30, 40, 113, 20))
self.policynametxt.setObjectName("policynametxt")
self.bw_spinbox = QtWidgets.QSpinBox(self.qosbox)
self.bw_spinbox.setGeometry(QtCore.QRect(150, 40, 42, 21))
self.bw_spinbox.setMinimum(0)
self.bw_spinbox.setMaximum(300)
self.bw_spinbox.setSingleStep(10)
self.bw_spinbox.setProperty("value", 10)
self.bw_spinbox.setDisplayIntegerBase(10)
self.bw_spinbox.setObjectName("bw_spinbox")
self.qos_slider = QtWidgets.QSlider(self.qosbox)
self.qos_slider.setGeometry(QtCore.QRect(30, 80, 160, 22))
self.qos_slider.setMinimum(0)
self.qos_slider.setMaximum(300)
self.qos_slider.setSingleStep(10)
self.qos_slider.setProperty("value", 10)
self.qos_slider.setOrientation(QtCore.Qt.Horizontal)
self.qos_slider.setObjectName("qos_slider")
self.save_btn = QtWidgets.QPushButton(self.centralwidget)
self.save_btn.setGeometry(QtCore.QRect(270, 390, 75, 23))
self.save_btn.setObjectName("save_btn")
self.ddosbox = QtWidgets.QGroupBox(self.centralwidget)
self.ddosbox.setGeometry(QtCore.QRect(310, 540, 241, 161))
self.ddosbox.setFlat(True)
self.ddosbox.setObjectName("ddosbox")
self.mitigatebtn = QtWidgets.QPushButton(self.ddosbox)
self.mitigatebtn.setGeometry(QtCore.QRect(30, 100, 171, 23))
self.mitigatebtn.setFlat(False)
self.mitigatebtn.setObjectName("mitigatebtn")
self.divert_chkbox = QtWidgets.QCheckBox(self.ddosbox)
self.divert_chkbox.setGeometry(QtCore.QRect(30, 20, 51, 17))
self.divert_chkbox.setObjectName("divert_chkbox")
self.nodivert_chkbox = QtWidgets.QCheckBox(self.ddosbox)
self.nodivert_chkbox.setGeometry(QtCore.QRect(30, 40, 70, 17))
self.nodivert_chkbox.setObjectName("nodivert_chkbox")
self.divert_all_chkbox = QtWidgets.QCheckBox(self.ddosbox)
self.divert_all_chkbox.setGeometry(QtCore.QRect(130, 20, 81, 17))
self.divert_all_chkbox.setObjectName("divert_all_chkbox")
self.no_divert_all_chkbox = QtWidgets.QCheckBox(self.ddosbox)
self.no_divert_all_chkbox.setGeometry(QtCore.QRect(130, 40, 101, 17))
self.no_divert_all_chkbox.setObjectName("no_divert_all_chkbox")
self.ddos_netaddrcombobox = QtWidgets.QComboBox(self.ddosbox)
self.ddos_netaddrcombobox.setGeometry(QtCore.QRect(30, 70, 171, 22))
self.ddos_netaddrcombobox.setObjectName("ddos_netaddrcombobox")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(20, 210, 241, 81))
self.groupBox.setObjectName("groupBox")
self.result_label = QtWidgets.QLabel(self.groupBox)
self.result_label.setGeometry(QtCore.QRect(10, 50, 221, 16))
font = QtGui.QFont()
font.setPointSize(7)
font.setBold(True)
font.setWeight(75)
self.result_label.setFont(font)
self.result_label.setText("")
self.result_label.setObjectName("result_label")
self.task_label = QtWidgets.QLabel(self.groupBox)
self.task_label.setGeometry(QtCore.QRect(10, 30, 231, 16))
font = QtGui.QFont()
font.setPointSize(7)
font.setBold(True)
font.setWeight(75)
self.task_label.setFont(font)
self.task_label.setText("")
self.task_label.setObjectName("task_label")
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(20, 300, 241, 23))
self.progressBar.setProperty("value", 0)
self.progressBar.setTextVisible(True)
self.progressBar.setTextDirection(QtWidgets.QProgressBar.TopToBottom)
self.progressBar.setObjectName("progressBar")
self.dhcp_summary_groupbox = QtWidgets.QGroupBox(self.centralwidget)
self.dhcp_summary_groupbox.setGeometry(QtCore.QRect(20, 330, 241, 81))
self.dhcp_summary_groupbox.setObjectName("dhcp_summary_groupbox")
self.total_pool_lbl = QtWidgets.QLabel(self.dhcp_summary_groupbox)
self.total_pool_lbl.setGeometry(QtCore.QRect(10, 20, 221, 16))
font = QtGui.QFont()
font.setPointSize(7)
font.setBold(True)
font.setWeight(75)
self.total_pool_lbl.setFont(font)
self.total_pool_lbl.setText("")
self.total_pool_lbl.setObjectName("total_pool_lbl")
self.network_add_lbl = QtWidgets.QLabel(self.dhcp_summary_groupbox)
self.network_add_lbl.setGeometry(QtCore.QRect(10, 40, 221, 16))
font = QtGui.QFont()
font.setPointSize(7)
font.setBold(True)
font.setWeight(75)
self.network_add_lbl.setFont(font)
self.network_add_lbl.setText("")
self.network_add_lbl.setObjectName("network_add_lbl")
self.netmask_lbl = QtWidgets.QLabel(self.dhcp_summary_groupbox)
self.netmask_lbl.setGeometry(QtCore.QRect(10, 60, 221, 16))
font = QtGui.QFont()
font.setPointSize(7)
font.setBold(True)
font.setWeight(75)
self.netmask_lbl.setFont(font)
self.netmask_lbl.setText("")
self.netmask_lbl.setObjectName("netmask_lbl")
self.optional_dhcpbox = QtWidgets.QGroupBox(self.centralwidget)
self.optional_dhcpbox.setGeometry(QtCore.QRect(30, 530, 241, 81))
self.optional_dhcpbox.setObjectName("optional_dhcpbox")
self.private_addr_cmbox = QtWidgets.QComboBox(self.optional_dhcpbox)
self.private_addr_cmbox.setGeometry(QtCore.QRect(110, 30, 121, 20))
self.private_addr_cmbox.setObjectName("private_addr_cmbox")
self.label_2 = QtWidgets.QLabel(self.optional_dhcpbox)
self.label_2.setGeometry(QtCore.QRect(10, 30, 91, 16))
self.label_2.setObjectName("label_2")
self.option_checkbox = QtWidgets.QCheckBox(self.centralwidget)
self.option_checkbox.setGeometry(QtCore.QRect(20, 30, 70, 17))
self.option_checkbox.setObjectName("option_checkbox")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 841, 21))
self.menubar.setObjectName("menubar")
self.menuConfig_Generator = QtWidgets.QMenu(self.menubar)
self.menuConfig_Generator.setObjectName("menuConfig_Generator")
self.menuNetwork_Task = QtWidgets.QMenu(self.menubar)
self.menuNetwork_Task.setObjectName("menuNetwork_Task")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionDDOS = QtWidgets.QAction(MainWindow)
self.actionDDOS.setObjectName("actionDDOS")
self.actionRoute = QtWidgets.QAction(MainWindow)
self.actionRoute.setObjectName("actionRoute")
self.actionDHCP = QtWidgets.QAction(MainWindow)
self.actionDHCP.setObjectName("actionDHCP")
self.actionQOS = QtWidgets.QAction(MainWindow)
self.actionQOS.setObjectName("actionQOS")
self.menuConfig_Generator.addAction(self.actionDDOS)
self.menuNetwork_Task.addAction(self.actionDHCP)
self.menuNetwork_Task.addAction(self.actionQOS)
self.menubar.addAction(self.menuConfig_Generator.menuAction())
self.menubar.addAction(self.menuNetwork_Task.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Andres Helper"))
self.dhcpbox.setTitle(_translate("MainWindow", "DHCP Generator"))
self.dhcp_generatebtn.setText(_translate("MainWindow", "Generate"))
self.dhcp_generatebtn.setShortcut(_translate("MainWindow", "Return"))
self.officenametxt.setPlaceholderText(_translate("MainWindow", "Pool Name"))
self.networkaddresstxt.setPlaceholderText(_translate("MainWindow", "Network Address"))
self.label.setText(_translate("MainWindow", "/"))
self.qosbox.setTitle(_translate("MainWindow", "QOS Generator"))
self.qos_generatebtn.setText(_translate("MainWindow", "Generate"))
self.qos_generatebtn.setShortcut(_translate("MainWindow", "Return"))
self.policynametxt.setPlaceholderText(_translate("MainWindow", "Policy Name"))
self.save_btn.setText(_translate("MainWindow", "Save"))
self.ddosbox.setTitle(_translate("MainWindow", "DDOS Mitigation Helper"))
self.mitigatebtn.setText(_translate("MainWindow", "Mitigate"))
self.mitigatebtn.setShortcut(_translate("MainWindow", "Return"))
self.divert_chkbox.setText(_translate("MainWindow", "Divert"))
self.nodivert_chkbox.setText(_translate("MainWindow", "No Divert"))
self.divert_all_chkbox.setText(_translate("MainWindow", "Divert All"))
self.no_divert_all_chkbox.setText(_translate("MainWindow", "Remove All"))
self.groupBox.setTitle(_translate("MainWindow", "Task Summary"))
self.dhcp_summary_groupbox.setTitle(_translate("MainWindow", "Task Summary"))
self.optional_dhcpbox.setTitle(_translate("MainWindow", "Optional"))
self.label_2.setText(_translate("MainWindow", "Private IP Address:"))
self.option_checkbox.setText(_translate("MainWindow", "Custom"))
self.menuConfig_Generator.setTitle(_translate("MainWindow", "Net Automation"))
self.menuNetwork_Task.setTitle(_translate("MainWindow", "Templates"))
self.actionDDOS.setText(_translate("MainWindow", "DDOS"))
self.actionDDOS.setShortcut(_translate("MainWindow", "Ctrl+M"))
self.actionRoute.setText(_translate("MainWindow", "Route"))
self.actionDHCP.setText(_translate("MainWindow", "DHCP"))
self.actionDHCP.setShortcut(_translate("MainWindow", "Ctrl+D"))
self.actionQOS.setText(_translate("MainWindow", "QOS"))
self.actionQOS.setShortcut(_translate("MainWindow", "Ctrl+Q"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
| {"/main.py": ["/networkauto.py"]} |
56,906 | andreslearns/andres_helper | refs/heads/master | /main.py | from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox, QFileDialog, QGraphicsBlurEffect
from PyQt5.QtCore import QTimer
from networkauto import Ui_MainWindow
from ipaddress import ip_network
from datetime import datetime
from nornir import InitNornir
from nornir.plugins.tasks.networking import netmiko_send_command, netmiko_send_config
from nornir.plugins.functions.text import print_result, print_title
from nornir.plugins.tasks.data import load_yaml
from nornir.plugins.tasks.text import template_file
import sys
import os
today = datetime.now()
save_today = today.strftime("%b-%d-%Y")
nr = InitNornir(config_file="config.yml", dry_run=True)
class MyWindow(QtWidgets.QMainWindow):
def __init__(self, mitigate):
mitigate = mitigate
super(MyWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.blur_effect = QGraphicsBlurEffect()
# MainWindow.setFixedSize(818, 478)
self.ui.ddosbox.setGeometry(QtCore.QRect(20, 50, 241, 151))
self.ui.qosbox.setGeometry(QtCore.QRect(20, 50, 241, 151))
self.ui.dhcp_summary_groupbox.setGeometry(QtCore.QRect(20, 210, 241, 81))
self.ui.optional_dhcpbox.setGeometry(QtCore.QRect(20, 300 , 241, 81))
self.ui.qosbox.hide()
self.ui.dhcpbox.hide()
self.ui.save_btn.hide()
self.ui.ddos_netaddrcombobox.hide()
self.ui.dhcp_summary_groupbox.hide()
self.ui.optional_dhcpbox.hide()
self.ui.option_checkbox.hide()
self.ui.actionQOS.triggered.connect(lambda: self.showqos())
self.ui.actionDHCP.triggered.connect(lambda: self.showdhcp())
self.ui.actionDDOS.triggered.connect(lambda: self.showddos())
# Slider change value for spinbox
self.ui.dhcp_slider.valueChanged.connect(self.changesubnet)
self.ui.qos_slider.valueChanged.connect(self.changebandwidth)
# Buttons links to functions
# dhcp
self.ui.dhcp_generatebtn.clicked.connect(self.dhcpConfig)
#qos
self.ui.qos_generatebtn.clicked.connect(self.qosConfig)
#save
self.ui.save_btn.clicked.connect(self.saveconfig)
#ddos mitigation
self.ui.divert_chkbox.toggled.connect(self.hidecheckboxes)
self.ui.nodivert_chkbox.toggled.connect(self.hidecheckboxes)
self.ui.no_divert_all_chkbox.toggled.connect(self.hidecheckboxes)
self.ui.divert_all_chkbox.toggled.connect(self.hidecheckboxes)
self.ui.mitigatebtn.hide()
#mitigate button linked to functions
self.ui.mitigatebtn.clicked.connect(lambda:nr.run(task=self.ddos_automate))
self.ui.ddos_netaddrcombobox.currentTextChanged.connect(self.hidecheckboxes)
# combobox datas
netadd_list = open("inventory/network_addr.cfg").read().splitlines()
self.ui.ddos_netaddrcombobox.addItems(netadd_list)
private_ip_lists = open("inventory/private_netaddr.cfg").read().splitlines()
self.ui.private_addr_cmbox.addItems(private_ip_lists)
self.ui.private_addr_cmbox.adjustSize()
self.ui.optional_dhcpbox.setEnabled(False)
self.ui.option_checkbox.toggled.connect(self.showoption)
self.ui.optional_dhcpbox.setGraphicsEffect(self.blur_effect)
def changesubnet(self):
subnet = self.ui.dhcp_slider.value()
self.ui.dhcp_spinbox.setValue(int(subnet))
def changebandwidth(self):
bandwidth = self.ui.qos_slider.value()
self.ui.bw_spinbox.setValue(bandwidth)
def showqos(self):
self.ui.qosbox.show()
self.ui.dhcpbox.hide()
self.ui.ddosbox.hide()
self.ui.groupBox.hide()
self.ui.save_btn.show()
self.ui.progressBar.hide()
self.ui.dhcp_summary_groupbox.hide()
self.ui.optional_dhcpbox.hide()
self.ui.option_checkbox.hide()
def showdhcp(self):
self.ui.qosbox.hide()
self.ui.ddosbox.hide()
self.ui.dhcpbox.show()
self.ui.groupBox.hide()
self.ui.save_btn.show()
self.ui.progressBar.hide()
self.ui.dhcp_summary_groupbox.show()
self.ui.optional_dhcpbox.show()
self.ui.option_checkbox.show()
def showddos(self):
self.ui.ddosbox.show()
self.ui.qosbox.hide()
self.ui.dhcpbox.hide()
self.ui.groupBox.show()
self.ui.save_btn.hide()
self.ui.progressBar.show()
self.ui.progressBar.setValue(0)
self.ui.dhcp_summary_groupbox.hide()
self.ui.optional_dhcpbox.hide()
self.ui.option_checkbox.hide()
def showoption(self):
if self.ui.option_checkbox.isChecked():
self.blur_effect.setEnabled(False)
self.ui.optional_dhcpbox.setEnabled(True)
self.ui.optional_dhcpbox.show()
else:
self.blur_effect.setEnabled(True)
def hidecheckboxes(self):
if self.ui.divert_chkbox.isChecked():
self.ui.divert_all_chkbox.setEnabled(False)
self.ui.no_divert_all_chkbox.setEnabled(False)
self.ui.nodivert_chkbox.setEnabled(False)
self.ui.ddos_netaddrcombobox.show()
self.ui.mitigatebtn.show()
self.mitigate = "divert"
self.ui.result_label.setText((f"Prefix\t:\t{self.ui.ddos_netaddrcombobox.currentText()}"))
self.ui.result_label.adjustSize()
self.ui.task_label.setText(f"Task\t:\tDIVERT")
self.ui.task_label.adjustSize()
self.ui.progressBar.setValue(0)
elif self.ui.nodivert_chkbox.isChecked():
self.ui.divert_all_chkbox.setEnabled(False)
self.ui.no_divert_all_chkbox.setEnabled(False)
self.ui.divert_chkbox.setEnabled(False)
self.ui.ddos_netaddrcombobox.show()
self.ui.mitigatebtn.show()
self.mitigate = "no_divert"
self.ui.result_label.setText((f"Prefix\t:\t{self.ui.ddos_netaddrcombobox.currentText()}"))
self.ui.result_label.adjustSize()
self.ui.task_label.setText(f"Task\t:\tNO DIVERT")
self.ui.task_label.adjustSize()
self.ui.progressBar.setValue(0)
elif self.ui.divert_all_chkbox.isChecked():
self.ui.nodivert_chkbox.setEnabled(False)
self.ui.no_divert_all_chkbox.setEnabled(False)
self.ui.divert_chkbox.setEnabled(False)
self.ui.mitigatebtn.show()
self.mitigate = "divert_all"
self.ui.result_label.setText((f"Prefix\t:\t113.61.42.0 - 58.0/24"))
self.ui.result_label.adjustSize()
self.ui.task_label.setText(f"Task\t:\tDIVERT ALL")
self.ui.task_label.adjustSize()
msg = QMessageBox()
msg.setWindowTitle("Warning!")
msg.setIcon(QMessageBox.Warning)
msg.setText(f"Warning! This may affect network stability. use with caution!")
x = msg.exec_()
self.ui.progressBar.setValue(0)
elif self.ui.no_divert_all_chkbox.isChecked():
self.ui.nodivert_chkbox.setEnabled(False)
self.ui.divert_all_chkbox.setEnabled(False)
self.ui.divert_chkbox.setEnabled(False)
self.ui.mitigatebtn.show()
self.mitigate = "no_divert_all"
self.ui.result_label.setText((f"Prefix\t:\t113.61.42 - 58.0/24"))
self.ui.result_label.adjustSize()
self.ui.task_label.setText(f"Task\t:\tNO DIVERT ALL")
self.ui.task_label.adjustSize()
msg = QMessageBox()
msg.setWindowTitle("Warning!")
msg.setIcon(QMessageBox.Warning)
msg.setText(f"Warning! This may affect network stability. use with caution!")
x = msg.exec_()
self.ui.progressBar.setValue(0)
else:
self.ui.no_divert_all_chkbox.setEnabled(True)
self.ui.nodivert_chkbox.setEnabled(True)
self.ui.divert_all_chkbox.setEnabled(True)
self.ui.divert_chkbox.setEnabled(True)
self.ui.ddos_netaddrcombobox.hide()
self.ui.mitigatebtn.hide()
def saveconfig(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
filename = QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()",f"{save_today}.txt","Text Files (*.txt)", options=options)
try:
with open(filename[0], 'w') as f:
my_config = self.ui.output_plaintext.toPlainText()
f.write(my_config)
except FileNotFoundError:
pass
def dhcpConfig(self):
self.ui.output_plaintext.clear()
try:
officename = self.ui.officenametxt.text()
officename = officename.upper()
if not officename:
raise ValueError("Empty")
netaddress = self.ui.networkaddresstxt.text()
mask = self.ui.dhcp_spinbox.value()
ipnetaddr = f"{netaddress}/{mask}"
ipnetaddr = ip_network(ipnetaddr)
netaddress = ipnetaddr[0]
first_usable = ipnetaddr[1]
last_usable = ipnetaddr[-2]
self.ui.output_plaintext.appendPlainText(f"!Generated by: Andres Bukid")
# private ip address custom
private_ip = self.ui.private_addr_cmbox.currentText()
custom_private = private_ip.split(".")
private_first_octet = custom_private[0]
private_second_octet = custom_private[1]
private_address = f"{private_first_octet}.{private_second_octet}."
usable = []
for x in ipnetaddr.hosts():
ipaddr = x
total_ip = str(ipaddr)
vlan = str(x)
vlan = vlan.split(".")
vlan = str(vlan[3])
self.ui.output_plaintext.appendPlainText(f"int g0/0/2.{vlan}")
self.ui.output_plaintext.appendPlainText(f"encapsulation dot1q {vlan}")
self.ui.output_plaintext.appendPlainText(f"ip address {private_address}{vlan}.254 255.255.255.0")
self.ui.output_plaintext.appendPlainText(f"ip nat inside\n!")
self.ui.output_plaintext.appendPlainText(f"ip dhcp pool {officename}_{vlan}")
self.ui.output_plaintext.appendPlainText(f"network {private_address}{vlan}.0 255.255.255.0")
self.ui.output_plaintext.appendPlainText(f"default-router {private_address}{vlan}.254")
self.ui.output_plaintext.appendPlainText(f"dns-server 8.8.8.8 208.67.222.222 208.67.220.220\n!")
self.ui.output_plaintext.appendPlainText(f"ip dhcp excluded-address {private_address}{vlan}.254\n!")
self.ui.output_plaintext.appendPlainText(f"ip access-list extended O{officename}_{vlan}")
self.ui.output_plaintext.appendPlainText(f"permit udp {private_address}{vlan}.0 0.0.0.255 any")
self.ui.output_plaintext.appendPlainText(f"permit tcp {private_address}{vlan}.0 0.0.0.255 any")
self.ui.output_plaintext.appendPlainText(f"permit icmp {private_address}{vlan}.0 0.0.0.255 any\n!")
self.ui.output_plaintext.appendPlainText(f"ip nat pool net{vlan} {ipaddr} {ipaddr} netmask {ipnetaddr.netmask}")
self.ui.output_plaintext.appendPlainText(f"ip nat inside source list O{officename}_{vlan} pool net{vlan} overload\n!!!!\n")
#progressbar
usable.append(total_ip)
cntlen = len(usable)
# task summary
self.ui.total_pool_lbl.setText(f"Total Pool\t: {cntlen}")
self.ui.network_add_lbl.setText(f"Network\t\t: {netaddress}")
self.ui.netmask_lbl.setText(f"Mask\t\t: {ipnetaddr.netmask}")
except ValueError:
msg = QMessageBox()
msg.setWindowTitle("DHCP Generator")
msg.setIcon(QMessageBox.Critical)
msg.setText(f"Invalid Office Name or Network Address")
x = msg.exec_()
except ValueError:
msg = QMessageBox()
msg.setWindowTitle("DHCP Generator")
msg.setIcon(QMessageBox.Critical)
msg.setText(f"Not a Valid Network Address")
x = msg.exec_()
except IndexError:
msg = QMessageBox()
msg.setWindowTitle("DHCP Generator")
msg.setIcon(QMessageBox.Critical)
msg.setText(f"Not a Valid Network Address")
x = msg.exec_()
def qosConfig(self):
try:
self.ui.output_plaintext.clear()
policy_name = self.ui.policynametxt.text()
policy_name = policy_name.upper()
if not policy_name:
raise ValueError("Empty")
bandwidth = self.ui.bw_spinbox.value()
# ROUTER
self.ui.output_plaintext.appendPlainText(f"################[ CISCO-SETUP ]################\n")
self.ui.output_plaintext.appendPlainText(f"conf t\nclass-map match-all O{policy_name}_limit")
self.ui.output_plaintext.appendPlainText(f"match any")
self.ui.output_plaintext.appendPlainText(f"exit\n!")
self.ui.output_plaintext.appendPlainText(f"policy-map {policy_name}_limit")
self.ui.output_plaintext.appendPlainText(f"police {bandwidth}000000 conform-action transmit exceed-action drop\n!")
self.ui.output_plaintext.appendPlainText(f"!!interface Config!!")
self.ui.output_plaintext.appendPlainText(f"service-policy input {policy_name}_limit")
self.ui.output_plaintext.appendPlainText(f"service-policy output {policy_name}_limit\nend\n!!!!")
# SWITCH
self.ui.output_plaintext.appendPlainText(f"\n###############[ NON-CISCO-SETUP ]##############\n")
self.ui.output_plaintext.appendPlainText(f"conf t")
self.ui.output_plaintext.appendPlainText(f"ip access-list extended O{policy_name}_ACL")
self.ui.output_plaintext.appendPlainText(f"permit ip any any\n!")
self.ui.output_plaintext.appendPlainText(f"class-map match-any O{policy_name}_class")
self.ui.output_plaintext.appendPlainText(f"match access-group name O{policy_name}_ACL\nexit\n!")
self.ui.output_plaintext.appendPlainText(f"policy-map O{policy_name}_limit")
self.ui.output_plaintext.appendPlainText(f"class O{policy_name}_class")
self.ui.output_plaintext.appendPlainText(f"police {bandwidth}000000 conform-action transmit exceed-action drop\nexit\n!")
self.ui.output_plaintext.appendPlainText(f"!!interface Config!!")
self.ui.output_plaintext.appendPlainText(f"service-policy input O{policy_name}_limit")
self.ui.output_plaintext.appendPlainText(f"service-policy output O{policy_name}_limit\nend\n!!!!")
except ValueError:
msg = QMessageBox()
msg.setWindowTitle("Policy name error")
msg.setIcon(QMessageBox.Critical)
msg.setText(f"NO Policy Name Detected, Try Again")
x = msg.exec_()
def ddos_automate(self, task):
self.ui.output_plaintext.clear()
input_ip = self.ui.ddos_netaddrcombobox.currentText()
net = ip_network(input_ip)
mitigate = self.mitigate
# Will send the commands in the routers via netmiko_send_command,[hosts]
acl_template = task.run(task=template_file,name="Buildling ACL Configuration",
net=net,
mitigate=mitigate,
template="divert.j2",
path=f"templates/{task.host}")
task.host["acl"] = acl_template.result
acl_output = task.host["acl"]
acl_send = acl_output.splitlines()
send_command = task.run(task=netmiko_send_config, name="Pushing ACL Commands", config_commands=acl_send)
self.ui.output_plaintext.appendPlainText(f"#############{task.host}#############\n")
self.ui.output_plaintext.appendPlainText(acl_output)
# print_result(send_command)
# num_host = len(task.host)
self.ui.progressBar.setValue(self.ui.progressBar.value() + 50)
def main() -> None:
app = QtWidgets.QApplication(sys.argv)
w = MyWindow(mitigate="")
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
palette = QtGui.QPalette()
palette.setColor(QtGui.QPalette.Window, QtGui.QColor(53,53,53))
palette.setColor(QtGui.QPalette.WindowText, QtCore.Qt.white)
palette.setColor(QtGui.QPalette.Base, QtGui.QColor(15,15,15))
palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(53,53,53))
palette.setColor(QtGui.QPalette.ToolTipBase, QtCore.Qt.white)
palette.setColor(QtGui.QPalette.ToolTipText, QtCore.Qt.white)
palette.setColor(QtGui.QPalette.Text, QtCore.Qt.white)
palette.setColor(QtGui.QPalette.Button, QtGui.QColor(53,53,53))
palette.setColor(QtGui.QPalette.ButtonText, QtCore.Qt.white)
palette.setColor(QtGui.QPalette.BrightText, QtCore.Qt.red)
palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(142,45,197).lighter())
palette.setColor(QtGui.QPalette.HighlightedText, QtCore.Qt.black)
app.setPalette(palette)
main() | {"/main.py": ["/networkauto.py"]} |
56,907 | andreslearns/andres_helper | refs/heads/master | /hook-nornir.py | from PyInstaller.utils.hooks import copy_metadata, collect_data_files
datas = copy_metadata('nornir')
datas += collect_data_files('nornir') | {"/main.py": ["/networkauto.py"]} |
56,963 | stasyao/bakecake | refs/heads/master | /users/migrations/0003_auto_20211029_1603.py | # Generated by Django 3.2.8 on 2021-10-29 13:03
import django.contrib.auth.models
from django.db import migrations, models
import users.models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_customuser_agreement'),
]
operations = [
migrations.CreateModel(
name='UsersCount',
fields=[
],
options={
'verbose_name': 'Статистика по пользователям',
'verbose_name_plural': 'Статистика по пользователям',
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('users.customuser',),
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.RemoveField(
model_name='customuser',
name='firstname',
),
migrations.RemoveField(
model_name='customuser',
name='lastname',
),
migrations.AlterField(
model_name='customuser',
name='agreement',
field=models.BooleanField(default=True, validators=[users.models.validate_agreement], verbose_name='Согласие на обработку персональных даных'),
),
migrations.AlterField(
model_name='customuser',
name='first_name',
field=models.CharField(max_length=50, verbose_name='Имя'),
),
migrations.AlterField(
model_name='customuser',
name='last_name',
field=models.CharField(max_length=50, verbose_name='Фамилия'),
),
]
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,964 | stasyao/bakecake | refs/heads/master | /users/views.py | from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from shop.models import Order
from .forms import CancellationOrderForm, CustomUserCreationForm
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
@login_required
def show_orders(request):
return render(request=request, template_name='user.html', context={'user': request.user})
@login_required
def cancel_order(request, order_id):
order = get_object_or_404(Order, pk=order_id)
if request.method == 'POST':
form = CancellationOrderForm(request.POST)
if form.is_valid():
canceled_order = form.save(commit=False)
canceled_order.order = order
canceled_order.save()
order.status = 5
order.save()
return redirect(reverse_lazy('account'))
form = CancellationOrderForm()
return render(request, 'cancellation.html', {'form': form})
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,965 | stasyao/bakecake | refs/heads/master | /bakecake_statistics/migrations/0001_initial.py | # Generated by Django 3.2.8 on 2021-11-02 19:31
from django.db import migrations
class Migration(migrations.Migration):
initial = True
dependencies = [
('shop', '0003_auto_20211102_2034'),
]
operations = [
migrations.CreateModel(
name='OrderStatistics',
fields=[
],
options={
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('shop.order',),
),
]
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,966 | stasyao/bakecake | refs/heads/master | /shop/forms.py | import datetime
from django import forms
from django.forms.widgets import (
CheckboxSelectMultiple, RadioSelect, TextInput, Textarea
)
from shop.models import Cake, Order, Topping, CakeLevel, CakeForm
class CakeConstructorForm(forms.ModelForm):
def __init__(self, **kwargs):
kwargs['initial'] = {
'level': CakeLevel.objects.first(),
'form': CakeForm.objects.first(),
'topping': Topping.objects.first()
}
super().__init__(**kwargs)
for field in self.fields.values():
field.required = False
class Meta:
model = Cake
fields = '__all__'
help_texts = {
'caption_on_cake': ('Можно сделать надпись, например '
'"С днем рождения!". '
'Но, пожалуйста, уложитесь в 45 символов.')
}
widgets = {
'level': RadioSelect(),
'form': RadioSelect(),
'topping': RadioSelect(),
'berry': CheckboxSelectMultiple(),
'decor': CheckboxSelectMultiple(),
'caption_on_cake': TextInput(
attrs={'class': "form-control border border-secondary"}
)
}
def initial_datetime():
initial = datetime.datetime.today() + datetime.timedelta(hours=5)
initial = initial.strftime("%Y-%m-%dT%H:%M")
return initial
class OrderDetailsForm(forms.ModelForm):
class Meta:
model = Order
fields = ['destination', 'comment', 'delivery_time']
labels = {
'destination': 'Куда привезти',
'delivery_time': 'Когда'
}
help_texts = {
'delivery_time': 'Минимальное время доставки 5 часов.'
}
widgets = {
'destination': TextInput(attrs={'class': 'form-control'}),
'comment': Textarea(attrs={
'rows': 3,
'class': ('form-control-sm col-12 mt-0 pt-0 mb-3 border'
' border-2')}
),
'delivery_time': TextInput(
attrs={
'class': 'form-control-sm border border-2',
'type': 'datetime-local',
'min': initial_datetime()
}
)
}
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,967 | stasyao/bakecake | refs/heads/master | /shop/urls.py | from django.urls import path
from . import views
# app_name = 'shop'
urlpatterns = [
path('', views.show_main_page, name='home'),
path('cake', views.make_cake_page, name='make_cake_page'),
path('order_details', views.order_details, name='order_details'),
path('make_order', views.make_order, name='make_order'),
path('get_code', views.get_and_check_promo_code,
name='get_and_check_promo_code'),
]
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,968 | stasyao/bakecake | refs/heads/master | /shop/admin.py | import csv
from django.contrib import admin
from django.contrib.admin import sites
from django.contrib.auth import get_user_model
from django.http.response import HttpResponse
from django.urls import path
from .models import (Berry, Cake, CakeForm, CakeLevel, CancellationOrder,
Decor, Order, PromoCode, Topping)
from bakecake_statistics.models import OrderStatistics
from bakecake_statistics.stat_utils import get_statistics
User = get_user_model()
class BakeCakeAdminSite(admin.AdminSite):
def get_app_list(self, request):
app_list = super().get_app_list(request)
try:
reordered_app_list = [
app_list[2],
app_list[0],
app_list[1]
]
except IndexError:
return app_list
return reordered_app_list
def get_urls(self):
urls = super().get_urls()
my_urls = [
path('stat_in_csv/', self.export_as_csv, name='stat_in_csv')
]
return my_urls + urls
def export_as_csv(self, request):
statistics = get_statistics()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=BC_stat.csv'
writer = csv.writer(response)
for stat_obj in statistics:
if None in statistics[stat_obj]:
del statistics[stat_obj][None]
elif 'Без топпинга' in statistics[stat_obj]:
del statistics[stat_obj]['Без топпинга']
else:
writer.writerows(statistics[stat_obj].items())
writer.writerow([' '])
return response
bake_cake_site = BakeCakeAdminSite()
admin.site = bake_cake_site
sites.site = bake_cake_site
admin.site.index_title = 'Управление магазином BakeCake'
@admin.register(OrderStatistics)
class BakeCakeStatAdmin(admin.ModelAdmin):
change_list_template = 'admin/bakecake_statistics.html'
def get_model_perms(self, request):
return {'view': True}
def changelist_view(self, request, extra_context=None):
response = super().changelist_view(
request,
extra_context=extra_context,
)
response.context_data['summary'] = get_statistics()
return response
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ['client', 'cake', 'destination', 'delivery_time', 'total_price']
list_display_links = ['cake']
admin.site.register([CakeLevel,
CakeForm,
Topping,
Berry,
Decor,
Cake,
CancellationOrder,
PromoCode,
User])
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,969 | stasyao/bakecake | refs/heads/master | /users/forms.py | from django import forms
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.forms.widgets import TextInput, Textarea
from shop.models import CancellationOrder
from .models import CustomUser
class CancellationOrderForm(forms.ModelForm):
class Meta:
model = CancellationOrder
fields = ('comment',)
widgets = {
'comment': Textarea(
attrs={
"rows": 3,
"class": "form-control-sm col-12 mt-0 pt-0 mb-3 border border-2",
"placeholder": "Вы можете оставить любой комментарий. Это не обязательно."
}
)
}
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = UserCreationForm.Meta.fields + (
'first_name',
'last_name',
'phonenumber',
'social_network',
'address',
'agreement',
)
widgets = {
'username': TextInput(attrs={"class": "form-control"}),
'first_name': TextInput(attrs={"class": "form-control"}),
'last_name': TextInput(attrs={"class": "form-control"}),
'social_network': TextInput(attrs={"class": "form-control"}),
'address': TextInput(attrs={"class": "form-control"}),
'phonenumber': TextInput(attrs={"class": "form-control"}),
'password1': forms.PasswordInput(attrs={'autocomplete': 'new-password', 'class': 'form-control'}),
'password2': forms.PasswordInput(attrs={'autocomplete': 'new-password', 'class': 'form-control'}),
}
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserChangeForm.Meta.fields
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,970 | stasyao/bakecake | refs/heads/master | /users/admin.py | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserChangeForm, CustomUserCreationForm
from .models import CustomUser, UsersCount
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['username', 'first_name', 'last_name']
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('phonenumber', 'address', 'social_network')}),
)
@admin.register(UsersCount)
class UsersCountAdmin(admin.ModelAdmin):
change_list_template = 'admin/users_count_change_list.html'
def changelist_view(self, request, extra_context=None):
response = super().changelist_view(
request,
extra_context=extra_context,
)
try:
users = response.context_data['cl'].queryset.filter(is_staff=False)
except (AttributeError, KeyError):
return response
response.context_data['amount'] = len(users)
return response
admin.site.register(CustomUser, CustomUserAdmin)
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,971 | stasyao/bakecake | refs/heads/master | /shop/migrations/0003_auto_20211102_2034.py | # Generated by Django 3.2.8 on 2021-11-02 17:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0002_auto_20211029_1603'),
]
operations = [
migrations.CreateModel(
name='CancellationOrderSummary',
fields=[
],
options={
'verbose_name': 'Статистика отмененных заказов',
'verbose_name_plural': 'Статистика отмененных заказов',
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('shop.cancellationorder',),
),
migrations.CreateModel(
name='OrderSummary',
fields=[
],
options={
'verbose_name': 'Статистика по статусам заказов',
'verbose_name_plural': 'Статистика по статусам заказов',
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('shop.order',),
),
migrations.AlterModelOptions(
name='berry',
options={'ordering': ('price',), 'verbose_name_plural': 'Ягоды'},
),
migrations.AlterModelOptions(
name='cake',
options={'verbose_name_plural': 'Торты'},
),
migrations.AlterModelOptions(
name='cakeform',
options={'ordering': ('price',), 'verbose_name_plural': 'Формы тортов'},
),
migrations.AlterModelOptions(
name='cakelevel',
options={'ordering': ('price',), 'verbose_name_plural': 'Уровни тортов'},
),
migrations.AlterModelOptions(
name='cancellationorder',
options={'verbose_name_plural': 'Отмены заказов'},
),
migrations.AlterModelOptions(
name='decor',
options={'ordering': ('price',), 'verbose_name_plural': 'Декоры'},
),
migrations.AlterModelOptions(
name='order',
options={'verbose_name_plural': 'Заказы'},
),
migrations.AlterModelOptions(
name='promocode',
options={'verbose_name_plural': 'Промокоды'},
),
migrations.AlterModelOptions(
name='topping',
options={'ordering': ('price',), 'verbose_name_plural': 'Топпинги'},
),
migrations.AlterField(
model_name='cake',
name='caption_on_cake',
field=models.CharField(blank=True, max_length=45, verbose_name='надпись на торте'),
),
]
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,972 | stasyao/bakecake | refs/heads/master | /bakecake_statistics/models.py | from django.db import models
from shop.models import Order
class OrderStatistics(Order):
class Meta:
proxy = True
verbose_name_plural = 'статистика по магазину'
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,973 | stasyao/bakecake | refs/heads/master | /bakecake_statistics/stat_utils.py | import collections
from django.contrib.auth import get_user_model
from django.db.models import Count
from shop.models import Cake, Order
User = get_user_model()
def get_statistics():
statistics = {
'orders': {'Всего заказов': Order.objects.count()},
'statuses': dict(collections.Counter(
order.get_status_display() for order in Order.objects.only('status')
)
),
'clients': {'Всего клиентов': User.objects.filter(is_staff=False).count()},
'topping': dict(
Cake.objects.values_list('topping__name').annotate(total=Count('id'))
),
'berry': dict(
Cake.objects.values_list('berry__name').annotate(total=Count('id'))
),
'decor': dict(
Cake.objects.values_list('decor__name').annotate(total=Count('id'))
)
}
return statistics
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,974 | stasyao/bakecake | refs/heads/master | /shop/migrations/0002_auto_20211029_1603.py | # Generated by Django 3.2.8 on 2021-10-29 13:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('shop', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='PromoCode',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('code', models.CharField(max_length=10, unique=True, verbose_name='промокод')),
],
),
migrations.AlterModelOptions(
name='berry',
options={'ordering': ('price',)},
),
migrations.AlterModelOptions(
name='cakeform',
options={'ordering': ('price',)},
),
migrations.AlterModelOptions(
name='cakelevel',
options={'ordering': ('price',)},
),
migrations.AlterModelOptions(
name='decor',
options={'ordering': ('price',)},
),
migrations.AlterModelOptions(
name='topping',
options={'ordering': ('price',)},
),
migrations.RemoveField(
model_name='cakelevel',
name='level',
),
migrations.AddField(
model_name='cake',
name='form',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='shop.cakeform', verbose_name='форма торта'),
),
migrations.AddField(
model_name='cakelevel',
name='level_num',
field=models.PositiveSmallIntegerField(default=1, verbose_name='число уровней торта'),
),
migrations.AddField(
model_name='order',
name='total_price',
field=models.PositiveSmallIntegerField(db_index=True, default=1, verbose_name='цена заказа'),
preserve_default=False,
),
migrations.AlterField(
model_name='berry',
name='name',
field=models.CharField(max_length=100, unique=True, verbose_name='название'),
),
migrations.AlterField(
model_name='berry',
name='price',
field=models.PositiveSmallIntegerField(verbose_name='цена'),
),
migrations.AlterField(
model_name='cake',
name='level',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='shop.cakelevel', verbose_name='число уровней'),
),
migrations.RemoveField(
model_name='cake',
name='topping',
),
migrations.AddField(
model_name='cake',
name='topping',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='shop.topping', verbose_name='топпинги'),
),
migrations.AlterField(
model_name='cakeform',
name='price',
field=models.PositiveSmallIntegerField(verbose_name='цена'),
),
migrations.AlterField(
model_name='cakeform',
name='type',
field=models.CharField(max_length=100, unique=True, verbose_name='тип'),
),
migrations.AlterField(
model_name='cakelevel',
name='price',
field=models.PositiveSmallIntegerField(verbose_name='цена'),
),
migrations.AlterField(
model_name='decor',
name='name',
field=models.CharField(max_length=100, unique=True, verbose_name='название'),
),
migrations.AlterField(
model_name='decor',
name='price',
field=models.PositiveSmallIntegerField(verbose_name='цена'),
),
migrations.AlterField(
model_name='order',
name='cake',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='shop.cake', verbose_name='торт'),
),
migrations.AlterField(
model_name='order',
name='client',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='orders', to=settings.AUTH_USER_MODEL, verbose_name='клиент'),
),
migrations.AlterField(
model_name='topping',
name='name',
field=models.CharField(max_length=100, unique=True, verbose_name='название'),
),
migrations.AlterField(
model_name='topping',
name='price',
field=models.PositiveSmallIntegerField(verbose_name='цена'),
),
migrations.AddField(
model_name='order',
name='promo_code',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='orders', to='shop.promocode', verbose_name='промокод'),
),
]
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,975 | stasyao/bakecake | refs/heads/master | /shop/models.py | from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class CakeLevel(models.Model):
level_num = models.PositiveSmallIntegerField(
verbose_name='число уровней торта',
default=1
)
price = models.PositiveSmallIntegerField(
verbose_name='цена'
)
class Meta:
verbose_name_plural = 'Уровни тортов'
ordering = ('price', )
def __str__(self):
return str(self.level_num)
class CakeForm(models.Model):
type = models.CharField(max_length=100,
unique=True,
verbose_name='тип')
price = models.PositiveSmallIntegerField(
verbose_name='цена'
)
class Meta:
verbose_name_plural = 'Формы тортов'
ordering = ('price', )
def __str__(self):
return self.type
class Topping(models.Model):
name = models.CharField(max_length=100,
unique=True,
verbose_name='название')
price = models.PositiveSmallIntegerField(verbose_name='цена')
class Meta:
verbose_name_plural = 'Топпинги'
ordering = ('price', )
def __str__(self):
return self.name
class Berry(models.Model):
name = models.CharField(max_length=100,
unique=True,
verbose_name='название')
price = models.PositiveSmallIntegerField(verbose_name='цена')
class Meta:
verbose_name_plural = 'Ягоды'
ordering = ('price', )
def __str__(self):
return self.name
class Decor(models.Model):
name = models.CharField(max_length=100,
unique=True,
verbose_name='название')
price = models.PositiveSmallIntegerField(
verbose_name='цена'
)
class Meta:
verbose_name_plural = 'Декоры'
ordering = ('price', )
def __str__(self):
return self.name
class Cake(models.Model):
level = models.ForeignKey(to=CakeLevel,
on_delete=models.SET_NULL,
null=True,
verbose_name='число уровней')
form = models.ForeignKey(to=CakeForm,
on_delete=models.SET_NULL,
null=True,
verbose_name='форма торта')
topping = models.ForeignKey(to=Topping,
on_delete=models.SET_NULL,
null=True,
verbose_name='топпинги')
berry = models.ManyToManyField(to=Berry,
verbose_name='ягоды')
decor = models.ManyToManyField(to=Decor,
verbose_name='декор')
caption_on_cake = models.CharField(blank=True,
max_length=45,
verbose_name='надпись на торте')
class Meta:
verbose_name_plural = 'Торты'
def __str__(self):
return f'Уровней: {self.level} | Форма: {self.form} | Топпинг: {self.topping}'
class PromoCode(models.Model):
code = models.CharField(max_length=10,
unique=True,
verbose_name='промокод')
class Meta:
verbose_name_plural = 'Промокоды'
def __str__(self):
return self.code
class Order(models.Model):
class OrderStatus(models.IntegerChoices):
IS_PROCESSING = 1, 'Заявка обрабатывается'
IS_PREPARING = 2, 'Торт готовится'
ON_THE_WAY = 3, 'Торт в пути'
DELIVERED = 4, 'Торт доставлен'
CANCELLED = 5, 'Заказ отменен'
status = models.PositiveSmallIntegerField(
db_index=True,
choices=OrderStatus.choices,
default=OrderStatus.IS_PROCESSING,
verbose_name='статус заказа')
total_price = models.PositiveSmallIntegerField(db_index=True,
verbose_name='цена заказа')
client = models.ForeignKey(to=User,
on_delete=models.SET_NULL,
null=True,
verbose_name='клиент',
related_name='orders')
cake = models.OneToOneField(to=Cake,
on_delete=models.SET_NULL,
null=True,
verbose_name='торт')
comment = models.TextField(blank=True,
verbose_name='комментарий к заказу')
destination = models.CharField(max_length=200)
delivery_time = models.DateTimeField()
promo_code = models.ForeignKey(to=PromoCode,
on_delete=models.SET_NULL,
blank=True,
null=True,
related_name='orders',
verbose_name='промокод')
class Meta:
verbose_name_plural = 'Заказы'
def __str__(self):
return (f'Заказ {self.client.username}'
'на {self.delivery_time.strftime("%d-%m-%Y %H:%M")}, '
'сумма {self.total_price}')
class CancellationOrder(models.Model):
order = models.OneToOneField(to=Order,
on_delete=models.CASCADE,
verbose_name='отмененный заказ')
comment = models.TextField(blank=True,
verbose_name='комментарий пользователя')
class Meta:
verbose_name_plural = 'Отмены заказов'
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,976 | stasyao/bakecake | refs/heads/master | /users/urls.py | from django.urls import path
from .views import SignUpView, show_orders, cancel_order
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
path('account/', show_orders, name='account'),
path('cancel/<int:order_id>', cancel_order, name='cancel'),
]
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,977 | stasyao/bakecake | refs/heads/master | /shop/migrations/0001_initial.py | # Generated by Django 3.2.8 on 2021-10-26 11:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import shop.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Berry',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('price', models.PositiveSmallIntegerField()),
],
),
migrations.CreateModel(
name='Cake',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('caption_on_cake', models.CharField(blank=True, max_length=200, verbose_name='надпись на торте')),
('berry', models.ManyToManyField(to='shop.Berry', verbose_name='ягоды')),
],
),
migrations.CreateModel(
name='CakeForm',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.CharField(max_length=100)),
('price', models.PositiveSmallIntegerField()),
],
),
migrations.CreateModel(
name='CakeLevel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('level', models.PositiveSmallIntegerField()),
('price', models.PositiveSmallIntegerField()),
],
),
migrations.CreateModel(
name='Decor',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('price', models.PositiveSmallIntegerField()),
],
),
migrations.CreateModel(
name='Topping',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('price', models.PositiveSmallIntegerField()),
],
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.PositiveSmallIntegerField(choices=[(1, 'Заявка обрабатывается'), (2, 'Торт готовится'), (3, 'Торт в пути'), (4, 'Торт доставлен'), (5, 'Заказ отменен')], db_index=True, default=1, verbose_name='статус заказа')),
('comment', models.TextField(blank=True, verbose_name='комментарий к заказу')),
('destination', models.CharField(max_length=200)),
('delivery_time', models.DateTimeField()),
('cake', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='shop.cake', verbose_name='торт')),
('client', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='клиент')),
],
),
migrations.CreateModel(
name='CancellationOrder',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('comment', models.TextField(blank=True, verbose_name='комментарий пользователя')),
('order', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='shop.order', verbose_name='отмененный заказ')),
],
),
migrations.AddField(
model_name='cake',
name='decor',
field=models.ManyToManyField(to='shop.Decor', verbose_name='декор'),
),
migrations.AddField(
model_name='cake',
name='level',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='shop.cakelevel', verbose_name='уровень'),
),
migrations.AddField(
model_name='cake',
name='topping',
field=models.ManyToManyField(to='shop.Topping', verbose_name='топпинги'),
),
]
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,978 | stasyao/bakecake | refs/heads/master | /shop/views.py | from django.contrib.auth.decorators import login_required
from django import urls
from django.http import JsonResponse
from django.shortcuts import redirect, render
from shop.models import PromoCode
from .forms import CakeConstructorForm, OrderDetailsForm
def show_main_page(request):
return render(request, 'super_main.html')
@login_required
def make_cake_page(request):
form = CakeConstructorForm()
context = {'form': form}
return render(
request,
'cake_constructor.html',
context=context
)
@login_required
def order_details(request):
if request.method == 'GET':
return redirect(urls.reverse('make_cake_page'))
cake_form = CakeConstructorForm(data=request.POST)
cake_form.is_valid()
prices = []
for obj in cake_form.cleaned_data.values():
try:
prices.extend(obj.values_list('price', flat=True))
except AttributeError:
# если объект не кверисет, а объект конкретной записи
try:
prices.append(obj.price)
# если у объекта конкретной записи нет атрибута "цена"
except AttributeError:
pass
total_price = sum(prices)
order_form = OrderDetailsForm(
initial={'price': total_price, 'destination': request.user.address}
)
return render(
request,
'order_details.html',
{'order_form': order_form, 'cake_form': cake_form, 'price': total_price}
)
@login_required
def make_order(request):
if request.method == 'GET':
return redirect(urls.reverse('make_cake_page'))
order_form = OrderDetailsForm(data=request.POST)
order_form.is_valid()
# создаём запись о заказанном торте
cake_form = CakeConstructorForm(data=request.POST)
cake_form.is_valid()
new_cake = cake_form.save(commit=False)
new_cake.save()
cake_form.save_m2m()
# берем итоговую цену заказа (генерируется на фронте,см.`static/promo.js`)
total_price = request.POST.get('cake_price')
# берем при наличии промокод (проверяется на фронте,см.`static/promo.js`)
if request.POST.get('promo_code'):
promo_code = PromoCode.objects.get(code=request.POST.get('promo_code'))
else:
promo_code = None
# создаём запись о заказе
new_order = order_form.save(commit=False)
new_order.client = request.user
new_order.promo_code = promo_code
new_order.total_price = total_price
new_order.cake = new_cake
new_order.save()
return redirect(urls.reverse('account'))
def get_and_check_promo_code(request):
actualPromoCode = PromoCode.objects.last()
if not actualPromoCode:
return JsonResponse(
{'actualCode': None, 'thisClientUsed': False}
)
code_is_used = request.user.orders.filter(
promo_code__code=actualPromoCode
).exists()
return JsonResponse(
{'actualCode': actualPromoCode.code, 'thisClientUsed': code_is_used}
)
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,979 | stasyao/bakecake | refs/heads/master | /users/models.py | from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
def validate_agreement(value):
if not value:
raise ValidationError(
'Для регистрации необходимо согласиться на обработку персональных данных.'
)
class CustomUser(AbstractUser):
first_name = models.CharField(
verbose_name='Имя',
max_length=50
)
last_name = models.CharField(
verbose_name='Фамилия',
max_length=50
)
phonenumber = PhoneNumberField(
verbose_name='Телефон',
)
social_network = models.CharField(
'Ссылка на соцсеть',
max_length=100,
blank=True,
)
address = models.CharField(
'Адрес',
max_length=200,
)
agreement = models.BooleanField(
'Согласие на обработку персональных даных',
validators=[validate_agreement],
default=True
)
class Meta:
verbose_name = 'Пользователь'
verbose_name_plural = 'Пользователи'
def __str__(self):
return f'{self.username} {self.first_name} {self.last_name}'
class UsersCount(CustomUser):
class Meta:
proxy = True
verbose_name = 'Статистика по пользователям'
verbose_name_plural = 'Статистика по пользователям'
| {"/users/migrations/0003_auto_20211029_1603.py": ["/users/models.py"], "/users/views.py": ["/shop/models.py", "/users/forms.py"], "/shop/forms.py": ["/shop/models.py"], "/shop/admin.py": ["/shop/models.py", "/bakecake_statistics/models.py", "/bakecake_statistics/stat_utils.py"], "/users/forms.py": ["/shop/models.py", "/users/models.py"], "/users/admin.py": ["/users/forms.py", "/users/models.py"], "/bakecake_statistics/models.py": ["/shop/models.py"], "/bakecake_statistics/stat_utils.py": ["/shop/models.py"], "/users/urls.py": ["/users/views.py"], "/shop/migrations/0001_initial.py": ["/shop/models.py"], "/shop/views.py": ["/shop/models.py", "/shop/forms.py"]} |
56,992 | meoke/pangtreevis | refs/heads/master | /dash_app/components/pangtreebuild.py | import os
from io import StringIO
from typing import Union, Optional
import dash_html_components as html
from pangtreebuild.consensus import simple_tree_generator, tree_generator
from pangtreebuild.consensus.cutoffs import MAX2, NODE3
from pangtreebuild.datamodel.DataType import DataType
from pangtreebuild.datamodel.Poagraph import Poagraph
from pangtreebuild.datamodel.fasta_providers.ConstSymbolProvider import ConstSymbolProvider
from pangtreebuild.datamodel.fasta_providers.FromNCBI import FromNCBI
from pangtreebuild.output.PangenomeFASTA import poagraph_to_fasta, consensuses_tree_to_fasta
from pangtreebuild.output.PangenomeJSON import to_PangenomeJSON, to_json, PangenomeJSON, TaskParameters
from pangtreebuild.output.PangenomePO import poagraph_to_PangenomePO
from pangtreebuild.tools import logprocess
from dash_app.components import tools
import time
from pathlib import Path
from pangtreebuild.consensus.input_types import Blosum, ConsensusInputError, Hbmin, Stop, P
from pangtreebuild.datamodel.fasta_providers.FastaProvider import FastaProviderException
from pangtreebuild.datamodel.fasta_providers.FromFile import FromFile
from pangtreebuild.datamodel.input_types import Maf, InputError, Po, MissingSymbol, MetadataCSV
def multialignment_file_is_valid(multialignment_content: str, filename: str) -> str:
if "maf" in filename:
try:
m = Maf(StringIO(multialignment_content), filename=filename)
except InputError as e:
return str(e)
elif "po" in filename:
try:
m = Po(StringIO(multialignment_content), filename=filename)
except InputError as e:
return str(e)
else:
return "Only po and maf file are accepted. The extension must be present in filename."
return ""
def fasta_file_is_valid(fasta_path: Path) -> str:
try:
_ = FromFile(fasta_path)
except FastaProviderException as e:
return str(e)
return ""
def blosum_file_is_valid(file_content: Path, missing_symbol: str) -> str:
try:
blosum = Blosum(file_content, None)
if missing_symbol != None:
blosum.check_if_symbol_is_present(missing_symbol)
except ConsensusInputError as e:
return str(e)
return ""
def metadata_file_is_valid(file_content: str, file_path: Path) -> str:
try:
_ = MetadataCSV(StringIO(file_content), file_path)
except InputError as e:
return str(e)
return ""
def get_default_blosum_path():
parent_dir = Path(os.path.dirname(os.path.abspath(__file__)) + '/')
return tools.get_child_path(parent_dir, "../dependencies/blosum80.mat")
def run_pangtreebuild(output_dir: Path,
datatype: DataType,
multialignment: Union[Maf, Po],
fasta_provider: Union[FromFile, FromNCBI, ConstSymbolProvider],
blosum: Blosum,
consensus_choice: str,
output_po: bool,
output_fasta: bool,
missing_symbol: MissingSymbol,
metadata: Optional[MetadataCSV]=None,
hbmin: Optional[Hbmin] = None,
stop: Optional[Stop] = None,
p: Optional[P] = None,
fasta_path: Optional[Path] = None
) -> PangenomeJSON:
start = time.time()
logprocess.add_file_handler_to_logger(output_dir, "details", "details.log", propagate=False)
logprocess.add_file_handler_to_logger(output_dir, "", "details.log", propagate=False)
logprocess.remove_console_handler_from_root_logger()
poagraph, dagmaf = None, None
if isinstance(multialignment, Maf):
poagraph, dagmaf = Poagraph.build_from_dagmaf(multialignment, fasta_provider, metadata)
elif isinstance(multialignment, Po):
poagraph = Poagraph.build_from_po(multialignment, metadata)
consensus_output_dir = tools.get_child_dir(output_dir, "consensus")
consensus_tree = None
if consensus_choice == 'poa':
consensus_tree = simple_tree_generator.get_simple_consensus_tree(poagraph,
blosum,
consensus_output_dir,
hbmin,
True)
elif consensus_choice == 'tree':
consensus_tree = tree_generator.get_consensus_tree(poagraph,
blosum,
consensus_output_dir,
stop,
p,
MAX2(),
NODE3(),
True)
if output_po:
pangenome_po = poagraph_to_PangenomePO(poagraph)
tools.save_to_file(pangenome_po, tools.get_child_path(output_dir, "poagraph.po"))
if output_fasta:
sequences_fasta = poagraph_to_fasta(poagraph)
tools.save_to_file(sequences_fasta, tools.get_child_path(output_dir, "sequences.fasta"))
if consensus_tree:
consensuses_fasta = consensuses_tree_to_fasta(poagraph, consensus_tree)
tools.save_to_file(consensuses_fasta, tools.get_child_path(output_dir, "consensuses.fasta"))
end = time.time()
task_parameters = TaskParameters(running_time=f"{end - start}s",
multialignment_file_path=multialignment.filename,
multialignment_format=str(type(multialignment).__name__),
datatype=datatype.name,
metadata_file_path=metadata.filename if metadata else None,
blosum_file_path=blosum.filepath.name,
output_path=None,
output_po=output_po,
output_fasta=output_fasta,
output_with_nodes=True,
verbose=True,
raw_maf=False,
fasta_provider=str(type(fasta_provider).__name__),
missing_base_symbol=missing_symbol.value,
fasta_source_file=fasta_path,
consensus_type=consensus_choice,
hbmin=hbmin.value if hbmin else None,
max_cutoff_option="MAX2",
search_range=None,
node_cutoff_option="NODE3",
multiplier=None,
stop=stop.value if stop else None,
p=p.value if p else None)
pangenomejson = to_PangenomeJSON(task_parameters=task_parameters,
poagraph=poagraph,
dagmaf=dagmaf,
consensuses_tree=consensus_tree)
pangenome_json_str = to_json(pangenomejson)
tools.save_to_file(pangenome_json_str, tools.get_child_path(output_dir, "pangenome.json"))
return pangenomejson
| {"/dash_app/callbacks/visualisation.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py"], "/dash_app/layout/pages.py": ["/dash_app/layout/layout_ids.py"], "/run.py": ["/dash_app/app.py"], "/dash_app/callbacks/consensustree.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/app.py": ["/dash_app/server.py"], "/dash_app/callbacks/consensustable.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/callbacks/mafgraph.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py"], "/dash_app/callbacks/pangtreebuild.py": ["/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py", "/dash_app/server.py"], "/dash_app/callbacks/poagraph.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py", "/dash_app/app.py"]} |
56,993 | meoke/pangtreevis | refs/heads/master | /dash_app/layout/layout_ids.py | id_pang_button = 'pang_button'
id_pangenome_upload = 'pangenome_upload'
id_pangenome_hidden = 'pangenome_hidden'
id_pangenome_parameters_hidden = 'pangenome_parameters_hidden'
id_program_parameters = 'program_parameters'
id_pangenome_info = 'pangenome_info'
id_full_consensustable_hidden = 'full_consensustable_hidden'
id_partial_consensustable_hidden = 'partial_consensustable_hidden'
id_consensuses_table = 'consensuses_table'
id_full_consensustree_hidden = 'full_consensustree_hidden'
id_current_consensustree_hidden = 'current_consensustree_hidden'
id_consensus_tree_container = 'consensus_tree_container'
id_consensus_tree_graph = 'consesus_tree_graph'
id_leaf_info_dropdown = 'leaf_info_dropdown'
id_consensus_tree_slider = 'consensus_tree_slider'
id_consensus_node_details_table_hidden="consensus_node_details_table_hidden"
id_consensus_node_details_header="consensus_node_details_header"
id_consensus_node_details_table= "consensus_node_details_table"
id_consensus_node_details_distribution = "consensus_node_details_distribution"
id_mafgraph_hidden = 'mafgraph_hidden'
id_mafgraph = "mafgraph"
id_mafgraph_container = "mafgraph_container"
id_mafgraph_graph = "mafgraph_graph"
id_poagraph_hidden = 'poagraph_hidden'
id_poagraph_container = "poagraph_container"
id_poagraph = "poagraph"
id_show_vis = "show_vis"
id_full_pangenome_container = "full_pangenome_container"
id_full_pangenome_graph = "full_pangenome_graph"
id_poagraph_node_info = "poagraph_node_info"
id_process_tab_content = "process_tab_content"
id_fasta_provider_choice = "fasta_provider_choice"
id_consensus_algorithm_choice = "tree_algorithm_choice"
id_output_configuration="id_output_configuration"
id_metadata_upload_param = "metadata_upload_param"
id_metadata_upload_state_info = "metadata_upload_state_info"
id_blosum_upload_state_info = "blosum_upload_state_info"
id_blosum_upload_state = "blosum_upload_state"
id_processing_result = "processing_result"
id_processing_result_text = "processing_result_text"
id_go_to_vis_tab = "go_to_vis_tab"
id_download_processing_result = "download_processing_result"
id_multialignment_upload = "multialignment_upload"
id_blosum_upload = "blosum_upload"
id_metadata_upload = "metadata_upload"
# Index
id_url = "url"
id_page_content = "id_page_content"
id_tools_tabs = "tools_tabs"
# Tools - PoaPangenome
id_session_state = "session_state"
id_session_dir = "session_dir"
id_poapangenome_tab = "poapangenome_tab"
id_pangviz_tab = "pangviz_tab"
id_data_type = "data_type_edit"
id_data_type_help = "data_type_edit_help"
id_metadata_upload = "metadata_upload"
id_metadata_upload_state = "metadata_upload_state"
id_metadata_upload_info = "metadata_upload_valid"
id_multialignment_upload = "multialignment_upload"
id_multialignment_upload_state = "multialignment_upload_state"
id_multialignment_upload_state_info = "multalignment_upload_state_info"
id_maf_specific_params = "maf_specific_params"
id_missing_symbol_param = "missing_symbol_param"
id_missing_symbol_input = "missing_symbol_input"
id_fasta_upload_param = "fasta_upload_param"
id_fasta_upload = "fasta_upload"
id_fasta_upload_state = "fasta_upload_state"
id_fasta_upload_state_info = "fasta_upload_state_info"
id_poa_specific_params = "poa_specific_params"
id_hbmin_input = "hbmin_input"
id_tree_specific_params = "tree_specific_params"
id_p_input = "p_input"
id_stop_input = "stop_input"
id_running_indicator = "running_indicator"
id_poapangenome_result_description = "poapangenome_result_description"
id_poapangenome_result = "poapangenome_result"
id_pangviz_load_row = "pangviz_load_row"
id_pangviz_example_fabricated = "pangviz_example_fabricated"
id_pangviz_example_ebola = "pangviz_example_ebola"
id_pangviz_example_ballibase = "pangviz_example_ballibase"
id_task_parameters_vis = "task_parameters_vis"
id_task_parameters_row = "task_parameters_row"
id_input_info_vis = "input_info_vis"
id_input_dagmaf_vis = "input_dagmaf_vis"
id_consensus_table_container = "consensus_table_container"
id_visualisation_session_info = "visualisation_session_info"
id_elements_cache_info = "elements_cache_info"
id_result_icon = "result_icon"
id_or = "or"
id_examples_dropdown = "examples_dropdown"
id_pangviz_result_collapse = "pangviz_result_collapse" | {"/dash_app/callbacks/visualisation.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py"], "/dash_app/layout/pages.py": ["/dash_app/layout/layout_ids.py"], "/run.py": ["/dash_app/app.py"], "/dash_app/callbacks/consensustree.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/app.py": ["/dash_app/server.py"], "/dash_app/callbacks/consensustable.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/callbacks/mafgraph.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py"], "/dash_app/callbacks/pangtreebuild.py": ["/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py", "/dash_app/server.py"], "/dash_app/callbacks/poagraph.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py", "/dash_app/app.py"]} |
56,994 | meoke/pangtreevis | refs/heads/master | /dash_app/callbacks/visualisation.py | from typing import List
from dash.exceptions import PreventUpdate
from ..server import app
from dash.dependencies import Input, Output, State
from ..layout.layout_ids import *
from ..layout.pages import get_task_description_layout
from ..components import tools, poagraph
@app.callback(
Output(id_pangenome_hidden, 'children'),
[Input(id_pangenome_upload, 'contents')])
def load_visualisation(pangenome_content: str) -> str:
if not pangenome_content:
raise PreventUpdate()
if pangenome_content.startswith("data:application/json;base64"):
return tools.decode_content(pangenome_content)
return pangenome_content
@app.callback(
Output(id_pangviz_result_collapse, 'is_open'),
[Input(id_pangenome_upload, 'contents')])
def show_visualisation(pangenome_content: str) -> str:
if not pangenome_content:
return False
return True
@app.callback(Output(id_task_parameters_vis, 'children'),
[Input(id_pangenome_hidden, 'children')])
def show_task_parameters(jsonified_pangenome):
if not jsonified_pangenome:
return []
jsonpangenome = tools.unjsonify_jsonpangenome(jsonified_pangenome)
return get_task_description_layout(jsonpangenome)
@app.callback(
Output(id_poagraph, 'stylesheet'),
[Input(id_pangenome_hidden, 'children'),
Input(id_partial_consensustable_hidden, 'children')],
[State(id_poagraph_container, 'children')]
)
def update_poagraph_stylesheet(jsonified_pangenome: str, jsonified_partial_consensustable, stylesheet: List) -> List:
if not jsonified_pangenome or not jsonified_partial_consensustable:
return []
jsonpangenome = tools.unjsonify_jsonpangenome(jsonified_pangenome)
if not jsonpangenome.consensuses:
return []
partial_consensustable_data = tools.unjsonify_df(jsonified_partial_consensustable)
current_consensuses_names = [column_name for column_name in list(partial_consensustable_data) if
"CONSENSUS" in column_name]
colors = poagraph.get_distinct_colors(len(jsonpangenome.consensuses))
stylesheet = poagraph.get_poagraph_stylesheet()
for i, consensus in enumerate(jsonpangenome.consensuses):
if consensus.name in current_consensuses_names:
stylesheet.append(
{
'selector': f'.c{consensus.name}',
'style': {
'line-color': f'rgb{colors[i]}',
}
}
)
else:
stylesheet.append(
{
'selector': f'.c{consensus.name}',
'style': {
'line-color': f'rgb{colors[i]}',
'display': 'none'
}
}
)
return stylesheet
| {"/dash_app/callbacks/visualisation.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py"], "/dash_app/layout/pages.py": ["/dash_app/layout/layout_ids.py"], "/run.py": ["/dash_app/app.py"], "/dash_app/callbacks/consensustree.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/app.py": ["/dash_app/server.py"], "/dash_app/callbacks/consensustable.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/callbacks/mafgraph.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py"], "/dash_app/callbacks/pangtreebuild.py": ["/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py", "/dash_app/server.py"], "/dash_app/callbacks/poagraph.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py", "/dash_app/app.py"]} |
56,995 | meoke/pangtreevis | refs/heads/master | /dash_app/layout/pages.py | import dash_bootstrap_components as dbc
import dash_html_components as html
import dash_core_components as dcc
from pangtreebuild.output.PangenomeJSON import PangenomeJSON
from .layout_ids import *
import dash_cytoscape as cyto
import dash_table
from ..components import mafgraph as mafgraph_component
from ..components import poagraph as poagraph_component
def contact():
return dbc.Container(
[
dbc.Card(
[
dbc.CardBody(
[
dbc.CardTitle("Norbert Dojer, PhD.", className="text-info"),
dbc.CardText(html.P("dojer@mimuw.edu.pl")),
]
),
],
outline=True,
color="info"
),
dbc.Card(
[
dbc.CardBody(
[
dbc.CardTitle("Paulina Dziadkiewicz, M.Sc.", className="text-info"),
dbc.CardText("pedziadkiewicz@gmail.com"),
]
)
],
outline=True,
color="info",
)
]
)
def index():
return dbc.Container(
html.Div([
dbc.Jumbotron(children=[dbc.Row(
[dbc.Col([html.H2("PangtreeBuild"),
html.P("is a tool for multiple sequence alignment analysis."),
html.H2("PangtreeVis"),
html.P("visualises the results of PangtreeBuild in browser.")
],
className="col-md-8"),
dbc.Col(html.I(className="fas fa-seedling fa-10x logo"), className="col-md-4")])]),
dbc.Row(
dbc.CardDeck(
[
dbc.Card(
[
dbc.CardHeader(dbc.Row([dbc.Col(html.I(className="fas fa-bezier-curve fa-2x"),
className="col-md-3 my-auto"),
html.P(
"Build graph representation of multiple sequence alignment",
className="col-md-9 my-auto")])),
dbc.CardBody(
[
dbc.CardText(
html.Ul([html.Li(
["Input formats: ",
html.A("MAF",
href="http://www1.bioinf.uni-leipzig.de/UCSC/FAQ/FAQformat.html#format5",
target="_blank"), ", ",
html.A("PO",
href="https://github.com/meoke/pangtree/blob/master/Documentation.md#po-file-format-specification",
target="_blank")]),
html.Li(["Internal representation: ", html.A("Partial Order graph",
href="https://doi.org/10.1093/bioinformatics/18.3.452",
target="_blank")]),
html.Li(["Cycles in graph removed with ", html.A("Mafgraph",
href="https://github.com/anialisiecka/Mafgraph",
target="_blank")]),
html.Li("Complement missing parts from NCBI or fasta")]))
]
),
]
),
dbc.Card(
[
dbc.CardHeader(dbc.Row([dbc.Col(html.I(className="fas fa-grip-lines fa-2x"),
className="col-md-3 my-auto"),
html.P("Find sequences consensus",
className="col-md-9 my-auto")])),
dbc.CardBody(
[
dbc.CardText(
["This tool extends Partial Order Alignment (POA) algorithm introduced by ",
html.A("Lee et al.",
href="https://doi.org/10.1093/bioinformatics/18.3.452",
target="_blank"), ". It provides:",
html.Ul([html.Li([html.Strong("Consensuses"),
" - agreed representations of input subsets"]),
html.Li([html.Strong("Affinity Tree"),
" - a structure similar to phylogenetic tree but it has a consensus assigned to every node"]),
html.Li([html.Strong("Compatibility"),
" - a measure of similarity between sequence and consensus"])])
]),
]
),
]
),
dbc.Card(
[
dbc.CardHeader(dbc.Row([dbc.Col(html.I(className="fas fa-eye fa-2x"),
className="col-md-3 my-auto"),
html.P("Visualise results",
className="col-md-9 my-auto")])),
dbc.CardBody(
[
dbc.CardText(
[
html.Ul([
# html.Li("MAF blocks graph"),
html.Li("Multiple sequence alignment as Partial Order Graph"),
html.Li("Affinity tree"),
html.Li("Compatibilities relations")]
)])
]
),
]
),
]
)
)
])
)
def package():
return dbc.Container([dbc.Row(html.Span(["The underlying software is available at ",
html.A("GitHub", href="https://github.com/meoke/pangtree", target="_blank"),
# " and ",
# html.A("PyPI", href="", target="_blank"),
". It can be incorporated into your Python application in this simple way:"])),
dbc.Card(dbc.CardBody(dcc.Markdown('''
from pangtreebuild import Poagraph, input_types, fasta_provider, consensus
poagraph = Poagraph.build_from_dagmaf(input_types.Maf("example.maf"),
fasta_provider.FromNCBI())
affinity_tree = consensus.tree_generator.get_affinity_tree(poagraph,
Blosum("BLOSUM80.mat"),
output_dir,
stop=1,
p=1)
pangenomejson = to_PangenomeJSON(poagraph, affinity_tree)
''')), style={"margin": '30px 0px', 'padding': '10px'}),
dbc.Row("or used as a CLI tool:"),
dbc.Card(dbc.CardBody(dcc.Markdown(
'''pangtreebuild --multialignment "example.maf" --consensus tree --p 1 --stop 1''')),
style={"margin": '30px 0px', 'padding': '10px'}),
dbc.Row("Check out full documentation at the above link.")
]
)
def tools():
return html.Div([
dbc.Tabs(
[
dbc.Tab(_poapangenome_tab_content, id=id_poapangenome_tab, label="PangtreeBuild",
tab_style={"margin-left": "auto"}, className="tools_tab"),
dbc.Tab(_pangviz_tab_content, id=id_pangviz_tab, label="PangtreeVis", label_style={"color": "#00AEF9"}, className="tools_tab"),
], className="nav-justified",
id=id_tools_tabs,
)
])
_data_type_form = dbc.FormGroup(
[
dbc.Label("Data Type", html_for=id_data_type, width=3, className="poapangenome_label"),
dbc.Col([dbc.RadioItems(value="Nucleotides", options=[{"label": "Nucleotides", "value": "Nucleotides"},
{"label": "Aminoacids", "value": "Proteins"}],
id=id_data_type),
dbc.FormText(
"Type of aligned sequences provided in the uploaded multialignment file.",
color="secondary",
)], width=6)
],
row=True,
style={"display": "none"}
)
_metadata_upload_form = dbc.FormGroup(
[
dbc.Label("Sequences metadata", html_for=id_metadata_upload, width=3, className="poapangenome_label"),
dbc.Col([dcc.Upload(id=id_metadata_upload,
multiple=False,
children=[
dbc.Row([dbc.Col(html.I(className="fas fa-file-csv fa-2x"),
className="col-md-2"),
html.P(
"Drag & drop or select file...",
className="col-md-10")])
], className="file_upload"),
dcc.Store(id=id_metadata_upload_state),
dbc.FormText(
[
"CSV with sequences metadata. It will be included in the visualisation. "
"The 'seqid' column is obligatory and must match"
" sequences identifiers from MULTIALIGNMENT file. "
"Other columns are optional. Example file: ",
html.A("metadata.csv",
href="https://github.com/meoke/pangtree/blob/master/data/Fabricated/f_metadata.csv",
target="_blank")],
color="secondary",
)
], width=6),
dbc.Label(id=id_metadata_upload_state_info, width=3, className="poapangenome_label")
],
row=True
)
_multialignment_upload_form = dbc.FormGroup(
[
dbc.Label("Multialignment", html_for=id_multialignment_upload, width=3, className="poapangenome_label"),
dbc.Col([dcc.Upload(id=id_multialignment_upload,
multiple=False,
children=[
dbc.Row([dbc.Col(html.I(className="fas fa-align-justify fa-2x"),
className="col-md-2"),
html.P(
"Drag & drop or select file...",
className="col-md-10")])
], className="file_upload"),
dcc.Store(id=id_multialignment_upload_state),
dbc.FormText(
[
"Accepted formats: ",
html.A(
href="http://www1.bioinf.uni-leipzig.de/UCSC/FAQ/FAQformat.html#format5",
target="_blank", children="maf"), ", ",
html.A(
href="https://github.com/meoke/pangtree/blob/master/Documentation.md#po-file-format-specification",
target="_blank", children="po"),
". See example file: ",
html.A(
href="https://github.com/meoke/pangtree/blob/master/data/Ebola/multialignment.maf",
target="_blank",
children="example.maf")],
color="secondary",
)
], width=6),
dbc.Label(id=id_multialignment_upload_state_info, width=3, className="poapangenome_label")
],
row=True
)
_missing_data_form = dbc.Collapse([dbc.FormGroup(
[
dbc.Label("Missing nucleotides source", html_for=id_fasta_provider_choice, width=3,
className="poapangenome_label"),
dbc.Col([dbc.RadioItems(value="NCBI", options=[{'label': "NCBI", 'value': 'NCBI'},
{'label': 'Fasta File',
'value': 'File'},
{'label': 'Custom symbol',
'value': 'Symbol'}],
id=id_fasta_provider_choice),
dbc.FormText(
"MAF file may not include full sequences. Specify source of missing nucleotides.",
color="secondary",
)], width=6)
],
row=True
), dbc.Collapse(id=id_missing_symbol_param, children=[dbc.FormGroup(
children=[
dbc.Label("Missing symbol for unknown nucleotides", html_for=id_fasta_provider_choice,
width=3, className="poapangenome_label"),
dbc.Col([dbc.Input(value="?",
id=id_missing_symbol_input, type='text', maxlength=1, minlength=1),
dbc.FormText(
"Any single character is accepted but it must be present in BLOSUM file. Default BLOSUM file uses '?'.",
color="secondary",
)], width=6)], row=True
)]),
dbc.Collapse(id=id_fasta_upload_param, children=[dbc.FormGroup(
children=[
dbc.Label("Missing symbols file source", html_for=id_fasta_provider_choice,
width=3, className="poapangenome_label"),
dbc.Col([dcc.Upload(id=id_fasta_upload,
multiple=False,
children=[
dbc.Row([dbc.Col(html.I(className="fas fa-align-left fa-2x"),
className="col-md-2"),
html.P(
"Drag & drop or select file...",
className="col-md-10")])
], className="file_upload"),
dcc.Store(id=id_fasta_upload_state),
dbc.FormText(
[
"Provide zip with fasta files or single fasta file. It must contain all full sequeneces which are not fully represented in provided MAF file."],
color="secondary",
)
], width=6),
dbc.Label(id=id_fasta_upload_state_info, width=3, className="poapangenome_label")], row=True
)])
], id=id_maf_specific_params)
_consensus_algorithm_form = dbc.FormGroup(
[
dbc.Label("Affinity tree algorithm", html_for=id_data_type, width=3, className="poapangenome_label"),
dbc.Col([dbc.RadioItems(value="tree", options=[
{'label': "Poa", 'value': 'poa'},
{'label': 'Tree', 'value': 'tree'},
],
id=id_consensus_algorithm_choice),
dbc.FormText(
[
"There are two available algorithms for affinity tree generation. 'Poa' by ",
html.A(
"Lee et al.",
href="https://doi.org/10.1093/bioinformatics/btg109"),
" and 'Tree' algorithm described ",
html.A("here",
href="https://github.com/meoke/pangtree/blob/master/Documentation.md#idea-and-algorithm-description")],
color="secondary",
)], width=6)
],
row=True
)
_blosum_upload_form = dbc.FormGroup(
[
dbc.Label("BLOSUM", html_for=id_blosum_upload, width=3, className="poapangenome_label"),
dbc.Col([dcc.Upload(id=id_blosum_upload,
multiple=False,
children=[
dbc.Row([dbc.Col(html.I(className="fas fa-table fa-2x"),
className="col-md-2"),
html.P(
"Drag & drop or select file...",
className="col-md-10")])
], className="file_upload"),
dcc.Store(id=id_blosum_upload_state),
dbc.FormText(
[
"This parameter is optional as default BLOSUM file is ", html.A(
href="https://github.com/meoke/pangtree/blob/master/bin/blosum80.mat",
target="_blank", children="BLOSUM80"),
". The BLOSUM matrix must contain '?' or the custom symbol for missing nucleotides, if specified."],
color="secondary",
)
], width=6),
dbc.Label(id=id_blosum_upload_state_info, width=3, className="poapangenome_label")
],
row=True
)
_poa_hbmin_form = dbc.Collapse([dbc.FormGroup(
[
dbc.Label("HBMIN", html_for=id_hbmin_input, width=3,
className="poapangenome_label"),
dbc.Col([dbc.Input(value=0.9, type='number', min=0, max=1,
id=id_hbmin_input),
dbc.FormText(
"HBMIN is required minimum value of similarity between sequence and assigned consensus. It must be a value from range [0,1].",
color="secondary",
)], width=6)
],
row=True
)
], id=id_poa_specific_params)
_tree_params_form = dbc.Collapse([dbc.FormGroup([
dbc.Label("P", html_for=id_hbmin_input, width=3,
className="poapangenome_label"),
dbc.Col([dbc.Input(value=1, type='number', min=0,
id=id_p_input),
dbc.FormText(
["P is used during cutoff search. P < 1 decreases distances between small compatibilities and increases distances between the bigger ones while P > 1 works in the opposite way. This value must be > 0. ",
html.A("Read more...",
href="https://github.com/meoke/pangtree",
target="_blank")],
color="secondary",
)], width=6)
],
row=True), dbc.FormGroup([
dbc.Label("Stop", html_for=id_hbmin_input, width=3,
className="poapangenome_label"),
dbc.Col([dbc.Input(value=1, type='number', min=0, max=1,
id=id_stop_input),
dbc.FormText(
"Minimum value of compatibility in affinity tree leaves. It must be a value from range [0,1].",
color="secondary",
)], width=6)
],
row=True)], id=id_tree_specific_params)
_output_form = dbc.FormGroup(
[
dbc.Label("Additional output generation", html_for=id_output_configuration, width=3,
className="poapangenome_label"),
dbc.Col([dbc.Checklist(id=id_output_configuration,
options=[
{
'label': 'FASTA (all sequences and consensuses in fasta format)',
'value': 'fasta'},
{'label': 'PO (poagraph in PO format)', 'value': 'po'},
],
values=['fasta', 'po'])], width=6)
,
], row=True
)
_poapangenome_form = dbc.Form([
_data_type_form,
_metadata_upload_form,
_multialignment_upload_form,
_missing_data_form,
_blosum_upload_form,
_consensus_algorithm_form,
_poa_hbmin_form,
_tree_params_form,
_output_form
])
_poapangenome_tab_content = html.Div([
dcc.Store(id=id_session_state),
dcc.Store(id=id_session_dir),
dbc.Row([
dbc.Col(
[
html.H3("Task Parameters"),
_poapangenome_form,
dbc.Row(
dbc.Col(dbc.Button("Run", id=id_pang_button, color="primary", className="offset-md-5 col-md-4 ")),
dbc.Col(dcc.Loading(id="l2", children=html.Div(id=id_running_indicator), type="default")))
], className="col-md-6 offset-md-1", id='poapangenome_form'),
dbc.Col([
html.H3("Example Input Data"),
# dbc.Card(
# [
# dbc.CardHeader(
# dbc.Button("Simulated", id="collapse_simulated_button",
# className="mb-3 btn-block my-auto opac-button")),
# dbc.Collapse(
# id="simulated_collapse",
# children=
# dbc.CardBody(
# [
# dbc.CardText(["This dataset is very small and consists of simulated sequences."
# "Its aim is to demonstrate how the processing and visualisation works",
# html.Button("a", className="btn btn-primary btn-block dataset")]),
# ]
# )),
# ]
# ),
dbc.Card(
[
dbc.CardHeader(
dbc.Button("Ebola", id="collapse-ebola-button",
className="mb-3 btn-block my-auto opac-button")),
dbc.Collapse(
id="ebola_collapse",
children=dbc.CardBody(
[
dbc.CardText(["This dataset orginates from ", html.A("UCSC Ebola Portal",
href="https://genome.ucsc.edu/ebolaPortal/",
target="_blank")]),
dbc.CardText([html.A(
href="https://github.com/meoke/pangtree/blob/master/data/Ebola/multialignment.maf",
target="_blank",
children="See example file...")]),
]
))
],
),
], className="col-md-3 offset-md-1")
], className="poapangenome_content"),
dbc.Collapse(id=id_poapangenome_result, children=dbc.Row(
children=[dbc.Col([dbc.Row([html.I(id=id_result_icon), html.H3("Task completed!", className="next_to_icon")]),
dbc.Col(html.Div(id=id_poapangenome_result_description), className="col-md-11")],
className="col-md-6 offset-md-1"),
dbc.Col([
html.A(dbc.Button("Download result files", block=True, className="result_btn", color="info"),
id=id_download_processing_result),
dbc.Button("Go to visualisation", id=id_go_to_vis_tab,
n_clicks_timestamp=0, block=True, className="result_btn", color="success", style={"visibility": "hidden"})],
className="col-md-3 offset-md-1")]
))
])
_load_pangenome_row = dbc.Row(id=id_pangviz_load_row,
children=[
dbc.Col(dcc.Upload(id=id_pangenome_upload,
multiple=False,
children=[
dbc.Row([dbc.Col(html.I(className="fas fa-seedling fa-2x"),
className="col-md-2"),
html.P(
"Drag & drop pangenome.json file or select file..",
className="col-md-10")])
], className="file_upload"), width={"size": 4, "offset": 4})
])
_task_parameters_row = dbc.Row(id=id_task_parameters_row,
children=html.Div([html.Div(html.H3("Task parameters"), className="panel-heading"),
dcc.Loading(html.Div(id=id_task_parameters_vis, className="panel-body"), type="circle")],
),
className="vis_row")
_input_data_row = dbc.Row(style={'display':'none'},children=[
dbc.Col(html.Div(id=id_input_dagmaf_vis,
children=[html.H3("MAF graph"),
dcc.Loading(cyto.Cytoscape(id=id_mafgraph_graph,
elements=[],
layout={'name': 'cose'},
autoRefreshLayout=True,
style={'width': 'auto',
'height': '350px'},
zoom=1,
# style={'width': 'auto',
# 'height': '300px'},
stylesheet=mafgraph_component.get_mafgraph_stylesheet(),
# autolock=True,
boxSelectionEnabled=False,
# autoungrabify=True,
autounselectify=True),
type="circle")]
))])
_pangenome_row = dbc.Row(children=[dbc.Col(html.H4("Pangenome - Cut Width statistic"), width=12),
dbc.Col([html.P("Representation of full poagraph as Cut Width statistics."),
html.P("Cut Width - edges count between two consecutive columns."),
html.I(id="arrow_icon",
className="fas fa-level-down-alt fa-flip-horizontal fa-5x")],
width=2),
dbc.Col(html.Div(id=id_full_pangenome_container,
style={'visibility': 'hidden'},
children=[dcc.Loading(dcc.Graph(
id=id_full_pangenome_graph,
# style={'width': 'auto'},
style={'height': '200px', 'width': 'auto'},
figure={},
config={
'displayModeBar': False,
}
), type="circle")]), width=10)], className="vis_row")
_poagraph_row = dbc.Row(children=[dbc.Col(html.H4("Pangenome - a closer view on graph details"), width=12),
dbc.Col([html.P(
"This is a visualisation of pangenome internal representation as a PoaGraph"),
html.Div(id=id_poagraph_node_info)], width=2),
dbc.Col(html.Div(id=id_poagraph_container,
children=dcc.Loading(cyto.Cytoscape(id=id_poagraph,
layout={
'name': 'preset'},
stylesheet=poagraph_component.get_poagraph_stylesheet(),
elements=[
],
style={'width': 'auto',
'height': '500px',
'background-color': 'white'},
zoom=20,
# minZoom=0.9,
# maxZoom=1.1,
# panningEnabled=False,
# userPanningEnabled=False,
boxSelectionEnabled=False,
# autoungrabify=True,
autolock=True,
autounselectify=True
), type="circle")), width=10)], className="vis_row")
_affinity_tree_row = dbc.Row(children=[dbc.Col([html.H4("Affinity Tree")], width=12),
dbc.Col([html.P(
"This is affinity tree generated using this software. It is similar to a phylogenetic tree but every node has a consensus sequence assigned.")],
width=2),
dbc.Col([dcc.Graph(
id=id_consensus_tree_graph,
style={'height': '600px', 'width': 'auto'},
config={
'displayModeBar': True
},
# style={'width': 'auto'}
),
html.Div(dcc.Slider(
id=id_consensus_tree_slider,
min=0,
max=1,
marks={
int(i) if i % 1 == 0 else i: '{}'.format(i)
for i
in
[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,
0.9,
1]},
step=0.01,
value=0.5,
dots=True
), style={"margin": '-1% 20% 0% 3%'})], width=7, id="consensus_tree_col"),
dbc.Col(children=[html.H5("Metadata in affinity tree leaves:"),
dcc.Dropdown(
id=id_leaf_info_dropdown,
style={'margin-bottom': '20px'},
options=[
],
value='SEQID'
),
html.H5(["Affinity tree node details:",html.P(
id=id_consensus_node_details_header
),]),
html.Img(
id=id_consensus_node_details_distribution,
style={'max-width': '100%', 'margin-bottom':'2%'}
),
dcc.Loading(dash_table.DataTable(
id=id_consensus_node_details_table,
style_table={
'maxHeight': '800',
'overflowY': 'scroll'
},
style_cell={'textAlign': 'left'},
sorting=True
), type="circle")], width=3)], className="vis_row")
_consensus_table_row = dbc.Row(children=[dbc.Col(html.H4("Consensuses on current cut level"), width=12),
dbc.Col(html.Div(id=id_consensus_table_container,
children=dcc.Loading(dash_table.DataTable(id=id_consensuses_table,
sorting=True,
sorting_type="multi"), type="circle")), width=12, style={'overflow-x': 'scroll'})], className="vis_row")
loading_style="circle"
_pangviz_tab_content = dbc.Container([
dcc.Store(id=id_visualisation_session_info, data=""),
dcc.Store(id=id_elements_cache_info, data=""),
dbc.Row(style={'display': 'none'}, children=[html.Div(id=id_pangenome_hidden),
html.Div(id=id_poagraph_hidden),
html.Div(id=id_full_consensustree_hidden),
html.Div(id=id_partial_consensustable_hidden),
html.Div(id=id_current_consensustree_hidden),
html.Div(id=id_full_consensustable_hidden),
html.Div(id=id_consensus_node_details_table_hidden)]),
_load_pangenome_row,
dbc.Collapse(
id=id_pangviz_result_collapse,
children=[_task_parameters_row,
_input_data_row,
_pangenome_row,
_poagraph_row,
_affinity_tree_row,
_consensus_table_row])
], fluid=True)
def get_task_description_layout(jsonpangenome: PangenomeJSON) -> dbc.CardDeck():
fasta_provider_paragraph = html.P()
if jsonpangenome.task_parameters.multialignment_format == "Maf":
opt = jsonpangenome.task_parameters.fasta_complementation_option
if opt == "ConstSymbolProvider":
o = f"Const symbol {jsonpangenome.task_parameters.missing_base_symbol}"
elif opt == "FromFile":
o = f"Fasta file {jsonpangenome.task_parameters.fasta_source_file}"
else:
o = "NCBI"
fasta_provider_paragraph = html.P(f"Fasta provider: {o}")
if jsonpangenome.task_parameters.consensus_type == "poa":
cons_type_paragraph = [html.P(f"Hbmin: {jsonpangenome.task_parameters.hbmin}")]
else:
cons_type_paragraph = [html.P(f"P: {jsonpangenome.task_parameters.p}"),
html.P(f"Stop: {jsonpangenome.task_parameters.stop}")]
return dbc.CardDeck(
[
dbc.Card(
[
dbc.CardBody(
[
dbc.CardText([
html.P(f"Multialignment: {jsonpangenome.task_parameters.multialignment_file_path}"),
html.P(f"Metadata : {jsonpangenome.task_parameters.metadata_file_path}"),
fasta_provider_paragraph
]
),
]
),
dbc.CardFooter("PoaGraph Configuration", className="text-center"),
],
outline=True,
color="dark",
),
dbc.Card(
[
dbc.CardBody(
[
dbc.CardText([
html.P(f"Algorithm: {jsonpangenome.task_parameters.consensus_type}"),
html.P(f"Blosum file: {jsonpangenome.task_parameters.blosum_file_path}")]
+ cons_type_paragraph
),
]
),
dbc.CardFooter("Consensus Configuration", className="text-center"),
],
outline=True,
color="dark",
),
dbc.Card(
[
dbc.CardBody(
[
dbc.CardText([
html.P(f"Time: {jsonpangenome.task_parameters.running_time}"),
html.P(f"Poagraph nodes count: {len(jsonpangenome.nodes)}"),
html.P(f"Sequences count: {len(jsonpangenome.sequences)}"),
html.P(f"Consensuses count: {len(jsonpangenome.consensuses)}"),
]
),
]
),
dbc.CardFooter("Processing info", className="text-center"),
],
outline=True,
color="dark",
),
]
)
| {"/dash_app/callbacks/visualisation.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py"], "/dash_app/layout/pages.py": ["/dash_app/layout/layout_ids.py"], "/run.py": ["/dash_app/app.py"], "/dash_app/callbacks/consensustree.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/app.py": ["/dash_app/server.py"], "/dash_app/callbacks/consensustable.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/callbacks/mafgraph.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py"], "/dash_app/callbacks/pangtreebuild.py": ["/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py", "/dash_app/server.py"], "/dash_app/callbacks/poagraph.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py", "/dash_app/app.py"]} |
56,996 | meoke/pangtreevis | refs/heads/master | /run.py | from dash_app.app import app
if __name__ == '__main__':
app.run_server(debug=True, port=8052, host='0.0.0.0', dev_tools_ui=False)
| {"/dash_app/callbacks/visualisation.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py"], "/dash_app/layout/pages.py": ["/dash_app/layout/layout_ids.py"], "/run.py": ["/dash_app/app.py"], "/dash_app/callbacks/consensustree.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/app.py": ["/dash_app/server.py"], "/dash_app/callbacks/consensustable.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/callbacks/mafgraph.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py"], "/dash_app/callbacks/pangtreebuild.py": ["/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py", "/dash_app/server.py"], "/dash_app/callbacks/poagraph.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py", "/dash_app/app.py"]} |
56,997 | meoke/pangtreevis | refs/heads/master | /dash_app/components/mafgraph.py | from typing import Dict, Union, Any, Tuple, List
from pangtreebuild.output.PangenomeJSON import PangenomeJSON
from ..layout.colors import colors
CytoscapeNode = Dict[str, Union[str, Dict[str, Any]]]
CytoscapeEdge = Dict[str, Union[str, Dict[str, Any]]]
def get_mafgraph_stylesheet():
return [
{
'selector': '.maf_node',
'style': {
'background-color': colors['light_background'],
'border-color': colors['dark_background'],
'border-width': '0.5px',
'content': 'data(label)',
# 'height': '10px',
# 'width': '10px',
'text-halign': 'center',
'text-valign': 'center',
'font-size': '5px',
'opacity': 0.5
}
},
{
'selector': 'edge',
'style': {
}
},
{
'selector': '.correct_edge',
'style': {
'width': 'data(weight)',
'target-arrow-shape': 'triangle',
'arrow-scale': 0.5,
'curve-style': 'bezier'
}
},
{
'selector': '.incorrect_edge',
'style': {
'width': 'data(weight)',
'target-arrow-shape': 'triangle',
'arrow-scale': 0.5,
'curve-style': 'bezier',
'line-style': 'dashed'
}
}
]
def get_graph_elements(jsonpangenome: PangenomeJSON) -> Tuple[List[CytoscapeNode], List[CytoscapeEdge]]:
def get_cytoscape_node(id, label, classes) -> CytoscapeNode:
return {'data': {'id': id, 'label': label}, "classes": classes}
def get_cytoscape_edge(source, target, weight, classes) -> CytoscapeEdge:
return {'data': {'source': source, 'target': target, 'weight': weight}, "classes": classes}
if not jsonpangenome.dagmaf_nodes:
return [], []
nodes = []
edges = []
for maf_node in jsonpangenome.dagmaf_nodes:
nodes.append(get_cytoscape_node(str(maf_node.node_id),
label=str(maf_node.node_id),
classes="maf_node" + (" reversed" if maf_node.orient == -1 else "")))
for edge in maf_node.out_edges:
edges.append(get_cytoscape_edge(source=str(maf_node.node_id),
target=str(edge.to_block),
weight=len(edge.sequences),
classes="correct_edge" if edge.edge_type == [1, -1] else "incorrect_edge"))
return nodes, edges | {"/dash_app/callbacks/visualisation.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py"], "/dash_app/layout/pages.py": ["/dash_app/layout/layout_ids.py"], "/run.py": ["/dash_app/app.py"], "/dash_app/callbacks/consensustree.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/app.py": ["/dash_app/server.py"], "/dash_app/callbacks/consensustable.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py"], "/dash_app/callbacks/mafgraph.py": ["/dash_app/server.py", "/dash_app/layout/layout_ids.py"], "/dash_app/callbacks/pangtreebuild.py": ["/dash_app/layout/layout_ids.py", "/dash_app/layout/pages.py", "/dash_app/server.py"], "/dash_app/callbacks/poagraph.py": ["/dash_app/layout/layout_ids.py", "/dash_app/server.py", "/dash_app/app.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.