本文整理汇总了Python中dotmap.DotMap方法的典型用法代码示例。如果您正苦于以下问题:Python dotmap.DotMap方法的具体用法?Python dotmap.DotMap怎么用?Python dotmap.DotMap使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dotmap
的用法示例。
在下文中一共展示了dotmap.DotMap方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_config
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def read_config(path):
if path:
with open(path) as json_data_file:
conf_args = json.load(json_data_file)
else:
raise ValueError("No config provided for classifier")
# flatten last part of config, take either value or default as value
for gk, gv in conf_args.items():
for k, v in gv.items():
conf_args[gk][k] = v["value"] if (v["value"] is not None) else v["default"]
# DotMap for making nested dictionary accessible through dot notation
args = DotMap(conf_args, _dynamic=False)
return args
示例2: load_current_kube_credentials
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def load_current_kube_credentials():
with open(os.path.expanduser(KUBE_CONFIG_PATH), 'r') as f:
config = DotMap(yaml.safe_load(f))
ctx_name = config['current-context']
ctx = next(c for c in config.contexts if c.name == ctx_name)
cluster = next(c for c in config.clusters if c.name == ctx.context.cluster).cluster
if 'certificate-authority' in cluster:
ca_cert = cluster['certificate-authority']
else:
ca_cert = None
if ctx.context.user:
user = next(u for u in config.users if u.name == ctx.context.user).user
return cluster.server, ca_cert, (user['client-certificate'], user['client-key'])
else:
return cluster.server, ca_cert, None
示例3: label_defunct
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def label_defunct(client: KubernetesAPIClient, namespace: str, job: DotMap):
job_name = job.metadata.name
pods = client.get('/api/v1/namespaces/{}/pods', namespace,
params={'labelSelector': 'job-name={}'.format(job_name)})
defunct_ops = [{
'op': 'add',
'path': '/metadata/labels/defunct',
'value': 'true'
}]
for pod in pods['items']:
r = client.json_patch(defunct_ops,
'/api/v1/namespaces/{}/pods/{}',
namespace, pod.metadata.name,
raise_for_status=False)
if r.status_code != 200:
# oh well
logger.error(
'Failed to label pod as defunct: %s/%s',
namespace, pod.metadata.name)
示例4: load_current_kube_credentials
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def load_current_kube_credentials():
with open(os.path.expanduser(KUBE_CONFIG_PATH), 'r') as kcf:
config = DotMap(yaml.safe_load(kcf))
ctx_name = config['current-context']
ctx = next(c for c in config.contexts if c.name == ctx_name)
cluster = next(c for c in config.clusters if c.name == ctx.context.cluster).cluster
if 'certificate-authority' in cluster:
ca_cert = cluster['certificate-authority']
else:
ca_cert = None
if ctx.context.user:
user = next(u for u in config.users if u.name == ctx.context.user).user
return cluster.server, ca_cert, (user['client-certificate'], user['client-key'])
return cluster.server, ca_cert, None
示例5: test_halton
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def test_halton():
carDomain = Struct({
'position': Box([-10,10], [-10,10], [0,1]),
'heading': Box([0, math.pi]),
'model': DiscreteBox([0, 10])
})
space = FeatureSpace({
'weather': Feature(DiscreteBox([0,12])),
'cars': Feature(Array(carDomain, [2]))
})
halton_params = DotMap()
halton_params.sample_index = -2
halton_params.bases_skipped = 0
sampler = FeatureSampler.haltonSamplerFor(space, halton_params)
for i in range(3):
print(f'Sample #{i}:')
print(sampler.nextSample())
示例6: test_feedback_multiple_lengths
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def test_feedback_multiple_lengths():
space = FeatureSpace({
'a': Feature(Box((0, 1)), lengthDomain=DiscreteBox((1, 2)))
})
def f(sample):
assert 1 <= len(sample.a) <= 2
return -1 if len(sample.a) == 1 and sample.a[0][0] < 0.5 else 1
ce_params = DotMap(alpha=0.5, thres=0)
ce_params.cont.buckets = 2
ce_params.cont.dist = None
ce_params.disc.dist = None
sampler = FeatureSampler.crossEntropySamplerFor(space, ce_params)
sampleWithFeedback(sampler, 100, f)
l1sampler = sampler.domainSamplers[sampler.lengthDomain.makePoint(a=(1,))]
l1dist = l1sampler.cont_sampler.dist[0]
l2sampler = sampler.domainSamplers[sampler.lengthDomain.makePoint(a=(2,))]
l2dists = l2sampler.cont_sampler.dist
assert len(l1dist) == 2
assert l1dist[0] > 0.9
assert all(list(l2dist) == [0.5, 0.5] for l2dist in l2dists)
示例7: test_bayesianOptimization
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def test_bayesianOptimization():
carDomain = Struct({
'position': Box([-10,10], [-10,10], [0,1]),
'heading': Box([0, math.pi]),
})
space = FeatureSpace({
'cars': Feature(Array(carDomain, [2]))
})
def f(sample):
sample = sample.cars[0].heading[0]
return abs(sample - 0.75)
bo_params = DotMap()
bo_params.init_num = 2
sampler = FeatureSampler.bayesianOptimizationSamplerFor(space, BO_params=bo_params)
sampleWithFeedback(sampler, 3, f)
示例8: read_env_cfg
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def read_env_cfg(config_filename = 'configs/main.cfg'):
# Load from config file
cfg = DotMap()
config = cp.ConfigParser()
config.read(config_filename)
cfg.run_name = config.get('general_params', 'env_name')
cfg.floorplan = str(config.get('general_params', 'floorplan'))
cfg.o_x = float(config.get('general_params', 'o_x').split(',')[0])
cfg.o_y = float(config.get('general_params', 'o_y').split(',')[0])
cfg.alpha = float(config.get('general_params', 'alpha').split(',')[0])
cfg.ceiling_z = float(config.get('general_params', 'ceiling_z').split(',')[0])
cfg.floor_z = float(config.get('general_params', 'floor_z').split(',')[0])
cfg.player_start_z = float(config.get('general_params', 'player_start_z').split(',')[0])
return cfg
示例9: main
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def main(env, ctrl_type, ctrl_args, overrides, model_dir, logdir):
ctrl_args = DotMap(**{key: val for (key, val) in ctrl_args})
overrides.append(["ctrl_cfg.prop_cfg.model_init_cfg.model_dir", model_dir])
overrides.append(["ctrl_cfg.prop_cfg.model_init_cfg.load_model", "True"])
overrides.append(["ctrl_cfg.prop_cfg.model_pretrained", "True"])
overrides.append(["exp_cfg.exp_cfg.ninit_rollouts", "0"])
overrides.append(["exp_cfg.exp_cfg.ntrain_iters", "1"])
overrides.append(["exp_cfg.log_cfg.nrecord", "1"])
cfg = create_config(env, ctrl_type, ctrl_args, overrides, logdir)
cfg.pprint()
if ctrl_type == "MPC":
cfg.exp_cfg.exp_cfg.policy = MPC(cfg.ctrl_cfg)
exp = MBExperiment(cfg.exp_cfg)
os.makedirs(exp.logdir)
with open(os.path.join(exp.logdir, "config.txt"), "w") as f:
f.write(pprint.pformat(cfg.toDict()))
exp.run_experiment()
示例10: __init__
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def __init__(self, params):
"""Initializes an agent.
Arguments:
params: (DotMap) A DotMap of agent parameters.
.env: (OpenAI gym environment) The environment for this agent.
.noisy_actions: (bool) Indicates whether random Gaussian noise will
be added to the actions of this agent.
.noise_stddev: (float) The standard deviation to be used for the
action noise if params.noisy_actions is True.
"""
self.env = params.env
self.noise_stddev = params.noise_stddev if params.get("noisy_actions", False) else None
if isinstance(self.env, DotMap):
raise ValueError("Environment must be provided to the agent at initialization.")
if (not isinstance(self.noise_stddev, float)) and params.get("noisy_actions", False):
raise ValueError("Must provide standard deviation for noise for noisy actions.")
if self.noise_stddev is not None:
self.dU = self.env.action_space.shape[0]
示例11: read_cfg
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def read_cfg(config_filename='configs/main.cfg', verbose=False):
parser = ConfigParser()
parser.optionxform = str
parser.read(config_filename)
cfg = DotMap()
if verbose:
hyphens = '-' * int((80 - len(config_filename))/2)
print(hyphens + ' ' + config_filename + ' ' + hyphens)
for section_name in parser.sections():
if verbose:
print('[' + section_name + ']')
for name, value in parser.items(section_name):
value = ConvertIfStringIsInt(value)
cfg[name] = value
spaces = ' ' * (30 - len(name))
if verbose:
print(name + ':' + spaces + str(cfg[name]))
return cfg
示例12: resize_token_embeddings
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def resize_token_embeddings(self, new_num_tokens=None):
# function is called as a vocab length validation inside FARM
# fast way of returning an object with num_embeddings attribute (needed for some checks)
# TODO add functionality to add words/tokens to a wordembeddingmodel after initialization
temp = {}
temp["num_embeddings"] = len(self.vocab)
temp = DotMap(temp)
return temp
示例13: is_condition_complete
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def is_condition_complete(condition: DotMap) -> bool:
return condition.type == 'Complete' and str(condition.status) == 'True'
示例14: get_config_from_json
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def get_config_from_json(json_file):
"""
Get the config from a json file
:param json_file:
:return: config(namespace) or config(dictionary)
"""
# parse the configurations from the config json file provided
with open(json_file, 'r') as config_file:
config_dict = json.load(config_file)
# convert the dictionary to a namespace using bunch lib
config = DotMap(config_dict)
return config, config_dict
示例15: __init__
# 需要导入模块: import dotmap [as 别名]
# 或者: from dotmap import DotMap [as 别名]
def __init__(self, baselines_params=None):
if baselines_params is None:
baselines_params = DotMap()
baselines_params.alg = 'ppo2'
baselines_params.env_id = 'MountainCar-v0'
baseline_params.num_timesteps = 1e3
else:
if 'env_id' not in baseline_params or baseline_params.env_id !='MountainCar-v0':
baseline_params.env_id = 'MountainCar-v0'
if 'alg' not in baseline_params:
baseline_params.alg = 'ppo2'
super().__init__(baselines_params=baselines_params)
if sample_type >= 1:
self.run_task = self.run_task_retrain
self.algs = ['ppo2', 'deepq', 'acer', 'a2c', 'trpo_mpi', 'acktr']