repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.get_system | def get_system(self, twig=None, **kwargs):
"""
Filter in the 'system' context
:parameter str twig: twig to use for filtering
:parameter **kwargs: any other tags to do the filter
(except twig or context)
:return: :class:`phoebe.parameters.parameters.Parameter` or
:class:`phoebe.parameters.parameters.ParameterSet`
"""
if twig is not None:
kwargs['twig'] = twig
kwargs['context'] = 'system'
return self.filter(**kwargs) | python | def get_system(self, twig=None, **kwargs):
"""
Filter in the 'system' context
:parameter str twig: twig to use for filtering
:parameter **kwargs: any other tags to do the filter
(except twig or context)
:return: :class:`phoebe.parameters.parameters.Parameter` or
:class:`phoebe.parameters.parameters.ParameterSet`
"""
if twig is not None:
kwargs['twig'] = twig
kwargs['context'] = 'system'
return self.filter(**kwargs) | [
"def",
"get_system",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"twig",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'twig'",
"]",
"=",
"twig",
"kwargs",
"[",
"'context'",
"]",
"=",
"'system'",
"return",
"self",
".... | Filter in the 'system' context
:parameter str twig: twig to use for filtering
:parameter **kwargs: any other tags to do the filter
(except twig or context)
:return: :class:`phoebe.parameters.parameters.Parameter` or
:class:`phoebe.parameters.parameters.ParameterSet` | [
"Filter",
"in",
"the",
"system",
"context"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L1345-L1359 | train | 40,000 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.get_feature | def get_feature(self, feature=None, **kwargs):
"""
Filter in the 'proerty' context
:parameter str feature: name of the feature (optional)
:parameter **kwargs: any other tags to do the filter
(except component or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if feature is not None:
kwargs['feature'] = feature
kwargs['context'] = 'feature'
return self.filter(**kwargs) | python | def get_feature(self, feature=None, **kwargs):
"""
Filter in the 'proerty' context
:parameter str feature: name of the feature (optional)
:parameter **kwargs: any other tags to do the filter
(except component or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if feature is not None:
kwargs['feature'] = feature
kwargs['context'] = 'feature'
return self.filter(**kwargs) | [
"def",
"get_feature",
"(",
"self",
",",
"feature",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"feature",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'feature'",
"]",
"=",
"feature",
"kwargs",
"[",
"'context'",
"]",
"=",
"'feature'",
"return",
... | Filter in the 'proerty' context
:parameter str feature: name of the feature (optional)
:parameter **kwargs: any other tags to do the filter
(except component or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet` | [
"Filter",
"in",
"the",
"proerty",
"context"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L1750-L1762 | train | 40,001 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.rename_feature | def rename_feature(self, old_feature, new_feature):
"""
Change the label of a feature attached to the Bundle
:parameter str old_feature: the current name of the feature
(must exist)
:parameter str new_feature: the desired new name of the feature
(must not exist)
:return: None
:raises ValueError: if the new_feature is forbidden
"""
# TODO: raise error if old_feature not found?
self._check_label(new_feature)
self._rename_label('feature', old_feature, new_feature) | python | def rename_feature(self, old_feature, new_feature):
"""
Change the label of a feature attached to the Bundle
:parameter str old_feature: the current name of the feature
(must exist)
:parameter str new_feature: the desired new name of the feature
(must not exist)
:return: None
:raises ValueError: if the new_feature is forbidden
"""
# TODO: raise error if old_feature not found?
self._check_label(new_feature)
self._rename_label('feature', old_feature, new_feature) | [
"def",
"rename_feature",
"(",
"self",
",",
"old_feature",
",",
"new_feature",
")",
":",
"# TODO: raise error if old_feature not found?",
"self",
".",
"_check_label",
"(",
"new_feature",
")",
"self",
".",
"_rename_label",
"(",
"'feature'",
",",
"old_feature",
",",
"n... | Change the label of a feature attached to the Bundle
:parameter str old_feature: the current name of the feature
(must exist)
:parameter str new_feature: the desired new name of the feature
(must not exist)
:return: None
:raises ValueError: if the new_feature is forbidden | [
"Change",
"the",
"label",
"of",
"a",
"feature",
"attached",
"to",
"the",
"Bundle"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L1803-L1817 | train | 40,002 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.get_component | def get_component(self, component=None, **kwargs):
"""
Filter in the 'component' context
:parameter str component: name of the component (optional)
:parameter **kwargs: any other tags to do the filter
(except component or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if component is not None:
kwargs['component'] = component
kwargs['context'] = 'component'
return self.filter(**kwargs) | python | def get_component(self, component=None, **kwargs):
"""
Filter in the 'component' context
:parameter str component: name of the component (optional)
:parameter **kwargs: any other tags to do the filter
(except component or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if component is not None:
kwargs['component'] = component
kwargs['context'] = 'component'
return self.filter(**kwargs) | [
"def",
"get_component",
"(",
"self",
",",
"component",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"component",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'component'",
"]",
"=",
"component",
"kwargs",
"[",
"'context'",
"]",
"=",
"'component'",
... | Filter in the 'component' context
:parameter str component: name of the component (optional)
:parameter **kwargs: any other tags to do the filter
(except component or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet` | [
"Filter",
"in",
"the",
"component",
"context"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L1921-L1933 | train | 40,003 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.rename_component | def rename_component(self, old_component, new_component):
"""
Change the label of a component attached to the Bundle
:parameter str old_component: the current name of the component
(must exist)
:parameter str new_component: the desired new name of the component
(must not exist)
:return: None
:raises ValueError: if the new_component is forbidden
"""
# TODO: raise error if old_component not found?
# even though _rename_tag will call _check_label again, we should
# do it first so that we can raise any errors BEFORE we start messing
# with the hierarchy
self._check_label(new_component)
# changing hierarchy must be called first since it needs to access
# the kind of old_component
if len([c for c in self.components if new_component in c]):
logger.warning("hierarchy may not update correctly with new component")
self.hierarchy.rename_component(old_component, new_component)
self._rename_label('component', old_component, new_component)
self._handle_dataset_selectparams() | python | def rename_component(self, old_component, new_component):
"""
Change the label of a component attached to the Bundle
:parameter str old_component: the current name of the component
(must exist)
:parameter str new_component: the desired new name of the component
(must not exist)
:return: None
:raises ValueError: if the new_component is forbidden
"""
# TODO: raise error if old_component not found?
# even though _rename_tag will call _check_label again, we should
# do it first so that we can raise any errors BEFORE we start messing
# with the hierarchy
self._check_label(new_component)
# changing hierarchy must be called first since it needs to access
# the kind of old_component
if len([c for c in self.components if new_component in c]):
logger.warning("hierarchy may not update correctly with new component")
self.hierarchy.rename_component(old_component, new_component)
self._rename_label('component', old_component, new_component)
self._handle_dataset_selectparams() | [
"def",
"rename_component",
"(",
"self",
",",
"old_component",
",",
"new_component",
")",
":",
"# TODO: raise error if old_component not found?",
"# even though _rename_tag will call _check_label again, we should",
"# do it first so that we can raise any errors BEFORE we start messing",
"# ... | Change the label of a component attached to the Bundle
:parameter str old_component: the current name of the component
(must exist)
:parameter str new_component: the desired new name of the component
(must not exist)
:return: None
:raises ValueError: if the new_component is forbidden | [
"Change",
"the",
"label",
"of",
"a",
"component",
"attached",
"to",
"the",
"Bundle"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L1949-L1974 | train | 40,004 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.get_dataset | def get_dataset(self, dataset=None, **kwargs):
"""
Filter in the 'dataset' context
:parameter str dataset: name of the dataset (optional)
:parameter **kwargs: any other tags to do the filter
(except dataset or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if dataset is not None:
kwargs['dataset'] = dataset
kwargs['context'] = 'dataset'
if 'kind' in kwargs.keys():
# since we switched how dataset kinds are named, let's just
# automatically handle switching to lowercase
kwargs['kind'] = kwargs['kind'].lower()
return self.filter(**kwargs) | python | def get_dataset(self, dataset=None, **kwargs):
"""
Filter in the 'dataset' context
:parameter str dataset: name of the dataset (optional)
:parameter **kwargs: any other tags to do the filter
(except dataset or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if dataset is not None:
kwargs['dataset'] = dataset
kwargs['context'] = 'dataset'
if 'kind' in kwargs.keys():
# since we switched how dataset kinds are named, let's just
# automatically handle switching to lowercase
kwargs['kind'] = kwargs['kind'].lower()
return self.filter(**kwargs) | [
"def",
"get_dataset",
"(",
"self",
",",
"dataset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dataset",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'dataset'",
"]",
"=",
"dataset",
"kwargs",
"[",
"'context'",
"]",
"=",
"'dataset'",
"if",
"'... | Filter in the 'dataset' context
:parameter str dataset: name of the dataset (optional)
:parameter **kwargs: any other tags to do the filter
(except dataset or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet` | [
"Filter",
"in",
"the",
"dataset",
"context"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L2410-L2427 | train | 40,005 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.remove_dataset | def remove_dataset(self, dataset=None, **kwargs):
""" Remove a dataset from the Bundle.
This removes all matching Parameters from the dataset, model, and
constraint contexts (by default if the context tag is not provided).
You must provide some sort of filter or this will raise an Error (so
that all Parameters are not accidentally removed).
:parameter str dataset: name of the dataset
:parameter **kwargs: any other tags to do the filter (except qualifier
and dataset)
:raises ValueError: if no filter is provided
"""
self._kwargs_checks(kwargs)
# Let's avoid deleting ALL parameters from the matching contexts
if dataset is None and not len(kwargs.items()):
raise ValueError("must provide some value to filter for datasets")
# let's handle deps if kind was passed
kind = kwargs.get('kind', None)
if kind is not None:
if isinstance(kind, str):
kind = [kind]
kind_deps = []
for kind_i in kind:
dep = '{}_dep'.format(kind_i)
if dep not in kind:
kind_deps.append(dep)
kind = kind + kind_deps
kwargs['kind'] = kind
if dataset is None:
# then let's find the list of datasets that match the filter,
# we'll then use dataset to do the removing. This avoids leaving
# pararameters behind that don't specifically match the filter
# (ie if kind is passed as 'rv' we still want to remove parameters
# with datasets that are RVs but belong to a different kind in
# another context like compute)
dataset = self.filter(**kwargs).datasets
kwargs['kind'] = None
kwargs['dataset'] = dataset
# Let's avoid the possibility of deleting a single parameter
kwargs['qualifier'] = None
# Let's also avoid the possibility of accidentally deleting system
# parameters, etc
kwargs.setdefault('context', ['dataset', 'model', 'constraint', 'compute'])
# ps = self.filter(**kwargs)
# logger.info('removing {} parameters (this is not undoable)'.\
# format(len(ps)))
# print "*** kwargs", kwargs, len(ps)
self.remove_parameters_all(**kwargs)
# not really sure why we need to call this twice, but it seems to do
# the trick
self.remove_parameters_all(**kwargs)
self._handle_dataset_selectparams()
# TODO: check to make sure that trying to undo this
# will raise an error saying this is not undo-able
self._add_history(redo_func='remove_dataset',
redo_kwargs={'dataset': dataset},
undo_func=None,
undo_kwargs={})
return | python | def remove_dataset(self, dataset=None, **kwargs):
""" Remove a dataset from the Bundle.
This removes all matching Parameters from the dataset, model, and
constraint contexts (by default if the context tag is not provided).
You must provide some sort of filter or this will raise an Error (so
that all Parameters are not accidentally removed).
:parameter str dataset: name of the dataset
:parameter **kwargs: any other tags to do the filter (except qualifier
and dataset)
:raises ValueError: if no filter is provided
"""
self._kwargs_checks(kwargs)
# Let's avoid deleting ALL parameters from the matching contexts
if dataset is None and not len(kwargs.items()):
raise ValueError("must provide some value to filter for datasets")
# let's handle deps if kind was passed
kind = kwargs.get('kind', None)
if kind is not None:
if isinstance(kind, str):
kind = [kind]
kind_deps = []
for kind_i in kind:
dep = '{}_dep'.format(kind_i)
if dep not in kind:
kind_deps.append(dep)
kind = kind + kind_deps
kwargs['kind'] = kind
if dataset is None:
# then let's find the list of datasets that match the filter,
# we'll then use dataset to do the removing. This avoids leaving
# pararameters behind that don't specifically match the filter
# (ie if kind is passed as 'rv' we still want to remove parameters
# with datasets that are RVs but belong to a different kind in
# another context like compute)
dataset = self.filter(**kwargs).datasets
kwargs['kind'] = None
kwargs['dataset'] = dataset
# Let's avoid the possibility of deleting a single parameter
kwargs['qualifier'] = None
# Let's also avoid the possibility of accidentally deleting system
# parameters, etc
kwargs.setdefault('context', ['dataset', 'model', 'constraint', 'compute'])
# ps = self.filter(**kwargs)
# logger.info('removing {} parameters (this is not undoable)'.\
# format(len(ps)))
# print "*** kwargs", kwargs, len(ps)
self.remove_parameters_all(**kwargs)
# not really sure why we need to call this twice, but it seems to do
# the trick
self.remove_parameters_all(**kwargs)
self._handle_dataset_selectparams()
# TODO: check to make sure that trying to undo this
# will raise an error saying this is not undo-able
self._add_history(redo_func='remove_dataset',
redo_kwargs={'dataset': dataset},
undo_func=None,
undo_kwargs={})
return | [
"def",
"remove_dataset",
"(",
"self",
",",
"dataset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_kwargs_checks",
"(",
"kwargs",
")",
"# Let's avoid deleting ALL parameters from the matching contexts",
"if",
"dataset",
"is",
"None",
"and",
"not"... | Remove a dataset from the Bundle.
This removes all matching Parameters from the dataset, model, and
constraint contexts (by default if the context tag is not provided).
You must provide some sort of filter or this will raise an Error (so
that all Parameters are not accidentally removed).
:parameter str dataset: name of the dataset
:parameter **kwargs: any other tags to do the filter (except qualifier
and dataset)
:raises ValueError: if no filter is provided | [
"Remove",
"a",
"dataset",
"from",
"the",
"Bundle",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L2429-L2502 | train | 40,006 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.rename_dataset | def rename_dataset(self, old_dataset, new_dataset):
"""
Change the label of a dataset attached to the Bundle
:parameter str old_dataset: the current name of the dataset
(must exist)
:parameter str new_dataset: the desired new name of the dataset
(must not exist)
:return: None
:raises ValueError: if the new_dataset is forbidden
"""
# TODO: raise error if old_component not found?
self._check_label(new_dataset)
self._rename_label('dataset', old_dataset, new_dataset)
self._handle_dataset_selectparams() | python | def rename_dataset(self, old_dataset, new_dataset):
"""
Change the label of a dataset attached to the Bundle
:parameter str old_dataset: the current name of the dataset
(must exist)
:parameter str new_dataset: the desired new name of the dataset
(must not exist)
:return: None
:raises ValueError: if the new_dataset is forbidden
"""
# TODO: raise error if old_component not found?
self._check_label(new_dataset)
self._rename_label('dataset', old_dataset, new_dataset)
self._handle_dataset_selectparams() | [
"def",
"rename_dataset",
"(",
"self",
",",
"old_dataset",
",",
"new_dataset",
")",
":",
"# TODO: raise error if old_component not found?",
"self",
".",
"_check_label",
"(",
"new_dataset",
")",
"self",
".",
"_rename_label",
"(",
"'dataset'",
",",
"old_dataset",
",",
... | Change the label of a dataset attached to the Bundle
:parameter str old_dataset: the current name of the dataset
(must exist)
:parameter str new_dataset: the desired new name of the dataset
(must not exist)
:return: None
:raises ValueError: if the new_dataset is forbidden | [
"Change",
"the",
"label",
"of",
"a",
"dataset",
"attached",
"to",
"the",
"Bundle"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L2511-L2526 | train | 40,007 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.get_constraint | def get_constraint(self, twig=None, **kwargs):
"""
Filter in the 'constraint' context
:parameter str constraint: name of the constraint (optional)
:parameter **kwargs: any other tags to do the filter
(except constraint or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if twig is not None:
kwargs['twig'] = twig
kwargs['context'] = 'constraint'
return self.get(**kwargs) | python | def get_constraint(self, twig=None, **kwargs):
"""
Filter in the 'constraint' context
:parameter str constraint: name of the constraint (optional)
:parameter **kwargs: any other tags to do the filter
(except constraint or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if twig is not None:
kwargs['twig'] = twig
kwargs['context'] = 'constraint'
return self.get(**kwargs) | [
"def",
"get_constraint",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"twig",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'twig'",
"]",
"=",
"twig",
"kwargs",
"[",
"'context'",
"]",
"=",
"'constraint'",
"return",
"sel... | Filter in the 'constraint' context
:parameter str constraint: name of the constraint (optional)
:parameter **kwargs: any other tags to do the filter
(except constraint or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet` | [
"Filter",
"in",
"the",
"constraint",
"context"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L2698-L2710 | train | 40,008 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.remove_constraint | def remove_constraint(self, twig=None, **kwargs):
"""
Remove a 'constraint' from the bundle
:parameter str twig: twig to filter for the constraint
:parameter **kwargs: any other tags to do the filter
(except twig or context)
"""
# let's run delayed constraints first to ensure that we get the same
# results in interactive and non-interactive modes as well as to make
# sure we don't have delayed constraints for the constraint we're
# about to remove. This could perhaps be optimized by searching
# for this/these constraints and only running/removing those, but
# probably isn't worth the savings.
changed_params = self.run_delayed_constraints()
kwargs['twig'] = twig
redo_kwargs = deepcopy(kwargs)
kwargs['context'] = 'constraint'
# we'll get the constraint so that we can undo the bookkeeping
# and also reproduce an undo command
constraint = self.get_parameter(**kwargs)
# undo parameter bookkeeping
constraint._remove_bookkeeping()
# and finally remove it
self.remove_parameter(**kwargs)
undo_kwargs = {k: v for k, v in constraint.to_dict().items()
if v is not None and
k not in ['uniqueid', 'uniquetwig', 'twig',
'Class', 'context']}
self._add_history(redo_func='remove_constraint',
redo_kwargs=redo_kwargs,
undo_func='add_constraint',
undo_kwargs=undo_kwargs) | python | def remove_constraint(self, twig=None, **kwargs):
"""
Remove a 'constraint' from the bundle
:parameter str twig: twig to filter for the constraint
:parameter **kwargs: any other tags to do the filter
(except twig or context)
"""
# let's run delayed constraints first to ensure that we get the same
# results in interactive and non-interactive modes as well as to make
# sure we don't have delayed constraints for the constraint we're
# about to remove. This could perhaps be optimized by searching
# for this/these constraints and only running/removing those, but
# probably isn't worth the savings.
changed_params = self.run_delayed_constraints()
kwargs['twig'] = twig
redo_kwargs = deepcopy(kwargs)
kwargs['context'] = 'constraint'
# we'll get the constraint so that we can undo the bookkeeping
# and also reproduce an undo command
constraint = self.get_parameter(**kwargs)
# undo parameter bookkeeping
constraint._remove_bookkeeping()
# and finally remove it
self.remove_parameter(**kwargs)
undo_kwargs = {k: v for k, v in constraint.to_dict().items()
if v is not None and
k not in ['uniqueid', 'uniquetwig', 'twig',
'Class', 'context']}
self._add_history(redo_func='remove_constraint',
redo_kwargs=redo_kwargs,
undo_func='add_constraint',
undo_kwargs=undo_kwargs) | [
"def",
"remove_constraint",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# let's run delayed constraints first to ensure that we get the same",
"# results in interactive and non-interactive modes as well as to make",
"# sure we don't have delayed constra... | Remove a 'constraint' from the bundle
:parameter str twig: twig to filter for the constraint
:parameter **kwargs: any other tags to do the filter
(except twig or context) | [
"Remove",
"a",
"constraint",
"from",
"the",
"bundle"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L2712-L2751 | train | 40,009 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.flip_constraint | def flip_constraint(self, twig=None, solve_for=None, **kwargs):
"""
Flip an existing constraint to solve for a different parameter
:parameter str twig: twig to filter the constraint
:parameter solve_for: twig or actual parameter object of the new
parameter which this constraint should constraint (solve for).
:type solve_for: str or :class:`phoebe.parameters.parameters.Parameter
:parameter **kwargs: any other tags to do the filter
(except twig or context)
"""
self._kwargs_checks(kwargs, additional_allowed_keys=['check_nan'])
kwargs['twig'] = twig
redo_kwargs = deepcopy(kwargs)
undo_kwargs = deepcopy(kwargs)
changed_params = self.run_delayed_constraints()
param = self.get_constraint(**kwargs)
if kwargs.pop('check_nan', True) and np.any(np.isnan([p.get_value() for p in param.vars.to_list()])):
raise ValueError("cannot flip constraint while the value of {} is nan".format([p.twig for p in param.vars.to_list() if np.isnan(p.get_value())]))
if solve_for is None:
return param
if isinstance(solve_for, Parameter):
solve_for = solve_for.uniquetwig
redo_kwargs['solve_for'] = solve_for
undo_kwargs['solve_for'] = param.constrained_parameter.uniquetwig
logger.info("flipping constraint '{}' to solve for '{}'".format(param.uniquetwig, solve_for))
param.flip_for(solve_for)
result = self.run_constraint(uniqueid=param.uniqueid, skip_kwargs_checks=True)
self._add_history(redo_func='flip_constraint',
redo_kwargs=redo_kwargs,
undo_func='flip_constraint',
undo_kwargs=undo_kwargs)
return param | python | def flip_constraint(self, twig=None, solve_for=None, **kwargs):
"""
Flip an existing constraint to solve for a different parameter
:parameter str twig: twig to filter the constraint
:parameter solve_for: twig or actual parameter object of the new
parameter which this constraint should constraint (solve for).
:type solve_for: str or :class:`phoebe.parameters.parameters.Parameter
:parameter **kwargs: any other tags to do the filter
(except twig or context)
"""
self._kwargs_checks(kwargs, additional_allowed_keys=['check_nan'])
kwargs['twig'] = twig
redo_kwargs = deepcopy(kwargs)
undo_kwargs = deepcopy(kwargs)
changed_params = self.run_delayed_constraints()
param = self.get_constraint(**kwargs)
if kwargs.pop('check_nan', True) and np.any(np.isnan([p.get_value() for p in param.vars.to_list()])):
raise ValueError("cannot flip constraint while the value of {} is nan".format([p.twig for p in param.vars.to_list() if np.isnan(p.get_value())]))
if solve_for is None:
return param
if isinstance(solve_for, Parameter):
solve_for = solve_for.uniquetwig
redo_kwargs['solve_for'] = solve_for
undo_kwargs['solve_for'] = param.constrained_parameter.uniquetwig
logger.info("flipping constraint '{}' to solve for '{}'".format(param.uniquetwig, solve_for))
param.flip_for(solve_for)
result = self.run_constraint(uniqueid=param.uniqueid, skip_kwargs_checks=True)
self._add_history(redo_func='flip_constraint',
redo_kwargs=redo_kwargs,
undo_func='flip_constraint',
undo_kwargs=undo_kwargs)
return param | [
"def",
"flip_constraint",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_kwargs_checks",
"(",
"kwargs",
",",
"additional_allowed_keys",
"=",
"[",
"'check_nan'",
"]",
")",
"kwargs",
... | Flip an existing constraint to solve for a different parameter
:parameter str twig: twig to filter the constraint
:parameter solve_for: twig or actual parameter object of the new
parameter which this constraint should constraint (solve for).
:type solve_for: str or :class:`phoebe.parameters.parameters.Parameter
:parameter **kwargs: any other tags to do the filter
(except twig or context) | [
"Flip",
"an",
"existing",
"constraint",
"to",
"solve",
"for",
"a",
"different",
"parameter"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L2754-L2797 | train | 40,010 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.run_constraint | def run_constraint(self, twig=None, return_parameter=False, **kwargs):
"""
Run a given 'constraint' now and set the value of the constrained
parameter. In general, there shouldn't be any need to manually
call this - constraints should automatically be run whenever a
dependent parameter's value is change.
:parameter str twig: twig to filter for the constraint
:parameter **kwargs: any other tags to do the filter
(except twig or context)
:return: the resulting value of the constraint
:rtype: float or units.Quantity
"""
if not kwargs.get('skip_kwargs_checks', False):
self._kwargs_checks(kwargs)
kwargs['twig'] = twig
kwargs['context'] = 'constraint'
# kwargs['qualifier'] = 'expression'
kwargs['check_visible'] = False
kwargs['check_default'] = False
# print "***", kwargs
expression_param = self.get_parameter(**kwargs)
kwargs = {}
kwargs['twig'] = None
# TODO: this might not be the case, we just know its not in constraint
kwargs['qualifier'] = expression_param.qualifier
kwargs['component'] = expression_param.component
kwargs['dataset'] = expression_param.dataset
kwargs['feature'] = expression_param.feature
kwargs['context'] = []
if kwargs['component'] is not None:
kwargs['context'] += ['component']
if kwargs['dataset'] is not None:
kwargs['context'] += ['dataset']
if kwargs['feature'] is not None:
kwargs['context'] += ['feature']
kwargs['check_visible'] = False
kwargs['check_default'] = False
constrained_param = self.get_parameter(**kwargs)
result = expression_param.result
constrained_param.set_value(result, force=True, run_constraints=True)
logger.debug("setting '{}'={} from '{}' constraint".format(constrained_param.uniquetwig, result, expression_param.uniquetwig))
if return_parameter:
return constrained_param
else:
return result | python | def run_constraint(self, twig=None, return_parameter=False, **kwargs):
"""
Run a given 'constraint' now and set the value of the constrained
parameter. In general, there shouldn't be any need to manually
call this - constraints should automatically be run whenever a
dependent parameter's value is change.
:parameter str twig: twig to filter for the constraint
:parameter **kwargs: any other tags to do the filter
(except twig or context)
:return: the resulting value of the constraint
:rtype: float or units.Quantity
"""
if not kwargs.get('skip_kwargs_checks', False):
self._kwargs_checks(kwargs)
kwargs['twig'] = twig
kwargs['context'] = 'constraint'
# kwargs['qualifier'] = 'expression'
kwargs['check_visible'] = False
kwargs['check_default'] = False
# print "***", kwargs
expression_param = self.get_parameter(**kwargs)
kwargs = {}
kwargs['twig'] = None
# TODO: this might not be the case, we just know its not in constraint
kwargs['qualifier'] = expression_param.qualifier
kwargs['component'] = expression_param.component
kwargs['dataset'] = expression_param.dataset
kwargs['feature'] = expression_param.feature
kwargs['context'] = []
if kwargs['component'] is not None:
kwargs['context'] += ['component']
if kwargs['dataset'] is not None:
kwargs['context'] += ['dataset']
if kwargs['feature'] is not None:
kwargs['context'] += ['feature']
kwargs['check_visible'] = False
kwargs['check_default'] = False
constrained_param = self.get_parameter(**kwargs)
result = expression_param.result
constrained_param.set_value(result, force=True, run_constraints=True)
logger.debug("setting '{}'={} from '{}' constraint".format(constrained_param.uniquetwig, result, expression_param.uniquetwig))
if return_parameter:
return constrained_param
else:
return result | [
"def",
"run_constraint",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"return_parameter",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"get",
"(",
"'skip_kwargs_checks'",
",",
"False",
")",
":",
"self",
".",
"_kwargs_checks... | Run a given 'constraint' now and set the value of the constrained
parameter. In general, there shouldn't be any need to manually
call this - constraints should automatically be run whenever a
dependent parameter's value is change.
:parameter str twig: twig to filter for the constraint
:parameter **kwargs: any other tags to do the filter
(except twig or context)
:return: the resulting value of the constraint
:rtype: float or units.Quantity | [
"Run",
"a",
"given",
"constraint",
"now",
"and",
"set",
"the",
"value",
"of",
"the",
"constrained",
"parameter",
".",
"In",
"general",
"there",
"shouldn",
"t",
"be",
"any",
"need",
"to",
"manually",
"call",
"this",
"-",
"constraints",
"should",
"automaticall... | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L2799-L2851 | train | 40,011 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.get_compute | def get_compute(self, compute=None, **kwargs):
"""
Filter in the 'compute' context
:parameter str compute: name of the compute options (optional)
:parameter **kwargs: any other tags to do the filter
(except compute or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if compute is not None:
kwargs['compute'] = compute
kwargs['context'] = 'compute'
return self.filter(**kwargs) | python | def get_compute(self, compute=None, **kwargs):
"""
Filter in the 'compute' context
:parameter str compute: name of the compute options (optional)
:parameter **kwargs: any other tags to do the filter
(except compute or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if compute is not None:
kwargs['compute'] = compute
kwargs['context'] = 'compute'
return self.filter(**kwargs) | [
"def",
"get_compute",
"(",
"self",
",",
"compute",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"compute",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'compute'",
"]",
"=",
"compute",
"kwargs",
"[",
"'context'",
"]",
"=",
"'compute'",
"return",
... | Filter in the 'compute' context
:parameter str compute: name of the compute options (optional)
:parameter **kwargs: any other tags to do the filter
(except compute or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet` | [
"Filter",
"in",
"the",
"compute",
"context"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L2977-L2989 | train | 40,012 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.remove_compute | def remove_compute(self, compute, **kwargs):
"""
Remove a 'compute' from the bundle
:parameter str compute: name of the compute options
:parameter **kwargs: any other tags to do the filter
(except twig or context)
:raise NotImplementedError: because it isn't
"""
kwargs['compute'] = compute
kwargs['context'] = 'comute'
self.remove_parameters_all(**kwargs) | python | def remove_compute(self, compute, **kwargs):
"""
Remove a 'compute' from the bundle
:parameter str compute: name of the compute options
:parameter **kwargs: any other tags to do the filter
(except twig or context)
:raise NotImplementedError: because it isn't
"""
kwargs['compute'] = compute
kwargs['context'] = 'comute'
self.remove_parameters_all(**kwargs) | [
"def",
"remove_compute",
"(",
"self",
",",
"compute",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'compute'",
"]",
"=",
"compute",
"kwargs",
"[",
"'context'",
"]",
"=",
"'comute'",
"self",
".",
"remove_parameters_all",
"(",
"*",
"*",
"kwargs",
")"... | Remove a 'compute' from the bundle
:parameter str compute: name of the compute options
:parameter **kwargs: any other tags to do the filter
(except twig or context)
:raise NotImplementedError: because it isn't | [
"Remove",
"a",
"compute",
"from",
"the",
"bundle"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L2991-L3002 | train | 40,013 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.rename_compute | def rename_compute(self, old_compute, new_compute):
"""
Change the label of a compute attached to the Bundle
:parameter str old_compute: the current name of the compute options
(must exist)
:parameter str new_compute: the desired new name of the compute options
(must not exist)
:return: None
:raises ValueError: if the new_compute is forbidden
"""
# TODO: raise error if old_compute not found?
self._check_label(new_compute)
self._rename_label('compute', old_compute, new_compute) | python | def rename_compute(self, old_compute, new_compute):
"""
Change the label of a compute attached to the Bundle
:parameter str old_compute: the current name of the compute options
(must exist)
:parameter str new_compute: the desired new name of the compute options
(must not exist)
:return: None
:raises ValueError: if the new_compute is forbidden
"""
# TODO: raise error if old_compute not found?
self._check_label(new_compute)
self._rename_label('compute', old_compute, new_compute) | [
"def",
"rename_compute",
"(",
"self",
",",
"old_compute",
",",
"new_compute",
")",
":",
"# TODO: raise error if old_compute not found?",
"self",
".",
"_check_label",
"(",
"new_compute",
")",
"self",
".",
"_rename_label",
"(",
"'compute'",
",",
"old_compute",
",",
"n... | Change the label of a compute attached to the Bundle
:parameter str old_compute: the current name of the compute options
(must exist)
:parameter str new_compute: the desired new name of the compute options
(must not exist)
:return: None
:raises ValueError: if the new_compute is forbidden | [
"Change",
"the",
"label",
"of",
"a",
"compute",
"attached",
"to",
"the",
"Bundle"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L3011-L3025 | train | 40,014 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.get_model | def get_model(self, model=None, **kwargs):
"""
Filter in the 'model' context
:parameter str model: name of the model (optional)
:parameter **kwargs: any other tags to do the filter
(except model or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if model is not None:
kwargs['model'] = model
kwargs['context'] = 'model'
return self.filter(**kwargs) | python | def get_model(self, model=None, **kwargs):
"""
Filter in the 'model' context
:parameter str model: name of the model (optional)
:parameter **kwargs: any other tags to do the filter
(except model or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if model is not None:
kwargs['model'] = model
kwargs['context'] = 'model'
return self.filter(**kwargs) | [
"def",
"get_model",
"(",
"self",
",",
"model",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"model",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'model'",
"]",
"=",
"model",
"kwargs",
"[",
"'context'",
"]",
"=",
"'model'",
"return",
"self",
... | Filter in the 'model' context
:parameter str model: name of the model (optional)
:parameter **kwargs: any other tags to do the filter
(except model or context)
:return: :class:`phoebe.parameters.parameters.ParameterSet` | [
"Filter",
"in",
"the",
"model",
"context"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L3306-L3318 | train | 40,015 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.remove_model | def remove_model(self, model, **kwargs):
"""
Remove a 'model' from the bundle
:parameter str twig: twig to filter for the model
:parameter **kwargs: any other tags to do the filter
(except twig or context)
"""
kwargs['model'] = model
kwargs['context'] = 'model'
self.remove_parameters_all(**kwargs) | python | def remove_model(self, model, **kwargs):
"""
Remove a 'model' from the bundle
:parameter str twig: twig to filter for the model
:parameter **kwargs: any other tags to do the filter
(except twig or context)
"""
kwargs['model'] = model
kwargs['context'] = 'model'
self.remove_parameters_all(**kwargs) | [
"def",
"remove_model",
"(",
"self",
",",
"model",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'model'",
"]",
"=",
"model",
"kwargs",
"[",
"'context'",
"]",
"=",
"'model'",
"self",
".",
"remove_parameters_all",
"(",
"*",
"*",
"kwargs",
")"
] | Remove a 'model' from the bundle
:parameter str twig: twig to filter for the model
:parameter **kwargs: any other tags to do the filter
(except twig or context) | [
"Remove",
"a",
"model",
"from",
"the",
"bundle"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L3320-L3330 | train | 40,016 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.rename_model | def rename_model(self, old_model, new_model):
"""
Change the label of a model attached to the Bundle
:parameter str old_model: the current name of the model
(must exist)
:parameter str new_model: the desired new name of the model
(must not exist)
:return: None
:raises ValueError: if the new_model is forbidden
"""
# TODO: raise error if old_feature not found?
self._check_label(new_model)
self._rename_label('model', old_model, new_model) | python | def rename_model(self, old_model, new_model):
"""
Change the label of a model attached to the Bundle
:parameter str old_model: the current name of the model
(must exist)
:parameter str new_model: the desired new name of the model
(must not exist)
:return: None
:raises ValueError: if the new_model is forbidden
"""
# TODO: raise error if old_feature not found?
self._check_label(new_model)
self._rename_label('model', old_model, new_model) | [
"def",
"rename_model",
"(",
"self",
",",
"old_model",
",",
"new_model",
")",
":",
"# TODO: raise error if old_feature not found?",
"self",
".",
"_check_label",
"(",
"new_model",
")",
"self",
".",
"_rename_label",
"(",
"'model'",
",",
"old_model",
",",
"new_model",
... | Change the label of a model attached to the Bundle
:parameter str old_model: the current name of the model
(must exist)
:parameter str new_model: the desired new name of the model
(must not exist)
:return: None
:raises ValueError: if the new_model is forbidden | [
"Change",
"the",
"label",
"of",
"a",
"model",
"attached",
"to",
"the",
"Bundle"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L3339-L3353 | train | 40,017 |
phoebe-project/phoebe2 | phoebe/parameters/twighelpers.py | _twig_to_uniqueid | def _twig_to_uniqueid(bundle, twig, **kwargs):
"""
kwargs are passed on to filter
"""
res = bundle.filter(twig=twig, force_ps=True, check_visible=False, check_default=False, **kwargs)
# we force_ps instead of checking is_instance(res, ParameterSet) to avoid
# having to import from parameters
if len(res) == 1:
#~ print "twighelpers._twig_to_uniqueid len(res): {}, res: {}".format(len(res), res)
return res.to_list()[0].uniqueid
else:
raise ValueError("did not return a single unique match to a parameter for '{}'".format(twig)) | python | def _twig_to_uniqueid(bundle, twig, **kwargs):
"""
kwargs are passed on to filter
"""
res = bundle.filter(twig=twig, force_ps=True, check_visible=False, check_default=False, **kwargs)
# we force_ps instead of checking is_instance(res, ParameterSet) to avoid
# having to import from parameters
if len(res) == 1:
#~ print "twighelpers._twig_to_uniqueid len(res): {}, res: {}".format(len(res), res)
return res.to_list()[0].uniqueid
else:
raise ValueError("did not return a single unique match to a parameter for '{}'".format(twig)) | [
"def",
"_twig_to_uniqueid",
"(",
"bundle",
",",
"twig",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"bundle",
".",
"filter",
"(",
"twig",
"=",
"twig",
",",
"force_ps",
"=",
"True",
",",
"check_visible",
"=",
"False",
",",
"check_default",
"=",
"Fals... | kwargs are passed on to filter | [
"kwargs",
"are",
"passed",
"on",
"to",
"filter"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/twighelpers.py#L10-L21 | train | 40,018 |
phoebe-project/phoebe2 | phoebe/constraints/expression.py | ConstraintVar.update_user_label | def update_user_label(self):
"""
finds this parameter and gets the least_unique_twig from the bundle
"""
self._user_label = _uniqueid_to_uniquetwig(self._bundle, self.unique_label)
self._set_curly_label() | python | def update_user_label(self):
"""
finds this parameter and gets the least_unique_twig from the bundle
"""
self._user_label = _uniqueid_to_uniquetwig(self._bundle, self.unique_label)
self._set_curly_label() | [
"def",
"update_user_label",
"(",
"self",
")",
":",
"self",
".",
"_user_label",
"=",
"_uniqueid_to_uniquetwig",
"(",
"self",
".",
"_bundle",
",",
"self",
".",
"unique_label",
")",
"self",
".",
"_set_curly_label",
"(",
")"
] | finds this parameter and gets the least_unique_twig from the bundle | [
"finds",
"this",
"parameter",
"and",
"gets",
"the",
"least_unique_twig",
"from",
"the",
"bundle"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/constraints/expression.py#L53-L59 | train | 40,019 |
phoebe-project/phoebe2 | phoebe/constraints/expression.py | ConstraintVar.get_parameter | def get_parameter(self):
"""
get the parameter object from the system for this var
needs to be backend safe (not passing or storing bundle)
"""
if not self.is_param:
raise ValueError("this var does not point to a parameter")
# this is quite expensive, so let's cache the parameter object so we only
# have to filter on the first time this is called
if self._parameter is None:
self._parameter = self._bundle.get_parameter(uniqueid=self.unique_label, check_visible=False, check_default=False)
return self._parameter | python | def get_parameter(self):
"""
get the parameter object from the system for this var
needs to be backend safe (not passing or storing bundle)
"""
if not self.is_param:
raise ValueError("this var does not point to a parameter")
# this is quite expensive, so let's cache the parameter object so we only
# have to filter on the first time this is called
if self._parameter is None:
self._parameter = self._bundle.get_parameter(uniqueid=self.unique_label, check_visible=False, check_default=False)
return self._parameter | [
"def",
"get_parameter",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_param",
":",
"raise",
"ValueError",
"(",
"\"this var does not point to a parameter\"",
")",
"# this is quite expensive, so let's cache the parameter object so we only",
"# have to filter on the first tim... | get the parameter object from the system for this var
needs to be backend safe (not passing or storing bundle) | [
"get",
"the",
"parameter",
"object",
"from",
"the",
"system",
"for",
"this",
"var"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/constraints/expression.py#L82-L96 | train | 40,020 |
phoebe-project/phoebe2 | phoebe/dependencies/autofig/axes.py | _process_dimension_kwargs | def _process_dimension_kwargs(direction, kwargs):
"""
process kwargs for AxDimension instances by stripping off the prefix
for the appropriate direction
"""
acceptable_keys = ['unit', 'pad', 'lim', 'label']
# if direction in ['s']:
# acceptable_keys += ['mode']
processed_kwargs = {}
for k,v in kwargs.items():
if k.startswith(direction):
processed_key = k.lstrip(direction)
else:
processed_key = k
if processed_key in acceptable_keys:
processed_kwargs[processed_key] = v
return processed_kwargs | python | def _process_dimension_kwargs(direction, kwargs):
"""
process kwargs for AxDimension instances by stripping off the prefix
for the appropriate direction
"""
acceptable_keys = ['unit', 'pad', 'lim', 'label']
# if direction in ['s']:
# acceptable_keys += ['mode']
processed_kwargs = {}
for k,v in kwargs.items():
if k.startswith(direction):
processed_key = k.lstrip(direction)
else:
processed_key = k
if processed_key in acceptable_keys:
processed_kwargs[processed_key] = v
return processed_kwargs | [
"def",
"_process_dimension_kwargs",
"(",
"direction",
",",
"kwargs",
")",
":",
"acceptable_keys",
"=",
"[",
"'unit'",
",",
"'pad'",
",",
"'lim'",
",",
"'label'",
"]",
"# if direction in ['s']:",
"# acceptable_keys += ['mode']",
"processed_kwargs",
"=",
"{",
"}",
"fo... | process kwargs for AxDimension instances by stripping off the prefix
for the appropriate direction | [
"process",
"kwargs",
"for",
"AxDimension",
"instances",
"by",
"stripping",
"off",
"the",
"prefix",
"for",
"the",
"appropriate",
"direction"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/autofig/axes.py#L1249-L1267 | train | 40,021 |
phoebe-project/phoebe2 | phoebe/dependencies/autofig/axes.py | Axes.calls_sorted | def calls_sorted(self):
"""
calls sorted in z
"""
def _z(call):
if isinstance(call.z.value, np.ndarray):
return np.mean(call.z.value.flatten())
elif isinstance(call.z.value, float) or isinstance(call.z.value, int):
return call.z.value
else:
# put it at the back
return -np.inf
calls = self._calls
zs = np.array([_z(c) for c in calls])
sorted_inds = zs.argsort()
# TODO: ugh, this is ugly. Test to find the optimal way to sort
# while still ending up with a list
return _call.make_callgroup(np.array(calls)[sorted_inds].tolist()) | python | def calls_sorted(self):
"""
calls sorted in z
"""
def _z(call):
if isinstance(call.z.value, np.ndarray):
return np.mean(call.z.value.flatten())
elif isinstance(call.z.value, float) or isinstance(call.z.value, int):
return call.z.value
else:
# put it at the back
return -np.inf
calls = self._calls
zs = np.array([_z(c) for c in calls])
sorted_inds = zs.argsort()
# TODO: ugh, this is ugly. Test to find the optimal way to sort
# while still ending up with a list
return _call.make_callgroup(np.array(calls)[sorted_inds].tolist()) | [
"def",
"calls_sorted",
"(",
"self",
")",
":",
"def",
"_z",
"(",
"call",
")",
":",
"if",
"isinstance",
"(",
"call",
".",
"z",
".",
"value",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"np",
".",
"mean",
"(",
"call",
".",
"z",
".",
"value",
".... | calls sorted in z | [
"calls",
"sorted",
"in",
"z"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/autofig/axes.py#L145-L163 | train | 40,022 |
pinax/pinax-teams | pinax/teams/utils.py | create_teams | def create_teams(obj, user, access):
"""
Will create new teams associated with the referenced obj and set the
resulting relation to the correct attribute.
The naming convention for team foreign keys is pluralname_team (for
example, instructors_team).
This function will take the access dictionary and apply the specified
access types as follows:
access = {
'trainees_team': ('open', 'add someone'),
}
Where the key name is the team name and the tuple contains the access
types for member access and manager access respectively.
If the foreign key already has a value associated with it, this function
will NOT create a new team to replace it.
"""
for field_name, access_types in access.items():
id_field = "{}_id".format(field_name)
# Check that the team is associated with the object via a FK...
if hasattr(obj, id_field) and getattr(obj, id_field) is None:
# ...and there is no existing related team.
# TODO - the team name needs to be able to create a unique
# slug that's < 50 characters long.
# TODO - this is just a workaround:
next_pk = next(iter(instance.pk for instance in obj.__class__.objects.order_by("-pk")), 0) + 1 # this is a thing a beauty. ;-)
team_name = u"{} for {} {}".format(
field_name, obj._meta.model_name, next_pk)
new_team = Team(
name=team_name,
member_access=access_types[0],
manager_access=access_types[1],
creator=user)
new_team.save()
setattr(obj, field_name, new_team)
return obj | python | def create_teams(obj, user, access):
"""
Will create new teams associated with the referenced obj and set the
resulting relation to the correct attribute.
The naming convention for team foreign keys is pluralname_team (for
example, instructors_team).
This function will take the access dictionary and apply the specified
access types as follows:
access = {
'trainees_team': ('open', 'add someone'),
}
Where the key name is the team name and the tuple contains the access
types for member access and manager access respectively.
If the foreign key already has a value associated with it, this function
will NOT create a new team to replace it.
"""
for field_name, access_types in access.items():
id_field = "{}_id".format(field_name)
# Check that the team is associated with the object via a FK...
if hasattr(obj, id_field) and getattr(obj, id_field) is None:
# ...and there is no existing related team.
# TODO - the team name needs to be able to create a unique
# slug that's < 50 characters long.
# TODO - this is just a workaround:
next_pk = next(iter(instance.pk for instance in obj.__class__.objects.order_by("-pk")), 0) + 1 # this is a thing a beauty. ;-)
team_name = u"{} for {} {}".format(
field_name, obj._meta.model_name, next_pk)
new_team = Team(
name=team_name,
member_access=access_types[0],
manager_access=access_types[1],
creator=user)
new_team.save()
setattr(obj, field_name, new_team)
return obj | [
"def",
"create_teams",
"(",
"obj",
",",
"user",
",",
"access",
")",
":",
"for",
"field_name",
",",
"access_types",
"in",
"access",
".",
"items",
"(",
")",
":",
"id_field",
"=",
"\"{}_id\"",
".",
"format",
"(",
"field_name",
")",
"# Check that the team is ass... | Will create new teams associated with the referenced obj and set the
resulting relation to the correct attribute.
The naming convention for team foreign keys is pluralname_team (for
example, instructors_team).
This function will take the access dictionary and apply the specified
access types as follows:
access = {
'trainees_team': ('open', 'add someone'),
}
Where the key name is the team name and the tuple contains the access
types for member access and manager access respectively.
If the foreign key already has a value associated with it, this function
will NOT create a new team to replace it. | [
"Will",
"create",
"new",
"teams",
"associated",
"with",
"the",
"referenced",
"obj",
"and",
"set",
"the",
"resulting",
"relation",
"to",
"the",
"correct",
"attribute",
"."
] | f8354ba0d32b3979d1dc18f50d23fd0096445ab7 | https://github.com/pinax/pinax-teams/blob/f8354ba0d32b3979d1dc18f50d23fd0096445ab7/pinax/teams/utils.py#L4-L43 | train | 40,023 |
phoebe-project/phoebe2 | phoebe/parameters/hierarchy.py | binaryorbit | def binaryorbit(orbit, comp1, comp2, envelope=None):
"""
Build the string representation of a hierarchy containing a binary
orbit with 2 components.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.set_hierarchy`
:parameter comp1: an existing hierarchy string, Parameter, or ParameterSet
:parameter comp2: an existing hierarchy string, Parameter, or ParameterSet
:return: the string representation of the hierarchy
"""
if envelope:
return '{}({}, {}, {})'.format(_to_component(orbit, False), _to_component(comp1), _to_component(comp2), _to_component(envelope, False))
else:
return '{}({}, {})'.format(_to_component(orbit, False), _to_component(comp1), _to_component(comp2)) | python | def binaryorbit(orbit, comp1, comp2, envelope=None):
"""
Build the string representation of a hierarchy containing a binary
orbit with 2 components.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.set_hierarchy`
:parameter comp1: an existing hierarchy string, Parameter, or ParameterSet
:parameter comp2: an existing hierarchy string, Parameter, or ParameterSet
:return: the string representation of the hierarchy
"""
if envelope:
return '{}({}, {}, {})'.format(_to_component(orbit, False), _to_component(comp1), _to_component(comp2), _to_component(envelope, False))
else:
return '{}({}, {})'.format(_to_component(orbit, False), _to_component(comp1), _to_component(comp2)) | [
"def",
"binaryorbit",
"(",
"orbit",
",",
"comp1",
",",
"comp2",
",",
"envelope",
"=",
"None",
")",
":",
"if",
"envelope",
":",
"return",
"'{}({}, {}, {})'",
".",
"format",
"(",
"_to_component",
"(",
"orbit",
",",
"False",
")",
",",
"_to_component",
"(",
... | Build the string representation of a hierarchy containing a binary
orbit with 2 components.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.set_hierarchy`
:parameter comp1: an existing hierarchy string, Parameter, or ParameterSet
:parameter comp2: an existing hierarchy string, Parameter, or ParameterSet
:return: the string representation of the hierarchy | [
"Build",
"the",
"string",
"representation",
"of",
"a",
"hierarchy",
"containing",
"a",
"binary",
"orbit",
"with",
"2",
"components",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/hierarchy.py#L37-L53 | train | 40,024 |
phoebe-project/phoebe2 | phoebe/dependencies/autofig/call.py | CallDimension.direction | def direction(self, direction):
"""
set the direction
"""
if not isinstance(direction, str):
raise TypeError("direction must be of type str")
accepted_values = ['i', 'x', 'y', 'z', 's', 'c']
if direction not in accepted_values:
raise ValueError("must be one of: {}".format(accepted_values))
self._direction = direction | python | def direction(self, direction):
"""
set the direction
"""
if not isinstance(direction, str):
raise TypeError("direction must be of type str")
accepted_values = ['i', 'x', 'y', 'z', 's', 'c']
if direction not in accepted_values:
raise ValueError("must be one of: {}".format(accepted_values))
self._direction = direction | [
"def",
"direction",
"(",
"self",
",",
"direction",
")",
":",
"if",
"not",
"isinstance",
"(",
"direction",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"direction must be of type str\"",
")",
"accepted_values",
"=",
"[",
"'i'",
",",
"'x'",
",",
"'y'",
... | set the direction | [
"set",
"the",
"direction"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/autofig/call.py#L1397-L1408 | train | 40,025 |
phoebe-project/phoebe2 | phoebe/dependencies/autofig/call.py | CallDimension.error | def error(self, error):
"""
set the error
"""
# TODO: check length with value?
# TODO: type checks (similar to value)
if self.direction not in ['x', 'y', 'z'] and error is not None:
raise ValueError("error only accepted for x, y, z dimensions")
if isinstance(error, u.Quantity):
error = error.to(self.unit).value
self._error = error | python | def error(self, error):
"""
set the error
"""
# TODO: check length with value?
# TODO: type checks (similar to value)
if self.direction not in ['x', 'y', 'z'] and error is not None:
raise ValueError("error only accepted for x, y, z dimensions")
if isinstance(error, u.Quantity):
error = error.to(self.unit).value
self._error = error | [
"def",
"error",
"(",
"self",
",",
"error",
")",
":",
"# TODO: check length with value?",
"# TODO: type checks (similar to value)",
"if",
"self",
".",
"direction",
"not",
"in",
"[",
"'x'",
",",
"'y'",
",",
"'z'",
"]",
"and",
"error",
"is",
"not",
"None",
":",
... | set the error | [
"set",
"the",
"error"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/autofig/call.py#L1783-L1795 | train | 40,026 |
phoebe-project/phoebe2 | phoebe/dependencies/autofig/call.py | CallDimension.label | def label(self, label):
"""
set the label
"""
if self.direction in ['i'] and label is not None:
raise ValueError("label not accepted for indep dimension")
if label is None:
self._label = label
return
if not isinstance(label, str):
try:
label = str(label)
except:
raise TypeError("label must be of type str")
self._label = label | python | def label(self, label):
"""
set the label
"""
if self.direction in ['i'] and label is not None:
raise ValueError("label not accepted for indep dimension")
if label is None:
self._label = label
return
if not isinstance(label, str):
try:
label = str(label)
except:
raise TypeError("label must be of type str")
self._label = label | [
"def",
"label",
"(",
"self",
",",
"label",
")",
":",
"if",
"self",
".",
"direction",
"in",
"[",
"'i'",
"]",
"and",
"label",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"label not accepted for indep dimension\"",
")",
"if",
"label",
"is",
"None"... | set the label | [
"set",
"the",
"label"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/autofig/call.py#L1820-L1838 | train | 40,027 |
phoebe-project/phoebe2 | phoebe/dependencies/autofig/call.py | CallDimensionI.value | def value(self):
"""
access the value
"""
if isinstance(self._value, str):
dimension = self._value
return getattr(self.call, dimension).value
return super(CallDimensionI, self)._get_value() | python | def value(self):
"""
access the value
"""
if isinstance(self._value, str):
dimension = self._value
return getattr(self.call, dimension).value
return super(CallDimensionI, self)._get_value() | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_value",
",",
"str",
")",
":",
"dimension",
"=",
"self",
".",
"_value",
"return",
"getattr",
"(",
"self",
".",
"call",
",",
"dimension",
")",
".",
"value",
"return",
"super... | access the value | [
"access",
"the",
"value"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/autofig/call.py#L1865-L1873 | train | 40,028 |
phoebe-project/phoebe2 | phoebe/dynamics/nbody.py | _ensure_tuple | def _ensure_tuple(item):
"""
Simply ensure that the passed item is a tuple. If it is not, then
convert it if possible, or raise a NotImplementedError
Args:
item: the item that needs to become a tuple
Returns:
the item casted as a tuple
Raises:
NotImplementedError: if converting the given item to a tuple
is not implemented.
"""
if isinstance(item, tuple):
return item
elif isinstance(item, list):
return tuple(item)
elif isinstance(item, np.ndarray):
return tuple(item.tolist())
else:
raise NotImplementedError | python | def _ensure_tuple(item):
"""
Simply ensure that the passed item is a tuple. If it is not, then
convert it if possible, or raise a NotImplementedError
Args:
item: the item that needs to become a tuple
Returns:
the item casted as a tuple
Raises:
NotImplementedError: if converting the given item to a tuple
is not implemented.
"""
if isinstance(item, tuple):
return item
elif isinstance(item, list):
return tuple(item)
elif isinstance(item, np.ndarray):
return tuple(item.tolist())
else:
raise NotImplementedError | [
"def",
"_ensure_tuple",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"tuple",
")",
":",
"return",
"item",
"elif",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"return",
"tuple",
"(",
"item",
")",
"elif",
"isinstance",
"(",
"item",
... | Simply ensure that the passed item is a tuple. If it is not, then
convert it if possible, or raise a NotImplementedError
Args:
item: the item that needs to become a tuple
Returns:
the item casted as a tuple
Raises:
NotImplementedError: if converting the given item to a tuple
is not implemented. | [
"Simply",
"ensure",
"that",
"the",
"passed",
"item",
"is",
"a",
"tuple",
".",
"If",
"it",
"is",
"not",
"then",
"convert",
"it",
"if",
"possible",
"or",
"raise",
"a",
"NotImplementedError"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dynamics/nbody.py#L36-L58 | train | 40,029 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | asini | def asini(b, orbit, solve_for=None):
"""
Create a constraint for asini in an orbit.
If any of the required parameters ('asini', 'sma', 'incl') do not
exist in the orbit, they will be created.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 'asini' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'sma' or 'incl')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
# We want to get the parameters in THIS orbit, but calling through
# the bundle in case we need to create it.
# To do that, we need to know the search parameters to get items from this PS.
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
# Now we'll define the parameters in case they don't exist and need to be created
sma_def = FloatParameter(qualifier='sma', value=8.0, default_unit=u.solRad, description='Semi major axis')
incl_def = FloatParameter(qualifier='incl', value=90.0, default_unit=u.deg, description='Orbital inclination angle')
asini_def = FloatParameter(qualifier='asini', value=8.0, default_unit=u.solRad, description='Projected semi major axis')
# And now call get_or_create on the bundle
sma, created = b.get_or_create('sma', sma_def, **metawargs)
incl, created = b.get_or_create('incl', incl_def, **metawargs)
asini, created = b.get_or_create('asini', asini_def, **metawargs)
if solve_for in [None, asini]:
lhs = asini
rhs = sma * sin(incl)
elif solve_for == sma:
lhs = sma
rhs = asini / sin(incl)
elif solve_for == incl:
lhs = incl
rhs = arcsin(asini/sma)
else:
raise NotImplementedError
#- return lhs, rhs, args_as_pss
return lhs, rhs, {'orbit': orbit} | python | def asini(b, orbit, solve_for=None):
"""
Create a constraint for asini in an orbit.
If any of the required parameters ('asini', 'sma', 'incl') do not
exist in the orbit, they will be created.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 'asini' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'sma' or 'incl')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
# We want to get the parameters in THIS orbit, but calling through
# the bundle in case we need to create it.
# To do that, we need to know the search parameters to get items from this PS.
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
# Now we'll define the parameters in case they don't exist and need to be created
sma_def = FloatParameter(qualifier='sma', value=8.0, default_unit=u.solRad, description='Semi major axis')
incl_def = FloatParameter(qualifier='incl', value=90.0, default_unit=u.deg, description='Orbital inclination angle')
asini_def = FloatParameter(qualifier='asini', value=8.0, default_unit=u.solRad, description='Projected semi major axis')
# And now call get_or_create on the bundle
sma, created = b.get_or_create('sma', sma_def, **metawargs)
incl, created = b.get_or_create('incl', incl_def, **metawargs)
asini, created = b.get_or_create('asini', asini_def, **metawargs)
if solve_for in [None, asini]:
lhs = asini
rhs = sma * sin(incl)
elif solve_for == sma:
lhs = sma
rhs = asini / sin(incl)
elif solve_for == incl:
lhs = incl
rhs = arcsin(asini/sma)
else:
raise NotImplementedError
#- return lhs, rhs, args_as_pss
return lhs, rhs, {'orbit': orbit} | [
"def",
"asini",
"(",
"b",
",",
"orbit",
",",
"solve_for",
"=",
"None",
")",
":",
"orbit_ps",
"=",
"_get_system_ps",
"(",
"b",
",",
"orbit",
")",
"# We want to get the parameters in THIS orbit, but calling through",
"# the bundle in case we need to create it.",
"# To do th... | Create a constraint for asini in an orbit.
If any of the required parameters ('asini', 'sma', 'incl') do not
exist in the orbit, they will be created.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 'asini' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'sma' or 'incl')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function) | [
"Create",
"a",
"constraint",
"for",
"asini",
"in",
"an",
"orbit",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L236-L287 | train | 40,030 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | esinw | def esinw(b, orbit, solve_for=None, **kwargs):
"""
Create a constraint for esinw in an orbit.
If 'esinw' does not exist in the orbit, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 'esinw' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'ecc', 'per0')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
esinw_def = FloatParameter(qualifier='esinw', value=0.0, default_unit=u.dimensionless_unscaled, limits=(-1.0,1.0), description='Eccentricity times sin of argument of periastron')
esinw, created = b.get_or_create('esinw', esinw_def, **metawargs)
ecc = b.get_parameter(qualifier='ecc', **metawargs)
per0 = b.get_parameter(qualifier='per0', **metawargs)
if solve_for in [None, esinw]:
lhs = esinw
rhs = ecc * sin(per0)
elif solve_for == ecc:
lhs = ecc
rhs = esinw / sin(per0)
elif solve_for == per0:
lhs = per0
#rhs = arcsin(esinw/ecc)
rhs = esinw2per0(ecc, esinw)
else:
raise NotImplementedError
return lhs, rhs, {'orbit': orbit} | python | def esinw(b, orbit, solve_for=None, **kwargs):
"""
Create a constraint for esinw in an orbit.
If 'esinw' does not exist in the orbit, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 'esinw' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'ecc', 'per0')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
esinw_def = FloatParameter(qualifier='esinw', value=0.0, default_unit=u.dimensionless_unscaled, limits=(-1.0,1.0), description='Eccentricity times sin of argument of periastron')
esinw, created = b.get_or_create('esinw', esinw_def, **metawargs)
ecc = b.get_parameter(qualifier='ecc', **metawargs)
per0 = b.get_parameter(qualifier='per0', **metawargs)
if solve_for in [None, esinw]:
lhs = esinw
rhs = ecc * sin(per0)
elif solve_for == ecc:
lhs = ecc
rhs = esinw / sin(per0)
elif solve_for == per0:
lhs = per0
#rhs = arcsin(esinw/ecc)
rhs = esinw2per0(ecc, esinw)
else:
raise NotImplementedError
return lhs, rhs, {'orbit': orbit} | [
"def",
"esinw",
"(",
"b",
",",
"orbit",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"orbit_ps",
"=",
"_get_system_ps",
"(",
"b",
",",
"orbit",
")",
"metawargs",
"=",
"orbit_ps",
".",
"meta",
"metawargs",
".",
"pop",
"(",
"'quali... | Create a constraint for esinw in an orbit.
If 'esinw' does not exist in the orbit, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 'esinw' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'ecc', 'per0')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function) | [
"Create",
"a",
"constraint",
"for",
"esinw",
"in",
"an",
"orbit",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L289-L329 | train | 40,031 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | ecosw | def ecosw(b, orbit, solve_for=None, **kwargs):
"""
Create a constraint for ecosw in an orbit.
If 'ecosw' does not exist in the orbit, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 'ecosw' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'ecc' or 'per0')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
ecosw_def = FloatParameter(qualifier='ecosw', value=0.0, default_unit=u.dimensionless_unscaled, limits=(-1.0,1.0), description='Eccentricity times cos of argument of periastron')
ecosw, created = b.get_or_create('ecosw', ecosw_def, **metawargs)
ecc = b.get_parameter(qualifier='ecc', **metawargs)
per0 = b.get_parameter(qualifier='per0', **metawargs)
if solve_for in [None, ecosw]:
lhs = ecosw
rhs = ecc * cos(per0)
elif solve_for == ecc:
lhs = ecc
rhs = ecosw / cos(per0)
elif solve_for == per0:
lhs = per0
#rhs = arccos(ecosw/ecc)
rhs = ecosw2per0(ecc, ecosw)
else:
raise NotImplementedError
return lhs, rhs, {'orbit': orbit} | python | def ecosw(b, orbit, solve_for=None, **kwargs):
"""
Create a constraint for ecosw in an orbit.
If 'ecosw' does not exist in the orbit, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 'ecosw' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'ecc' or 'per0')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
ecosw_def = FloatParameter(qualifier='ecosw', value=0.0, default_unit=u.dimensionless_unscaled, limits=(-1.0,1.0), description='Eccentricity times cos of argument of periastron')
ecosw, created = b.get_or_create('ecosw', ecosw_def, **metawargs)
ecc = b.get_parameter(qualifier='ecc', **metawargs)
per0 = b.get_parameter(qualifier='per0', **metawargs)
if solve_for in [None, ecosw]:
lhs = ecosw
rhs = ecc * cos(per0)
elif solve_for == ecc:
lhs = ecc
rhs = ecosw / cos(per0)
elif solve_for == per0:
lhs = per0
#rhs = arccos(ecosw/ecc)
rhs = ecosw2per0(ecc, ecosw)
else:
raise NotImplementedError
return lhs, rhs, {'orbit': orbit} | [
"def",
"ecosw",
"(",
"b",
",",
"orbit",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"orbit_ps",
"=",
"_get_system_ps",
"(",
"b",
",",
"orbit",
")",
"metawargs",
"=",
"orbit_ps",
".",
"meta",
"metawargs",
".",
"pop",
"(",
"'quali... | Create a constraint for ecosw in an orbit.
If 'ecosw' does not exist in the orbit, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 'ecosw' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'ecc' or 'per0')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function) | [
"Create",
"a",
"constraint",
"for",
"ecosw",
"in",
"an",
"orbit",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L331-L371 | train | 40,032 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | t0_perpass_supconj | def t0_perpass_supconj(b, orbit, solve_for=None, **kwargs):
"""
Create a constraint for t0_perpass in an orbit - allowing translating between
t0_perpass and t0_supconj.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 't0_perpass' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 't0_supconj', 'per0', 'period')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
# by default both t0s exist in an orbit, so we don't have to worry about creating either
t0_perpass = b.get_parameter(qualifier='t0_perpass', **metawargs)
t0_supconj = b.get_parameter(qualifier='t0_supconj', **metawargs)
period = b.get_parameter(qualifier='period', **metawargs)
ecc = b.get_parameter(qualifier='ecc', **metawargs)
per0 = b.get_parameter(qualifier='per0', **metawargs)
if solve_for in [None, t0_perpass]:
lhs = t0_perpass
rhs = t0_supconj_to_perpass(t0_supconj, period, ecc, per0)
elif solve_for == t0_supconj:
lhs = t0_supconj
rhs = t0_perpass_to_supconj(t0_perpass, period, ecc, per0)
else:
raise NotImplementedError
return lhs, rhs, {'orbit': orbit} | python | def t0_perpass_supconj(b, orbit, solve_for=None, **kwargs):
"""
Create a constraint for t0_perpass in an orbit - allowing translating between
t0_perpass and t0_supconj.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 't0_perpass' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 't0_supconj', 'per0', 'period')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
# by default both t0s exist in an orbit, so we don't have to worry about creating either
t0_perpass = b.get_parameter(qualifier='t0_perpass', **metawargs)
t0_supconj = b.get_parameter(qualifier='t0_supconj', **metawargs)
period = b.get_parameter(qualifier='period', **metawargs)
ecc = b.get_parameter(qualifier='ecc', **metawargs)
per0 = b.get_parameter(qualifier='per0', **metawargs)
if solve_for in [None, t0_perpass]:
lhs = t0_perpass
rhs = t0_supconj_to_perpass(t0_supconj, period, ecc, per0)
elif solve_for == t0_supconj:
lhs = t0_supconj
rhs = t0_perpass_to_supconj(t0_perpass, period, ecc, per0)
else:
raise NotImplementedError
return lhs, rhs, {'orbit': orbit} | [
"def",
"t0_perpass_supconj",
"(",
"b",
",",
"orbit",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"orbit_ps",
"=",
"_get_system_ps",
"(",
"b",
",",
"orbit",
")",
"metawargs",
"=",
"orbit_ps",
".",
"meta",
"metawargs",
".",
"pop",
"... | Create a constraint for t0_perpass in an orbit - allowing translating between
t0_perpass and t0_supconj.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 't0_perpass' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 't0_supconj', 'per0', 'period')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function) | [
"Create",
"a",
"constraint",
"for",
"t0_perpass",
"in",
"an",
"orbit",
"-",
"allowing",
"translating",
"between",
"t0_perpass",
"and",
"t0_supconj",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L373-L413 | train | 40,033 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | t0_ref_supconj | def t0_ref_supconj(b, orbit, solve_for=None, **kwargs):
"""
Create a constraint for t0_ref in an orbit - allowing translating between
t0_ref and t0_supconj.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 't0_ref' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 't0_supconj', 'per0', 'period')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
# by default both t0s exist in an orbit, so we don't have to worry about creating either
t0_ref = b.get_parameter(qualifier='t0_ref', **metawargs)
t0_supconj = b.get_parameter(qualifier='t0_supconj', **metawargs)
period = b.get_parameter(qualifier='period', **metawargs)
ecc = b.get_parameter(qualifier='ecc', **metawargs)
per0 = b.get_parameter(qualifier='per0', **metawargs)
if solve_for in [None, t0_ref]:
lhs = t0_ref
rhs = t0_supconj_to_ref(t0_supconj, period, ecc, per0)
elif solve_for == t0_supconj:
lhs = t0_supconj
rhs = t0_ref_to_supconj(t0_ref, period, ecc, per0)
else:
raise NotImplementedError
return lhs, rhs, {'orbit': orbit} | python | def t0_ref_supconj(b, orbit, solve_for=None, **kwargs):
"""
Create a constraint for t0_ref in an orbit - allowing translating between
t0_ref and t0_supconj.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 't0_ref' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 't0_supconj', 'per0', 'period')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
orbit_ps = _get_system_ps(b, orbit)
metawargs = orbit_ps.meta
metawargs.pop('qualifier')
# by default both t0s exist in an orbit, so we don't have to worry about creating either
t0_ref = b.get_parameter(qualifier='t0_ref', **metawargs)
t0_supconj = b.get_parameter(qualifier='t0_supconj', **metawargs)
period = b.get_parameter(qualifier='period', **metawargs)
ecc = b.get_parameter(qualifier='ecc', **metawargs)
per0 = b.get_parameter(qualifier='per0', **metawargs)
if solve_for in [None, t0_ref]:
lhs = t0_ref
rhs = t0_supconj_to_ref(t0_supconj, period, ecc, per0)
elif solve_for == t0_supconj:
lhs = t0_supconj
rhs = t0_ref_to_supconj(t0_ref, period, ecc, per0)
else:
raise NotImplementedError
return lhs, rhs, {'orbit': orbit} | [
"def",
"t0_ref_supconj",
"(",
"b",
",",
"orbit",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"orbit_ps",
"=",
"_get_system_ps",
"(",
"b",
",",
"orbit",
")",
"metawargs",
"=",
"orbit_ps",
".",
"meta",
"metawargs",
".",
"pop",
"(",
... | Create a constraint for t0_ref in an orbit - allowing translating between
t0_ref and t0_supconj.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be built
:parameter str solve_for: if 't0_ref' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 't0_supconj', 'per0', 'period')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function) | [
"Create",
"a",
"constraint",
"for",
"t0_ref",
"in",
"an",
"orbit",
"-",
"allowing",
"translating",
"between",
"t0_ref",
"and",
"t0_supconj",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L421-L459 | train | 40,034 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | irrad_frac | def irrad_frac(b, component, solve_for=None, **kwargs):
"""
Create a constraint to ensure that energy is conserved and all incident
light is accounted for.
"""
comp_ps = b.get_component(component=component)
irrad_frac_refl_bol = comp_ps.get_parameter(qualifier='irrad_frac_refl_bol')
irrad_frac_lost_bol = comp_ps.get_parameter(qualifier='irrad_frac_lost_bol')
if solve_for in [irrad_frac_lost_bol, None]:
lhs = irrad_frac_lost_bol
rhs = 1.0 - irrad_frac_refl_bol
elif solve_for in [irrad_frac_refl_bol]:
lhs = irrad_frac_refl_bol
rhs = 1.0 - irrad_frac_lost_bol
else:
raise NotImplementedError
return lhs, rhs, {'component': component} | python | def irrad_frac(b, component, solve_for=None, **kwargs):
"""
Create a constraint to ensure that energy is conserved and all incident
light is accounted for.
"""
comp_ps = b.get_component(component=component)
irrad_frac_refl_bol = comp_ps.get_parameter(qualifier='irrad_frac_refl_bol')
irrad_frac_lost_bol = comp_ps.get_parameter(qualifier='irrad_frac_lost_bol')
if solve_for in [irrad_frac_lost_bol, None]:
lhs = irrad_frac_lost_bol
rhs = 1.0 - irrad_frac_refl_bol
elif solve_for in [irrad_frac_refl_bol]:
lhs = irrad_frac_refl_bol
rhs = 1.0 - irrad_frac_lost_bol
else:
raise NotImplementedError
return lhs, rhs, {'component': component} | [
"def",
"irrad_frac",
"(",
"b",
",",
"component",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"comp_ps",
"=",
"b",
".",
"get_component",
"(",
"component",
"=",
"component",
")",
"irrad_frac_refl_bol",
"=",
"comp_ps",
".",
"get_paramete... | Create a constraint to ensure that energy is conserved and all incident
light is accounted for. | [
"Create",
"a",
"constraint",
"to",
"ensure",
"that",
"energy",
"is",
"conserved",
"and",
"all",
"incident",
"light",
"is",
"accounted",
"for",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L666-L686 | train | 40,035 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | semidetached | def semidetached(b, component, solve_for=None, **kwargs):
"""
Create a constraint to force requiv to be semidetached
"""
comp_ps = b.get_component(component=component)
requiv = comp_ps.get_parameter(qualifier='requiv')
requiv_critical = comp_ps.get_parameter(qualifier='requiv_max')
if solve_for in [requiv, None]:
lhs = requiv
rhs = 1.0*requiv_critical
else:
raise NotImplementedError
return lhs, rhs, {'component': component} | python | def semidetached(b, component, solve_for=None, **kwargs):
"""
Create a constraint to force requiv to be semidetached
"""
comp_ps = b.get_component(component=component)
requiv = comp_ps.get_parameter(qualifier='requiv')
requiv_critical = comp_ps.get_parameter(qualifier='requiv_max')
if solve_for in [requiv, None]:
lhs = requiv
rhs = 1.0*requiv_critical
else:
raise NotImplementedError
return lhs, rhs, {'component': component} | [
"def",
"semidetached",
"(",
"b",
",",
"component",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"comp_ps",
"=",
"b",
".",
"get_component",
"(",
"component",
"=",
"component",
")",
"requiv",
"=",
"comp_ps",
".",
"get_parameter",
"(",
... | Create a constraint to force requiv to be semidetached | [
"Create",
"a",
"constraint",
"to",
"force",
"requiv",
"to",
"be",
"semidetached"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L688-L703 | train | 40,036 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | mass | def mass(b, component, solve_for=None, **kwargs):
"""
Create a constraint for the mass of a star based on Kepler's third
law from its parent orbit.
If 'mass' does not exist in the component, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'mass' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'q', sma', 'period')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
:raises NotImplementedError: if the hierarchy is not found
:raises NotImplementedError: if the value of solve_for is not yet implemented
"""
# TODO: optimize this - this is currently by far the most expensive constraint (due mostly to the parameter multiplication)
hier = b.get_hierarchy()
if not len(hier.get_value()):
# TODO: change to custom error type to catch in bundle.add_component
# TODO: check whether the problem is 0 hierarchies or more than 1
raise NotImplementedError("constraint for mass requires hierarchy")
component_ps = _get_system_ps(b, component)
parentorbit = hier.get_parent_of(component)
parentorbit_ps = _get_system_ps(b, parentorbit)
metawargs = component_ps.meta
metawargs.pop('qualifier')
mass_def = FloatParameter(qualifier='mass', value=1.0, default_unit=u.solMass, description='Mass')
mass, created = b.get_or_create('mass', mass_def, **metawargs)
metawargs = parentorbit_ps.meta
metawargs.pop('qualifier')
sma = b.get_parameter(qualifier='sma', **metawargs)
period = b.get_parameter(qualifier='period', **metawargs)
q = b.get_parameter(qualifier='q', **metawargs)
G = c.G.to('solRad3 / (solMass d2)')
G.keep_in_solar_units = True
if hier.get_primary_or_secondary(component) == 'primary':
qthing = 1.0+q
else:
qthing = 1.0+1./q
if solve_for in [None, mass]:
lhs = mass
rhs = (4*np.pi**2 * sma**3 ) / (period**2 * qthing * G)
elif solve_for==sma:
lhs = sma
rhs = ((mass * period**2 * qthing * G)/(4 * np.pi**2))**"(1./3)"
elif solve_for==period:
lhs = period
rhs = ((4 * np.pi**2 * sma**3)/(mass * qthing * G))**"(1./2)"
elif solve_for==q:
# TODO: implement this so that one mass can be solved for sma and the
# other can be solved for q. The tricky thing is that we actually
# have qthing here... so we'll probably need to handle the primary
# vs secondary case separately.
raise NotImplementedError
else:
# TODO: solve for other options
raise NotImplementedError
return lhs, rhs, {'component': component} | python | def mass(b, component, solve_for=None, **kwargs):
"""
Create a constraint for the mass of a star based on Kepler's third
law from its parent orbit.
If 'mass' does not exist in the component, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'mass' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'q', sma', 'period')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
:raises NotImplementedError: if the hierarchy is not found
:raises NotImplementedError: if the value of solve_for is not yet implemented
"""
# TODO: optimize this - this is currently by far the most expensive constraint (due mostly to the parameter multiplication)
hier = b.get_hierarchy()
if not len(hier.get_value()):
# TODO: change to custom error type to catch in bundle.add_component
# TODO: check whether the problem is 0 hierarchies or more than 1
raise NotImplementedError("constraint for mass requires hierarchy")
component_ps = _get_system_ps(b, component)
parentorbit = hier.get_parent_of(component)
parentorbit_ps = _get_system_ps(b, parentorbit)
metawargs = component_ps.meta
metawargs.pop('qualifier')
mass_def = FloatParameter(qualifier='mass', value=1.0, default_unit=u.solMass, description='Mass')
mass, created = b.get_or_create('mass', mass_def, **metawargs)
metawargs = parentorbit_ps.meta
metawargs.pop('qualifier')
sma = b.get_parameter(qualifier='sma', **metawargs)
period = b.get_parameter(qualifier='period', **metawargs)
q = b.get_parameter(qualifier='q', **metawargs)
G = c.G.to('solRad3 / (solMass d2)')
G.keep_in_solar_units = True
if hier.get_primary_or_secondary(component) == 'primary':
qthing = 1.0+q
else:
qthing = 1.0+1./q
if solve_for in [None, mass]:
lhs = mass
rhs = (4*np.pi**2 * sma**3 ) / (period**2 * qthing * G)
elif solve_for==sma:
lhs = sma
rhs = ((mass * period**2 * qthing * G)/(4 * np.pi**2))**"(1./3)"
elif solve_for==period:
lhs = period
rhs = ((4 * np.pi**2 * sma**3)/(mass * qthing * G))**"(1./2)"
elif solve_for==q:
# TODO: implement this so that one mass can be solved for sma and the
# other can be solved for q. The tricky thing is that we actually
# have qthing here... so we'll probably need to handle the primary
# vs secondary case separately.
raise NotImplementedError
else:
# TODO: solve for other options
raise NotImplementedError
return lhs, rhs, {'component': component} | [
"def",
"mass",
"(",
"b",
",",
"component",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: optimize this - this is currently by far the most expensive constraint (due mostly to the parameter multiplication)",
"hier",
"=",
"b",
".",
"get_hierarchy"... | Create a constraint for the mass of a star based on Kepler's third
law from its parent orbit.
If 'mass' does not exist in the component, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'mass' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'q', sma', 'period')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
:raises NotImplementedError: if the hierarchy is not found
:raises NotImplementedError: if the value of solve_for is not yet implemented | [
"Create",
"a",
"constraint",
"for",
"the",
"mass",
"of",
"a",
"star",
"based",
"on",
"Kepler",
"s",
"third",
"law",
"from",
"its",
"parent",
"orbit",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L719-L795 | train | 40,037 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | comp_sma | def comp_sma(b, component, solve_for=None, **kwargs):
"""
Create a constraint for the star's semi-major axes WITHIN its
parent orbit. This is NOT the same as the semi-major axes OF
the parent orbit
If 'sma' does not exist in the component, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'sma@star' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'sma@orbit', 'q')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
hier = b.get_hierarchy()
if not len(hier.get_value()):
# TODO: change to custom error type to catch in bundle.add_component
# TODO: check whether the problem is 0 hierarchies or more than 1
raise NotImplementedError("constraint for comp_sma requires hierarchy")
component_ps = _get_system_ps(b, component)
parentorbit = hier.get_parent_of(component)
parentorbit_ps = _get_system_ps(b, parentorbit)
metawargs = component_ps.meta
metawargs.pop('qualifier')
compsma_def = FloatParameter(qualifier='sma', value=4.0, default_unit=u.solRad, description='Semi major axis of the component in the orbit')
compsma, created = b.get_or_create('sma', compsma_def, **metawargs)
metawargs = parentorbit_ps.meta
metawargs.pop('qualifier')
sma = b.get_parameter(qualifier='sma', **metawargs)
q = b.get_parameter(qualifier='q', **metawargs)
# NOTE: similar logic is also in dynamics.keplerian.dynamics_from_bundle to
# handle nested hierarchical orbits. If changing any of the logic here,
# it should be changed there as well.
if hier.get_primary_or_secondary(component) == 'primary':
qthing = (1. + 1./q)
else:
qthing = (1. + q)
if solve_for in [None, compsma]:
lhs = compsma
rhs = sma / qthing
elif solve_for == sma:
lhs = sma
rhs = compsma * qthing
else:
raise NotImplementedError
return lhs, rhs, {'component': component} | python | def comp_sma(b, component, solve_for=None, **kwargs):
"""
Create a constraint for the star's semi-major axes WITHIN its
parent orbit. This is NOT the same as the semi-major axes OF
the parent orbit
If 'sma' does not exist in the component, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'sma@star' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'sma@orbit', 'q')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
hier = b.get_hierarchy()
if not len(hier.get_value()):
# TODO: change to custom error type to catch in bundle.add_component
# TODO: check whether the problem is 0 hierarchies or more than 1
raise NotImplementedError("constraint for comp_sma requires hierarchy")
component_ps = _get_system_ps(b, component)
parentorbit = hier.get_parent_of(component)
parentorbit_ps = _get_system_ps(b, parentorbit)
metawargs = component_ps.meta
metawargs.pop('qualifier')
compsma_def = FloatParameter(qualifier='sma', value=4.0, default_unit=u.solRad, description='Semi major axis of the component in the orbit')
compsma, created = b.get_or_create('sma', compsma_def, **metawargs)
metawargs = parentorbit_ps.meta
metawargs.pop('qualifier')
sma = b.get_parameter(qualifier='sma', **metawargs)
q = b.get_parameter(qualifier='q', **metawargs)
# NOTE: similar logic is also in dynamics.keplerian.dynamics_from_bundle to
# handle nested hierarchical orbits. If changing any of the logic here,
# it should be changed there as well.
if hier.get_primary_or_secondary(component) == 'primary':
qthing = (1. + 1./q)
else:
qthing = (1. + q)
if solve_for in [None, compsma]:
lhs = compsma
rhs = sma / qthing
elif solve_for == sma:
lhs = sma
rhs = compsma * qthing
else:
raise NotImplementedError
return lhs, rhs, {'component': component} | [
"def",
"comp_sma",
"(",
"b",
",",
"component",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"hier",
"=",
"b",
".",
"get_hierarchy",
"(",
")",
"if",
"not",
"len",
"(",
"hier",
".",
"get_value",
"(",
")",
")",
":",
"# TODO: chang... | Create a constraint for the star's semi-major axes WITHIN its
parent orbit. This is NOT the same as the semi-major axes OF
the parent orbit
If 'sma' does not exist in the component, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'sma@star' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'sma@orbit', 'q')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function) | [
"Create",
"a",
"constraint",
"for",
"the",
"star",
"s",
"semi",
"-",
"major",
"axes",
"WITHIN",
"its",
"parent",
"orbit",
".",
"This",
"is",
"NOT",
"the",
"same",
"as",
"the",
"semi",
"-",
"major",
"axes",
"OF",
"the",
"parent",
"orbit"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L798-L857 | train | 40,038 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | fillout_factor | def fillout_factor(b, component, solve_for=None, **kwargs):
"""
Create a constraint to determine the fillout factor of a contact envelope.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'requiv_max' should not be the derived/constrained
parameter, provide which other parameter should be derived
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
hier = b.get_hierarchy()
if not len(hier.get_value()):
# TODO: change to custom error type to catch in bundle.add_component
# TODO: check whether the problem is 0 hierarchies or more than 1
raise NotImplementedError("constraint for requiv_contact_max requires hierarchy")
component_ps = _get_system_ps(b, component)
parentorbit = hier.get_parent_of(component)
parentorbit_ps = _get_system_ps(b, parentorbit)
pot = component_ps.get_parameter(qualifier='pot')
fillout_factor = component_ps.get_parameter(qualifier='fillout_factor')
q = parentorbit_ps.get_parameter(qualifier='q')
if solve_for in [None, fillout_factor]:
lhs = fillout_factor
rhs = roche_pot_to_fillout_factor(q, pot)
elif solve_for in [pot]:
lhs = pot
rhs = roche_fillout_factor_to_pot(q, fillout_factor)
else:
raise NotImplementedError("fillout_factor can not be solved for {}".format(solve_for))
return lhs, rhs, {'component': component} | python | def fillout_factor(b, component, solve_for=None, **kwargs):
"""
Create a constraint to determine the fillout factor of a contact envelope.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'requiv_max' should not be the derived/constrained
parameter, provide which other parameter should be derived
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
hier = b.get_hierarchy()
if not len(hier.get_value()):
# TODO: change to custom error type to catch in bundle.add_component
# TODO: check whether the problem is 0 hierarchies or more than 1
raise NotImplementedError("constraint for requiv_contact_max requires hierarchy")
component_ps = _get_system_ps(b, component)
parentorbit = hier.get_parent_of(component)
parentorbit_ps = _get_system_ps(b, parentorbit)
pot = component_ps.get_parameter(qualifier='pot')
fillout_factor = component_ps.get_parameter(qualifier='fillout_factor')
q = parentorbit_ps.get_parameter(qualifier='q')
if solve_for in [None, fillout_factor]:
lhs = fillout_factor
rhs = roche_pot_to_fillout_factor(q, pot)
elif solve_for in [pot]:
lhs = pot
rhs = roche_fillout_factor_to_pot(q, fillout_factor)
else:
raise NotImplementedError("fillout_factor can not be solved for {}".format(solve_for))
return lhs, rhs, {'component': component} | [
"def",
"fillout_factor",
"(",
"b",
",",
"component",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"hier",
"=",
"b",
".",
"get_hierarchy",
"(",
")",
"if",
"not",
"len",
"(",
"hier",
".",
"get_value",
"(",
")",
")",
":",
"# TODO:... | Create a constraint to determine the fillout factor of a contact envelope.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'requiv_max' should not be the derived/constrained
parameter, provide which other parameter should be derived
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function) | [
"Create",
"a",
"constraint",
"to",
"determine",
"the",
"fillout",
"factor",
"of",
"a",
"contact",
"envelope",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L1067-L1106 | train | 40,039 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | rotation_period | def rotation_period(b, component, solve_for=None, **kwargs):
"""
Create a constraint for the rotation period of a star given its orbital
period and synchronicity parameters.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'period@star' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'syncpar@star', 'period@orbit')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
hier = b.get_hierarchy()
if not len(hier.get_value()):
# TODO: change to custom error type to catch in bundle.add_component
# TODO: check whether the problem is 0 hierarchies or more than 1
raise NotImplementedError("constraint for comp_sma requires hierarchy")
component_ps = _get_system_ps(b, component)
parentorbit = hier.get_parent_of(component)
parentorbit_ps = _get_system_ps(b, parentorbit)
metawargs = component_ps.meta
metawargs.pop('qualifier')
period_star = b.get_parameter(qualifier='period', **metawargs)
syncpar_star = b.get_parameter(qualifier='syncpar', **metawargs)
metawargs = parentorbit_ps.meta
metawargs.pop('qualifier')
period_orbit = b.get_parameter(qualifier='period', **metawargs)
if solve_for in [None, period_star]:
lhs = period_star
rhs = period_orbit / syncpar_star
elif solve_for == syncpar_star:
lhs = syncpar_star
rhs = period_orbit / period_star
elif solve_for == period_orbit:
lhs = period_orbit
rhs = syncpar_star * period_star
else:
raise NotImplementedError
return lhs, rhs, {'component': component} | python | def rotation_period(b, component, solve_for=None, **kwargs):
"""
Create a constraint for the rotation period of a star given its orbital
period and synchronicity parameters.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'period@star' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'syncpar@star', 'period@orbit')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function)
"""
hier = b.get_hierarchy()
if not len(hier.get_value()):
# TODO: change to custom error type to catch in bundle.add_component
# TODO: check whether the problem is 0 hierarchies or more than 1
raise NotImplementedError("constraint for comp_sma requires hierarchy")
component_ps = _get_system_ps(b, component)
parentorbit = hier.get_parent_of(component)
parentorbit_ps = _get_system_ps(b, parentorbit)
metawargs = component_ps.meta
metawargs.pop('qualifier')
period_star = b.get_parameter(qualifier='period', **metawargs)
syncpar_star = b.get_parameter(qualifier='syncpar', **metawargs)
metawargs = parentorbit_ps.meta
metawargs.pop('qualifier')
period_orbit = b.get_parameter(qualifier='period', **metawargs)
if solve_for in [None, period_star]:
lhs = period_star
rhs = period_orbit / syncpar_star
elif solve_for == syncpar_star:
lhs = syncpar_star
rhs = period_orbit / period_star
elif solve_for == period_orbit:
lhs = period_orbit
rhs = syncpar_star * period_star
else:
raise NotImplementedError
return lhs, rhs, {'component': component} | [
"def",
"rotation_period",
"(",
"b",
",",
"component",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"hier",
"=",
"b",
".",
"get_hierarchy",
"(",
")",
"if",
"not",
"len",
"(",
"hier",
".",
"get_value",
"(",
")",
")",
":",
"# TODO... | Create a constraint for the rotation period of a star given its orbital
period and synchronicity parameters.
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of the star in which this
constraint should be built
:parameter str solve_for: if 'period@star' should not be the derived/constrained
parameter, provide which other parameter should be derived
(ie 'syncpar@star', 'period@orbit')
:returns: lhs (Parameter), rhs (ConstraintParameter), args (list of arguments
that were passed to this function) | [
"Create",
"a",
"constraint",
"for",
"the",
"rotation",
"period",
"of",
"a",
"star",
"given",
"its",
"orbital",
"period",
"and",
"synchronicity",
"parameters",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L1108-L1158 | train | 40,040 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/nparray.py | is_unit | def is_unit(value):
"""must be an astropy unit"""
if not _has_astropy:
raise ImportError("astropy must be installed for unit support")
if (isinstance(value, units.Unit) or isinstance(value, units.IrreducibleUnit) or isinstance(value, units.CompositeUnit)):
return True, value
else:
return False, value | python | def is_unit(value):
"""must be an astropy unit"""
if not _has_astropy:
raise ImportError("astropy must be installed for unit support")
if (isinstance(value, units.Unit) or isinstance(value, units.IrreducibleUnit) or isinstance(value, units.CompositeUnit)):
return True, value
else:
return False, value | [
"def",
"is_unit",
"(",
"value",
")",
":",
"if",
"not",
"_has_astropy",
":",
"raise",
"ImportError",
"(",
"\"astropy must be installed for unit support\"",
")",
"if",
"(",
"isinstance",
"(",
"value",
",",
"units",
".",
"Unit",
")",
"or",
"isinstance",
"(",
"val... | must be an astropy unit | [
"must",
"be",
"an",
"astropy",
"unit"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/nparray.py#L17-L24 | train | 40,041 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/nparray.py | is_unit_or_unitstring | def is_unit_or_unitstring(value):
"""must be an astropy.unit"""
if is_unit(value)[0]:
return True, value
try:
unit = units.Unit(value)
except:
return False, value
else:
return True, unit | python | def is_unit_or_unitstring(value):
"""must be an astropy.unit"""
if is_unit(value)[0]:
return True, value
try:
unit = units.Unit(value)
except:
return False, value
else:
return True, unit | [
"def",
"is_unit_or_unitstring",
"(",
"value",
")",
":",
"if",
"is_unit",
"(",
"value",
")",
"[",
"0",
"]",
":",
"return",
"True",
",",
"value",
"try",
":",
"unit",
"=",
"units",
".",
"Unit",
"(",
"value",
")",
"except",
":",
"return",
"False",
",",
... | must be an astropy.unit | [
"must",
"be",
"an",
"astropy",
".",
"unit"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/nparray.py#L26-L35 | train | 40,042 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/nparray.py | is_float | def is_float(value):
"""must be a float"""
return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value) | python | def is_float(value):
"""must be a float"""
return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value) | [
"def",
"is_float",
"(",
"value",
")",
":",
"return",
"isinstance",
"(",
"value",
",",
"float",
")",
"or",
"isinstance",
"(",
"value",
",",
"int",
")",
"or",
"isinstance",
"(",
"value",
",",
"np",
".",
"float64",
")",
",",
"float",
"(",
"value",
")"
] | must be a float | [
"must",
"be",
"a",
"float"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/nparray.py#L47-L49 | train | 40,043 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/nparray.py | ArrayWrapper.to | def to(self, unit):
"""
convert between units. Returns a new nparray object with the new units
"""
if not _has_astropy:
raise ImportError("astropy must be installed for unit/quantity support")
if self.unit is None:
raise ValueError("no units currently set")
if not is_unit_or_unitstring(unit)[0]:
raise ValueError("unit not recognized")
mult_factor = self.unit.to(unit)
copy = self.copy() * mult_factor
copy.unit = unit
return copy | python | def to(self, unit):
"""
convert between units. Returns a new nparray object with the new units
"""
if not _has_astropy:
raise ImportError("astropy must be installed for unit/quantity support")
if self.unit is None:
raise ValueError("no units currently set")
if not is_unit_or_unitstring(unit)[0]:
raise ValueError("unit not recognized")
mult_factor = self.unit.to(unit)
copy = self.copy() * mult_factor
copy.unit = unit
return copy | [
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"if",
"not",
"_has_astropy",
":",
"raise",
"ImportError",
"(",
"\"astropy must be installed for unit/quantity support\"",
")",
"if",
"self",
".",
"unit",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"no units ... | convert between units. Returns a new nparray object with the new units | [
"convert",
"between",
"units",
".",
"Returns",
"a",
"new",
"nparray",
"object",
"with",
"the",
"new",
"units"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/nparray.py#L136-L152 | train | 40,044 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/nparray.py | ArrayWrapper.to_dict | def to_dict(self):
"""
dump a representation of the nparray object to a dictionary. The
nparray object should then be able to be fully restored via
nparray.from_dict
"""
def _json_safe(v):
if isinstance(v, np.ndarray):
return v.tolist()
elif is_unit(v)[0]:
return v.to_string()
else:
return v
d = {k:_json_safe(v) for k,v in self._descriptors.items()}
d['nparray'] = self.__class__.__name__.lower()
return d | python | def to_dict(self):
"""
dump a representation of the nparray object to a dictionary. The
nparray object should then be able to be fully restored via
nparray.from_dict
"""
def _json_safe(v):
if isinstance(v, np.ndarray):
return v.tolist()
elif is_unit(v)[0]:
return v.to_string()
else:
return v
d = {k:_json_safe(v) for k,v in self._descriptors.items()}
d['nparray'] = self.__class__.__name__.lower()
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"def",
"_json_safe",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"v",
".",
"tolist",
"(",
")",
"elif",
"is_unit",
"(",
"v",
")",
"[",
"0",
"]",
":",
... | dump a representation of the nparray object to a dictionary. The
nparray object should then be able to be fully restored via
nparray.from_dict | [
"dump",
"a",
"representation",
"of",
"the",
"nparray",
"object",
"to",
"a",
"dictionary",
".",
"The",
"nparray",
"object",
"should",
"then",
"be",
"able",
"to",
"be",
"fully",
"restored",
"via",
"nparray",
".",
"from_dict"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/nparray.py#L224-L239 | train | 40,045 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/nparray.py | ArrayWrapper.to_file | def to_file(self, filename, **kwargs):
"""
dump a representation of the nparray object to a json-formatted file.
The nparray object should then be able to be fully restored via
nparray.from_file
@parameter str filename: path to the file to be created (will overwrite
if already exists)
@rtype: str
@returns: the filename
"""
f = open(filename, 'w')
f.write(self.to_json(**kwargs))
f.close()
return filename | python | def to_file(self, filename, **kwargs):
"""
dump a representation of the nparray object to a json-formatted file.
The nparray object should then be able to be fully restored via
nparray.from_file
@parameter str filename: path to the file to be created (will overwrite
if already exists)
@rtype: str
@returns: the filename
"""
f = open(filename, 'w')
f.write(self.to_json(**kwargs))
f.close()
return filename | [
"def",
"to_file",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"self",
".",
"to_json",
"(",
"*",
"*",
"kwargs",
")",
")",
"f",
".",
"close",
"(",
... | dump a representation of the nparray object to a json-formatted file.
The nparray object should then be able to be fully restored via
nparray.from_file
@parameter str filename: path to the file to be created (will overwrite
if already exists)
@rtype: str
@returns: the filename | [
"dump",
"a",
"representation",
"of",
"the",
"nparray",
"object",
"to",
"a",
"json",
"-",
"formatted",
"file",
".",
"The",
"nparray",
"object",
"should",
"then",
"be",
"able",
"to",
"be",
"fully",
"restored",
"via",
"nparray",
".",
"from_file"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/nparray.py#L249-L263 | train | 40,046 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/nparray.py | Arange.to_linspace | def to_linspace(self):
"""
convert from arange to linspace
"""
num = int((self.stop-self.start)/(self.step))
return Linspace(self.start, self.stop-self.step, num) | python | def to_linspace(self):
"""
convert from arange to linspace
"""
num = int((self.stop-self.start)/(self.step))
return Linspace(self.start, self.stop-self.step, num) | [
"def",
"to_linspace",
"(",
"self",
")",
":",
"num",
"=",
"int",
"(",
"(",
"self",
".",
"stop",
"-",
"self",
".",
"start",
")",
"/",
"(",
"self",
".",
"step",
")",
")",
"return",
"Linspace",
"(",
"self",
".",
"start",
",",
"self",
".",
"stop",
"... | convert from arange to linspace | [
"convert",
"from",
"arange",
"to",
"linspace"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/nparray.py#L382-L387 | train | 40,047 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/nparray.py | Linspace.to_arange | def to_arange(self):
"""
convert from linspace to arange
"""
arr, step = np.linspace(self.start, self.stop, self.num, self.endpoint, retstep=True)
return Arange(self.start, self.stop+step, step) | python | def to_arange(self):
"""
convert from linspace to arange
"""
arr, step = np.linspace(self.start, self.stop, self.num, self.endpoint, retstep=True)
return Arange(self.start, self.stop+step, step) | [
"def",
"to_arange",
"(",
"self",
")",
":",
"arr",
",",
"step",
"=",
"np",
".",
"linspace",
"(",
"self",
".",
"start",
",",
"self",
".",
"stop",
",",
"self",
".",
"num",
",",
"self",
".",
"endpoint",
",",
"retstep",
"=",
"True",
")",
"return",
"Ar... | convert from linspace to arange | [
"convert",
"from",
"linspace",
"to",
"arange"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/nparray.py#L427-L432 | train | 40,048 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/nparray.py | Full.to_linspace | def to_linspace(self):
"""
convert from full to linspace
"""
if hasattr(self.shape, '__len__'):
raise NotImplementedError("can only convert flat Full arrays to linspace")
return Linspace(self.fill_value, self.fill_value, self.shape) | python | def to_linspace(self):
"""
convert from full to linspace
"""
if hasattr(self.shape, '__len__'):
raise NotImplementedError("can only convert flat Full arrays to linspace")
return Linspace(self.fill_value, self.fill_value, self.shape) | [
"def",
"to_linspace",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"shape",
",",
"'__len__'",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"can only convert flat Full arrays to linspace\"",
")",
"return",
"Linspace",
"(",
"self",
".",
"fill_value"... | convert from full to linspace | [
"convert",
"from",
"full",
"to",
"linspace"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/nparray.py#L525-L531 | train | 40,049 |
phoebe-project/phoebe2 | phoebe/backend/etvs.py | crossing | def crossing(b, component, time, dynamics_method='keplerian', ltte=True, tol=1e-4, maxiter=1000):
"""
tol in days
"""
def projected_separation_sq(time, b, dynamics_method, cind1, cind2, ltte=True):
"""
"""
#print "*** projected_separation_sq", time, dynamics_method, cind1, cind2, ltte
times = np.array([time])
if dynamics_method in ['nbody', 'rebound']:
# TODO: make sure that this takes systemic velocity and corrects positions and velocities (including ltte effects if enabled)
ts, xs, ys, zs, vxs, vys, vzs = dynamics.nbody.dynamics_from_bundle(b, times, compute=None, ltte=ltte)
elif dynamics_method=='bs':
ts, xs, ys, zs, vxs, vys, vzs = dynamics.nbody.dynamics_from_bundle_bs(b, times, compute, ltte=ltte)
elif dynamics_method=='keplerian':
# TODO: make sure that this takes systemic velocity and corrects positions and velocities (including ltte effects if enabled)
ts, xs, ys, zs, vxs, vys, vzs = dynamics.keplerian.dynamics_from_bundle(b, times, compute=None, ltte=ltte, return_euler=False)
else:
raise NotImplementedError
return (xs[cind2][0]-xs[cind1][0])**2 + (ys[cind2][0]-ys[cind1][0])**2
# TODO: optimize this by allowing to pass cind1 and cind2 directly (and fallback to this if they aren't)
starrefs = b.hierarchy.get_stars()
cind1 = starrefs.index(component)
cind2 = starrefs.index(b.hierarchy.get_sibling_of(component))
# TODO: provide options for tol and maxiter (in the frontend computeoptionsp)?
return newton(projected_separation_sq, x0=time, args=(b, dynamics_method, cind1, cind2, ltte), tol=tol, maxiter=maxiter) | python | def crossing(b, component, time, dynamics_method='keplerian', ltte=True, tol=1e-4, maxiter=1000):
"""
tol in days
"""
def projected_separation_sq(time, b, dynamics_method, cind1, cind2, ltte=True):
"""
"""
#print "*** projected_separation_sq", time, dynamics_method, cind1, cind2, ltte
times = np.array([time])
if dynamics_method in ['nbody', 'rebound']:
# TODO: make sure that this takes systemic velocity and corrects positions and velocities (including ltte effects if enabled)
ts, xs, ys, zs, vxs, vys, vzs = dynamics.nbody.dynamics_from_bundle(b, times, compute=None, ltte=ltte)
elif dynamics_method=='bs':
ts, xs, ys, zs, vxs, vys, vzs = dynamics.nbody.dynamics_from_bundle_bs(b, times, compute, ltte=ltte)
elif dynamics_method=='keplerian':
# TODO: make sure that this takes systemic velocity and corrects positions and velocities (including ltte effects if enabled)
ts, xs, ys, zs, vxs, vys, vzs = dynamics.keplerian.dynamics_from_bundle(b, times, compute=None, ltte=ltte, return_euler=False)
else:
raise NotImplementedError
return (xs[cind2][0]-xs[cind1][0])**2 + (ys[cind2][0]-ys[cind1][0])**2
# TODO: optimize this by allowing to pass cind1 and cind2 directly (and fallback to this if they aren't)
starrefs = b.hierarchy.get_stars()
cind1 = starrefs.index(component)
cind2 = starrefs.index(b.hierarchy.get_sibling_of(component))
# TODO: provide options for tol and maxiter (in the frontend computeoptionsp)?
return newton(projected_separation_sq, x0=time, args=(b, dynamics_method, cind1, cind2, ltte), tol=tol, maxiter=maxiter) | [
"def",
"crossing",
"(",
"b",
",",
"component",
",",
"time",
",",
"dynamics_method",
"=",
"'keplerian'",
",",
"ltte",
"=",
"True",
",",
"tol",
"=",
"1e-4",
",",
"maxiter",
"=",
"1000",
")",
":",
"def",
"projected_separation_sq",
"(",
"time",
",",
"b",
"... | tol in days | [
"tol",
"in",
"days"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/etvs.py#L15-L53 | train | 40,050 |
phoebe-project/phoebe2 | phoebe/constraints/builtin.py | _delta_t_supconj_perpass | def _delta_t_supconj_perpass(period, ecc, per0):
"""
time shift between superior conjuction and periastron passage
"""
ups_sc = np.pi/2-per0
E_sc = 2*np.arctan( np.sqrt((1-ecc)/(1+ecc)) * np.tan(ups_sc/2) )
M_sc = E_sc - ecc*np.sin(E_sc)
return period*(M_sc/2./np.pi) | python | def _delta_t_supconj_perpass(period, ecc, per0):
"""
time shift between superior conjuction and periastron passage
"""
ups_sc = np.pi/2-per0
E_sc = 2*np.arctan( np.sqrt((1-ecc)/(1+ecc)) * np.tan(ups_sc/2) )
M_sc = E_sc - ecc*np.sin(E_sc)
return period*(M_sc/2./np.pi) | [
"def",
"_delta_t_supconj_perpass",
"(",
"period",
",",
"ecc",
",",
"per0",
")",
":",
"ups_sc",
"=",
"np",
".",
"pi",
"/",
"2",
"-",
"per0",
"E_sc",
"=",
"2",
"*",
"np",
".",
"arctan",
"(",
"np",
".",
"sqrt",
"(",
"(",
"1",
"-",
"ecc",
")",
"/",... | time shift between superior conjuction and periastron passage | [
"time",
"shift",
"between",
"superior",
"conjuction",
"and",
"periastron",
"passage"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/constraints/builtin.py#L106-L113 | train | 40,051 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/__init__.py | from_dict | def from_dict(d):
"""
load an nparray object from a dictionary
@parameter str d: dictionary representing the nparray object
"""
if isinstance(d, str):
return from_json(d)
if not isinstance(d, dict):
raise TypeError("argument must be of type dict")
if 'nparray' not in d.keys():
raise ValueError("input dictionary missing 'nparray' entry")
classname = d.pop('nparray').title()
return getattr(_wrappers, classname)(**d) | python | def from_dict(d):
"""
load an nparray object from a dictionary
@parameter str d: dictionary representing the nparray object
"""
if isinstance(d, str):
return from_json(d)
if not isinstance(d, dict):
raise TypeError("argument must be of type dict")
if 'nparray' not in d.keys():
raise ValueError("input dictionary missing 'nparray' entry")
classname = d.pop('nparray').title()
return getattr(_wrappers, classname)(**d) | [
"def",
"from_dict",
"(",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"str",
")",
":",
"return",
"from_json",
"(",
"d",
")",
"if",
"not",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"argument must be of type dict\"",
... | load an nparray object from a dictionary
@parameter str d: dictionary representing the nparray object | [
"load",
"an",
"nparray",
"object",
"from",
"a",
"dictionary"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/__init__.py#L106-L121 | train | 40,052 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/__init__.py | from_json | def from_json(j):
"""
load an nparray object from a json-formatted string
@parameter str j: json-formatted string
"""
if isinstance(j, dict):
return from_dict(j)
if not (isinstance(j, str) or isinstance(j, unicode)):
raise TypeError("argument must be of type str")
return from_dict(json.loads(j)) | python | def from_json(j):
"""
load an nparray object from a json-formatted string
@parameter str j: json-formatted string
"""
if isinstance(j, dict):
return from_dict(j)
if not (isinstance(j, str) or isinstance(j, unicode)):
raise TypeError("argument must be of type str")
return from_dict(json.loads(j)) | [
"def",
"from_json",
"(",
"j",
")",
":",
"if",
"isinstance",
"(",
"j",
",",
"dict",
")",
":",
"return",
"from_dict",
"(",
"j",
")",
"if",
"not",
"(",
"isinstance",
"(",
"j",
",",
"str",
")",
"or",
"isinstance",
"(",
"j",
",",
"unicode",
")",
")",
... | load an nparray object from a json-formatted string
@parameter str j: json-formatted string | [
"load",
"an",
"nparray",
"object",
"from",
"a",
"json",
"-",
"formatted",
"string"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/__init__.py#L123-L135 | train | 40,053 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/__init__.py | from_file | def from_file(filename):
"""
load an nparray object from a json filename
@parameter str filename: path to the file
"""
f = open(filename, 'r')
j = json.load(f)
f.close()
return from_dict(j) | python | def from_file(filename):
"""
load an nparray object from a json filename
@parameter str filename: path to the file
"""
f = open(filename, 'r')
j = json.load(f)
f.close()
return from_dict(j) | [
"def",
"from_file",
"(",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"j",
"=",
"json",
".",
"load",
"(",
"f",
")",
"f",
".",
"close",
"(",
")",
"return",
"from_dict",
"(",
"j",
")"
] | load an nparray object from a json filename
@parameter str filename: path to the file | [
"load",
"an",
"nparray",
"object",
"from",
"a",
"json",
"filename"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/__init__.py#L137-L147 | train | 40,054 |
phoebe-project/phoebe2 | phoebe/dependencies/nparray/__init__.py | monkeypatch | def monkeypatch():
"""
monkeypath built-in numpy functions to call those provided by nparray instead.
"""
np.array = array
np.arange = arange
np.linspace = linspace
np.logspace = logspace
np.geomspace = geomspace
np.full = full
np.full_like = full_like
np.zeros = zeros
np.zeros_like = zeros_like
np.ones = ones
np.ones_like = ones_like
np.eye = eye | python | def monkeypatch():
"""
monkeypath built-in numpy functions to call those provided by nparray instead.
"""
np.array = array
np.arange = arange
np.linspace = linspace
np.logspace = logspace
np.geomspace = geomspace
np.full = full
np.full_like = full_like
np.zeros = zeros
np.zeros_like = zeros_like
np.ones = ones
np.ones_like = ones_like
np.eye = eye | [
"def",
"monkeypatch",
"(",
")",
":",
"np",
".",
"array",
"=",
"array",
"np",
".",
"arange",
"=",
"arange",
"np",
".",
"linspace",
"=",
"linspace",
"np",
".",
"logspace",
"=",
"logspace",
"np",
".",
"geomspace",
"=",
"geomspace",
"np",
".",
"full",
"=... | monkeypath built-in numpy functions to call those provided by nparray instead. | [
"monkeypath",
"built",
"-",
"in",
"numpy",
"functions",
"to",
"call",
"those",
"provided",
"by",
"nparray",
"instead",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dependencies/nparray/__init__.py#L149-L164 | train | 40,055 |
phoebe-project/phoebe2 | phoebe/atmospheres/passbands.py | install_passband | def install_passband(fname, local=True):
"""
Install a passband from a local file. This simply copies the file into the
install path - but beware that clearing the installation will clear the
passband as well
If local=False, you must have permissions to access the installation directory
"""
pbdir = _pbdir_local if local else _pbdir_global
shutil.copy(fname, pbdir)
init_passband(os.path.join(pbdir, fname)) | python | def install_passband(fname, local=True):
"""
Install a passband from a local file. This simply copies the file into the
install path - but beware that clearing the installation will clear the
passband as well
If local=False, you must have permissions to access the installation directory
"""
pbdir = _pbdir_local if local else _pbdir_global
shutil.copy(fname, pbdir)
init_passband(os.path.join(pbdir, fname)) | [
"def",
"install_passband",
"(",
"fname",
",",
"local",
"=",
"True",
")",
":",
"pbdir",
"=",
"_pbdir_local",
"if",
"local",
"else",
"_pbdir_global",
"shutil",
".",
"copy",
"(",
"fname",
",",
"pbdir",
")",
"init_passband",
"(",
"os",
".",
"path",
".",
"joi... | Install a passband from a local file. This simply copies the file into the
install path - but beware that clearing the installation will clear the
passband as well
If local=False, you must have permissions to access the installation directory | [
"Install",
"a",
"passband",
"from",
"a",
"local",
"file",
".",
"This",
"simply",
"copies",
"the",
"file",
"into",
"the",
"install",
"path",
"-",
"but",
"beware",
"that",
"clearing",
"the",
"installation",
"will",
"clear",
"the",
"passband",
"as",
"well"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/atmospheres/passbands.py#L1161-L1171 | train | 40,056 |
phoebe-project/phoebe2 | phoebe/atmospheres/passbands.py | download_passband | def download_passband(passband, local=True):
"""
Download and install a given passband from the repository.
If local=False, you must have permission to access the installation directory
"""
if passband not in list_online_passbands():
raise ValueError("passband '{}' not available".format(passband))
pbdir = _pbdir_local if local else _pbdir_global
passband_fname = _online_passbands[passband]['fname']
passband_fname_local = os.path.join(pbdir, passband_fname)
url = 'http://github.com/phoebe-project/phoebe2-tables/raw/master/passbands/{}'.format(passband_fname)
logger.info("downloading from {} and installing to {}...".format(url, passband_fname_local))
try:
urllib.urlretrieve(url, passband_fname_local)
except IOError:
raise IOError("unable to download {} passband - check connection".format(passband))
else:
init_passband(passband_fname_local) | python | def download_passband(passband, local=True):
"""
Download and install a given passband from the repository.
If local=False, you must have permission to access the installation directory
"""
if passband not in list_online_passbands():
raise ValueError("passband '{}' not available".format(passband))
pbdir = _pbdir_local if local else _pbdir_global
passband_fname = _online_passbands[passband]['fname']
passband_fname_local = os.path.join(pbdir, passband_fname)
url = 'http://github.com/phoebe-project/phoebe2-tables/raw/master/passbands/{}'.format(passband_fname)
logger.info("downloading from {} and installing to {}...".format(url, passband_fname_local))
try:
urllib.urlretrieve(url, passband_fname_local)
except IOError:
raise IOError("unable to download {} passband - check connection".format(passband))
else:
init_passband(passband_fname_local) | [
"def",
"download_passband",
"(",
"passband",
",",
"local",
"=",
"True",
")",
":",
"if",
"passband",
"not",
"in",
"list_online_passbands",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"passband '{}' not available\"",
".",
"format",
"(",
"passband",
")",
")",
"p... | Download and install a given passband from the repository.
If local=False, you must have permission to access the installation directory | [
"Download",
"and",
"install",
"a",
"given",
"passband",
"from",
"the",
"repository",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/atmospheres/passbands.py#L1186-L1206 | train | 40,057 |
phoebe-project/phoebe2 | phoebe/atmospheres/passbands.py | Passband._planck_deriv | def _planck_deriv(self, lam, Teff):
"""
Computes the derivative of the monochromatic blackbody intensity using
the Planck function.
@lam: wavelength in m
@Teff: effective temperature in K
Returns: the derivative of monochromatic blackbody intensity
"""
expterm = np.exp(self.h*self.c/lam/self.k/Teff)
return 2*self.h*self.c*self.c/self.k/Teff/lam**7 * (expterm-1)**-2 * (self.h*self.c*expterm-5*lam*self.k*Teff*(expterm-1)) | python | def _planck_deriv(self, lam, Teff):
"""
Computes the derivative of the monochromatic blackbody intensity using
the Planck function.
@lam: wavelength in m
@Teff: effective temperature in K
Returns: the derivative of monochromatic blackbody intensity
"""
expterm = np.exp(self.h*self.c/lam/self.k/Teff)
return 2*self.h*self.c*self.c/self.k/Teff/lam**7 * (expterm-1)**-2 * (self.h*self.c*expterm-5*lam*self.k*Teff*(expterm-1)) | [
"def",
"_planck_deriv",
"(",
"self",
",",
"lam",
",",
"Teff",
")",
":",
"expterm",
"=",
"np",
".",
"exp",
"(",
"self",
".",
"h",
"*",
"self",
".",
"c",
"/",
"lam",
"/",
"self",
".",
"k",
"/",
"Teff",
")",
"return",
"2",
"*",
"self",
".",
"h",... | Computes the derivative of the monochromatic blackbody intensity using
the Planck function.
@lam: wavelength in m
@Teff: effective temperature in K
Returns: the derivative of monochromatic blackbody intensity | [
"Computes",
"the",
"derivative",
"of",
"the",
"monochromatic",
"blackbody",
"intensity",
"using",
"the",
"Planck",
"function",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/atmospheres/passbands.py#L326-L338 | train | 40,058 |
phoebe-project/phoebe2 | phoebe/atmospheres/passbands.py | Passband.interpolate_ck2004_ldcoeffs | def interpolate_ck2004_ldcoeffs(self, Teff=5772., logg=4.43, abun=0.0, atm='ck2004', ld_func='power', photon_weighted=False):
"""
Interpolate the passband-stored table of LD model coefficients.
"""
if 'ck2004_ld' not in self.content:
print('Castelli & Kurucz (2004) limb darkening coefficients are not computed yet. Please compute those first.')
return None
if photon_weighted:
table = self._ck2004_ld_photon_grid
else:
table = self._ck2004_ld_energy_grid
if not hasattr(Teff, '__iter__'):
req = np.array(((Teff, logg, abun),))
ld_coeffs = libphoebe.interp(req, self._ck2004_intensity_axes[0:3], table)[0]
else:
req = np.vstack((Teff, logg, abun)).T
ld_coeffs = libphoebe.interp(req, self._ck2004_intensity_axes[0:3], table).T
if ld_func == 'linear':
return ld_coeffs[0:1]
elif ld_func == 'logarithmic':
return ld_coeffs[1:3]
elif ld_func == 'square_root':
return ld_coeffs[3:5]
elif ld_func == 'quadratic':
return ld_coeffs[5:7]
elif ld_func == 'power':
return ld_coeffs[7:11]
elif ld_func == 'all':
return ld_coeffs
else:
print('ld_func=%s is invalid; please choose from [linear, logarithmic, square_root, quadratic, power, all].')
return None | python | def interpolate_ck2004_ldcoeffs(self, Teff=5772., logg=4.43, abun=0.0, atm='ck2004', ld_func='power', photon_weighted=False):
"""
Interpolate the passband-stored table of LD model coefficients.
"""
if 'ck2004_ld' not in self.content:
print('Castelli & Kurucz (2004) limb darkening coefficients are not computed yet. Please compute those first.')
return None
if photon_weighted:
table = self._ck2004_ld_photon_grid
else:
table = self._ck2004_ld_energy_grid
if not hasattr(Teff, '__iter__'):
req = np.array(((Teff, logg, abun),))
ld_coeffs = libphoebe.interp(req, self._ck2004_intensity_axes[0:3], table)[0]
else:
req = np.vstack((Teff, logg, abun)).T
ld_coeffs = libphoebe.interp(req, self._ck2004_intensity_axes[0:3], table).T
if ld_func == 'linear':
return ld_coeffs[0:1]
elif ld_func == 'logarithmic':
return ld_coeffs[1:3]
elif ld_func == 'square_root':
return ld_coeffs[3:5]
elif ld_func == 'quadratic':
return ld_coeffs[5:7]
elif ld_func == 'power':
return ld_coeffs[7:11]
elif ld_func == 'all':
return ld_coeffs
else:
print('ld_func=%s is invalid; please choose from [linear, logarithmic, square_root, quadratic, power, all].')
return None | [
"def",
"interpolate_ck2004_ldcoeffs",
"(",
"self",
",",
"Teff",
"=",
"5772.",
",",
"logg",
"=",
"4.43",
",",
"abun",
"=",
"0.0",
",",
"atm",
"=",
"'ck2004'",
",",
"ld_func",
"=",
"'power'",
",",
"photon_weighted",
"=",
"False",
")",
":",
"if",
"'ck2004_l... | Interpolate the passband-stored table of LD model coefficients. | [
"Interpolate",
"the",
"passband",
"-",
"stored",
"table",
"of",
"LD",
"model",
"coefficients",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/atmospheres/passbands.py#L793-L828 | train | 40,059 |
phoebe-project/phoebe2 | phoebe/atmospheres/passbands.py | Passband.import_wd_atmcof | def import_wd_atmcof(self, plfile, atmfile, wdidx, Nabun=19, Nlogg=11, Npb=25, Nints=4):
"""
Parses WD's atmcof and reads in all Legendre polynomials for the
given passband.
@plfile: path and filename of atmcofplanck.dat
@atmfile: path and filename of atmcof.dat
@wdidx: WD index of the passed passband. This can be automated
but it's not a high priority.
@Nabun: number of metallicity nodes in atmcof.dat. For the 2003 version
the number of nodes is 19.
@Nlogg: number of logg nodes in atmcof.dat. For the 2003 version
the number of nodes is 11.
@Npb: number of passbands in atmcof.dat. For the 2003 version
the number of passbands is 25.
@Nints: number of temperature intervals (input lines) per entry.
For the 2003 version the number of lines is 4.
"""
# Initialize the external atmcof module if necessary:
# PERHAPS WD_DATA SHOULD BE GLOBAL??
self.wd_data = libphoebe.wd_readdata(plfile, atmfile)
# That is all that was necessary for *_extern_planckint() and
# *_extern_atmx() functions. However, we also want to support
# circumventing WD subroutines and use WD tables directly. For
# that, we need to do a bit more work.
# Store the passband index for use in planckint() and atmx():
self.extern_wd_idx = wdidx
# Break up the table along axes and extract a single passband data:
atmtab = np.reshape(self.wd_data['atm_table'], (Nabun, Npb, Nlogg, Nints, -1))
atmtab = atmtab[:, wdidx, :, :, :]
# Finally, reverse the metallicity axis because it is sorted in
# reverse order in atmcof:
self.extern_wd_atmx = atmtab[::-1, :, :, :]
self.content += ['extern_planckint', 'extern_atmx']
self.atmlist += ['extern_planckint', 'extern_atmx'] | python | def import_wd_atmcof(self, plfile, atmfile, wdidx, Nabun=19, Nlogg=11, Npb=25, Nints=4):
"""
Parses WD's atmcof and reads in all Legendre polynomials for the
given passband.
@plfile: path and filename of atmcofplanck.dat
@atmfile: path and filename of atmcof.dat
@wdidx: WD index of the passed passband. This can be automated
but it's not a high priority.
@Nabun: number of metallicity nodes in atmcof.dat. For the 2003 version
the number of nodes is 19.
@Nlogg: number of logg nodes in atmcof.dat. For the 2003 version
the number of nodes is 11.
@Npb: number of passbands in atmcof.dat. For the 2003 version
the number of passbands is 25.
@Nints: number of temperature intervals (input lines) per entry.
For the 2003 version the number of lines is 4.
"""
# Initialize the external atmcof module if necessary:
# PERHAPS WD_DATA SHOULD BE GLOBAL??
self.wd_data = libphoebe.wd_readdata(plfile, atmfile)
# That is all that was necessary for *_extern_planckint() and
# *_extern_atmx() functions. However, we also want to support
# circumventing WD subroutines and use WD tables directly. For
# that, we need to do a bit more work.
# Store the passband index for use in planckint() and atmx():
self.extern_wd_idx = wdidx
# Break up the table along axes and extract a single passband data:
atmtab = np.reshape(self.wd_data['atm_table'], (Nabun, Npb, Nlogg, Nints, -1))
atmtab = atmtab[:, wdidx, :, :, :]
# Finally, reverse the metallicity axis because it is sorted in
# reverse order in atmcof:
self.extern_wd_atmx = atmtab[::-1, :, :, :]
self.content += ['extern_planckint', 'extern_atmx']
self.atmlist += ['extern_planckint', 'extern_atmx'] | [
"def",
"import_wd_atmcof",
"(",
"self",
",",
"plfile",
",",
"atmfile",
",",
"wdidx",
",",
"Nabun",
"=",
"19",
",",
"Nlogg",
"=",
"11",
",",
"Npb",
"=",
"25",
",",
"Nints",
"=",
"4",
")",
":",
"# Initialize the external atmcof module if necessary:",
"# PERHAP... | Parses WD's atmcof and reads in all Legendre polynomials for the
given passband.
@plfile: path and filename of atmcofplanck.dat
@atmfile: path and filename of atmcof.dat
@wdidx: WD index of the passed passband. This can be automated
but it's not a high priority.
@Nabun: number of metallicity nodes in atmcof.dat. For the 2003 version
the number of nodes is 19.
@Nlogg: number of logg nodes in atmcof.dat. For the 2003 version
the number of nodes is 11.
@Npb: number of passbands in atmcof.dat. For the 2003 version
the number of passbands is 25.
@Nints: number of temperature intervals (input lines) per entry.
For the 2003 version the number of lines is 4. | [
"Parses",
"WD",
"s",
"atmcof",
"and",
"reads",
"in",
"all",
"Legendre",
"polynomials",
"for",
"the",
"given",
"passband",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/atmospheres/passbands.py#L830-L869 | train | 40,060 |
phoebe-project/phoebe2 | phoebe/atmospheres/passbands.py | Passband._log10_Inorm_extern_planckint | def _log10_Inorm_extern_planckint(self, Teff):
"""
Internal function to compute normal passband intensities using
the external WD machinery that employs blackbody approximation.
@Teff: effective temperature in K
Returns: log10(Inorm)
"""
log10_Inorm = libphoebe.wd_planckint(Teff, self.extern_wd_idx, self.wd_data["planck_table"])
return log10_Inorm | python | def _log10_Inorm_extern_planckint(self, Teff):
"""
Internal function to compute normal passband intensities using
the external WD machinery that employs blackbody approximation.
@Teff: effective temperature in K
Returns: log10(Inorm)
"""
log10_Inorm = libphoebe.wd_planckint(Teff, self.extern_wd_idx, self.wd_data["planck_table"])
return log10_Inorm | [
"def",
"_log10_Inorm_extern_planckint",
"(",
"self",
",",
"Teff",
")",
":",
"log10_Inorm",
"=",
"libphoebe",
".",
"wd_planckint",
"(",
"Teff",
",",
"self",
".",
"extern_wd_idx",
",",
"self",
".",
"wd_data",
"[",
"\"planck_table\"",
"]",
")",
"return",
"log10_I... | Internal function to compute normal passband intensities using
the external WD machinery that employs blackbody approximation.
@Teff: effective temperature in K
Returns: log10(Inorm) | [
"Internal",
"function",
"to",
"compute",
"normal",
"passband",
"intensities",
"using",
"the",
"external",
"WD",
"machinery",
"that",
"employs",
"blackbody",
"approximation",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/atmospheres/passbands.py#L871-L883 | train | 40,061 |
phoebe-project/phoebe2 | phoebe/atmospheres/passbands.py | Passband._log10_Inorm_extern_atmx | def _log10_Inorm_extern_atmx(self, Teff, logg, abun):
"""
Internal function to compute normal passband intensities using
the external WD machinery that employs model atmospheres and
ramps.
@Teff: effective temperature in K
@logg: surface gravity in cgs
@abun: metallicity in dex, Solar=0.0
Returns: log10(Inorm)
"""
log10_Inorm = libphoebe.wd_atmint(Teff, logg, abun, self.extern_wd_idx, self.wd_data["planck_table"], self.wd_data["atm_table"])
return log10_Inorm | python | def _log10_Inorm_extern_atmx(self, Teff, logg, abun):
"""
Internal function to compute normal passband intensities using
the external WD machinery that employs model atmospheres and
ramps.
@Teff: effective temperature in K
@logg: surface gravity in cgs
@abun: metallicity in dex, Solar=0.0
Returns: log10(Inorm)
"""
log10_Inorm = libphoebe.wd_atmint(Teff, logg, abun, self.extern_wd_idx, self.wd_data["planck_table"], self.wd_data["atm_table"])
return log10_Inorm | [
"def",
"_log10_Inorm_extern_atmx",
"(",
"self",
",",
"Teff",
",",
"logg",
",",
"abun",
")",
":",
"log10_Inorm",
"=",
"libphoebe",
".",
"wd_atmint",
"(",
"Teff",
",",
"logg",
",",
"abun",
",",
"self",
".",
"extern_wd_idx",
",",
"self",
".",
"wd_data",
"["... | Internal function to compute normal passband intensities using
the external WD machinery that employs model atmospheres and
ramps.
@Teff: effective temperature in K
@logg: surface gravity in cgs
@abun: metallicity in dex, Solar=0.0
Returns: log10(Inorm) | [
"Internal",
"function",
"to",
"compute",
"normal",
"passband",
"intensities",
"using",
"the",
"external",
"WD",
"machinery",
"that",
"employs",
"model",
"atmospheres",
"and",
"ramps",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/atmospheres/passbands.py#L885-L900 | train | 40,062 |
driftx/Telephus | telephus/protocol.py | ManagedCassandraClientFactory.set_keyspace | def set_keyspace(self, keyspace):
""" switch all connections to another keyspace """
self.keyspace = keyspace
dfrds = []
for p in self._protos:
dfrds.append(p.submitRequest(ManagedThriftRequest(
'set_keyspace', keyspace)))
return defer.gatherResults(dfrds) | python | def set_keyspace(self, keyspace):
""" switch all connections to another keyspace """
self.keyspace = keyspace
dfrds = []
for p in self._protos:
dfrds.append(p.submitRequest(ManagedThriftRequest(
'set_keyspace', keyspace)))
return defer.gatherResults(dfrds) | [
"def",
"set_keyspace",
"(",
"self",
",",
"keyspace",
")",
":",
"self",
".",
"keyspace",
"=",
"keyspace",
"dfrds",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
".",
"_protos",
":",
"dfrds",
".",
"append",
"(",
"p",
".",
"submitRequest",
"(",
"ManagedThriftR... | switch all connections to another keyspace | [
"switch",
"all",
"connections",
"to",
"another",
"keyspace"
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/protocol.py#L195-L202 | train | 40,063 |
driftx/Telephus | telephus/protocol.py | ManagedCassandraClientFactory.login | def login(self, credentials):
""" authenticate all connections """
dfrds = []
for p in self._protos:
dfrds.append(p.submitRequest(ManagedThriftRequest('login',
ttypes.AuthenticationRequest(credentials=credentials))))
return defer.gatherResults(dfrds) | python | def login(self, credentials):
""" authenticate all connections """
dfrds = []
for p in self._protos:
dfrds.append(p.submitRequest(ManagedThriftRequest('login',
ttypes.AuthenticationRequest(credentials=credentials))))
return defer.gatherResults(dfrds) | [
"def",
"login",
"(",
"self",
",",
"credentials",
")",
":",
"dfrds",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
".",
"_protos",
":",
"dfrds",
".",
"append",
"(",
"p",
".",
"submitRequest",
"(",
"ManagedThriftRequest",
"(",
"'login'",
",",
"ttypes",
".",
... | authenticate all connections | [
"authenticate",
"all",
"connections"
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/protocol.py#L204-L210 | train | 40,064 |
driftx/Telephus | telephus/pool.py | CassandraPoolReconnectorFactory.retry | def retry(self):
"""
Retry this factory's connection. It is assumed that a previous
connection was attempted and failed- either before or after a
successful connection.
"""
if self.connector is None:
raise ValueError("No connector to retry")
if self.service is None:
return
self.connector.connect() | python | def retry(self):
"""
Retry this factory's connection. It is assumed that a previous
connection was attempted and failed- either before or after a
successful connection.
"""
if self.connector is None:
raise ValueError("No connector to retry")
if self.service is None:
return
self.connector.connect() | [
"def",
"retry",
"(",
"self",
")",
":",
"if",
"self",
".",
"connector",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No connector to retry\"",
")",
"if",
"self",
".",
"service",
"is",
"None",
":",
"return",
"self",
".",
"connector",
".",
"connect",
"... | Retry this factory's connection. It is assumed that a previous
connection was attempted and failed- either before or after a
successful connection. | [
"Retry",
"this",
"factory",
"s",
"connection",
".",
"It",
"is",
"assumed",
"that",
"a",
"previous",
"connection",
"was",
"attempted",
"and",
"failed",
"-",
"either",
"before",
"or",
"after",
"a",
"successful",
"connection",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/pool.py#L244-L255 | train | 40,065 |
driftx/Telephus | telephus/pool.py | CassandraPoolReconnectorFactory.prep_connection | def prep_connection(self, creds=None, keyspace=None, node_auto_discovery=True):
"""
Do login and set_keyspace tasks as necessary, and also check this
node's idea of the Cassandra ring. Expects that our connection is
alive.
Return a Deferred that will fire with the ring information, or be
errbacked if something goes wrong.
"""
d = defer.succeed(None)
if creds is not None:
d.addCallback(lambda _: self.my_login(creds))
if keyspace is not None:
d.addCallback(lambda _: self.my_set_keyspace(keyspace))
if node_auto_discovery:
d.addCallback(lambda _: self.my_describe_ring(keyspace))
return d | python | def prep_connection(self, creds=None, keyspace=None, node_auto_discovery=True):
"""
Do login and set_keyspace tasks as necessary, and also check this
node's idea of the Cassandra ring. Expects that our connection is
alive.
Return a Deferred that will fire with the ring information, or be
errbacked if something goes wrong.
"""
d = defer.succeed(None)
if creds is not None:
d.addCallback(lambda _: self.my_login(creds))
if keyspace is not None:
d.addCallback(lambda _: self.my_set_keyspace(keyspace))
if node_auto_discovery:
d.addCallback(lambda _: self.my_describe_ring(keyspace))
return d | [
"def",
"prep_connection",
"(",
"self",
",",
"creds",
"=",
"None",
",",
"keyspace",
"=",
"None",
",",
"node_auto_discovery",
"=",
"True",
")",
":",
"d",
"=",
"defer",
".",
"succeed",
"(",
"None",
")",
"if",
"creds",
"is",
"not",
"None",
":",
"d",
".",... | Do login and set_keyspace tasks as necessary, and also check this
node's idea of the Cassandra ring. Expects that our connection is
alive.
Return a Deferred that will fire with the ring information, or be
errbacked if something goes wrong. | [
"Do",
"login",
"and",
"set_keyspace",
"tasks",
"as",
"necessary",
"and",
"also",
"check",
"this",
"node",
"s",
"idea",
"of",
"the",
"Cassandra",
"ring",
".",
"Expects",
"that",
"our",
"connection",
"is",
"alive",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/pool.py#L257-L276 | train | 40,066 |
driftx/Telephus | telephus/pool.py | CassandraPoolReconnectorFactory.my_pick_non_system_keyspace | def my_pick_non_system_keyspace(self):
"""
Find a keyspace in the cluster which is not 'system', for the purpose
of getting a valid ring view. Can't use 'system' or null.
"""
d = self.my_describe_keyspaces()
def pick_non_system(klist):
for k in klist:
if k.name not in SYSTEM_KEYSPACES:
return k.name
err = NoKeyspacesAvailable("Can't gather information about the "
"Cassandra ring; no non-system "
"keyspaces available")
warn(err)
raise err
d.addCallback(pick_non_system)
return d | python | def my_pick_non_system_keyspace(self):
"""
Find a keyspace in the cluster which is not 'system', for the purpose
of getting a valid ring view. Can't use 'system' or null.
"""
d = self.my_describe_keyspaces()
def pick_non_system(klist):
for k in klist:
if k.name not in SYSTEM_KEYSPACES:
return k.name
err = NoKeyspacesAvailable("Can't gather information about the "
"Cassandra ring; no non-system "
"keyspaces available")
warn(err)
raise err
d.addCallback(pick_non_system)
return d | [
"def",
"my_pick_non_system_keyspace",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"my_describe_keyspaces",
"(",
")",
"def",
"pick_non_system",
"(",
"klist",
")",
":",
"for",
"k",
"in",
"klist",
":",
"if",
"k",
".",
"name",
"not",
"in",
"SYSTEM_KEYSPACES"... | Find a keyspace in the cluster which is not 'system', for the purpose
of getting a valid ring view. Can't use 'system' or null. | [
"Find",
"a",
"keyspace",
"in",
"the",
"cluster",
"which",
"is",
"not",
"system",
"for",
"the",
"purpose",
"of",
"getting",
"a",
"valid",
"ring",
"view",
".",
"Can",
"t",
"use",
"system",
"or",
"null",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/pool.py#L326-L343 | train | 40,067 |
driftx/Telephus | telephus/pool.py | CassandraPoolReconnectorFactory.finish_and_die | def finish_and_die(self):
"""
If there is a request pending, let it finish and be handled, then
disconnect and die. If not, cancel any pending queue requests and
just die.
"""
self.logstate('finish_and_die')
self.stop_working_on_queue()
if self.jobphase != 'pending_request':
self.stopFactory() | python | def finish_and_die(self):
"""
If there is a request pending, let it finish and be handled, then
disconnect and die. If not, cancel any pending queue requests and
just die.
"""
self.logstate('finish_and_die')
self.stop_working_on_queue()
if self.jobphase != 'pending_request':
self.stopFactory() | [
"def",
"finish_and_die",
"(",
"self",
")",
":",
"self",
".",
"logstate",
"(",
"'finish_and_die'",
")",
"self",
".",
"stop_working_on_queue",
"(",
")",
"if",
"self",
".",
"jobphase",
"!=",
"'pending_request'",
":",
"self",
".",
"stopFactory",
"(",
")"
] | If there is a request pending, let it finish and be handled, then
disconnect and die. If not, cancel any pending queue requests and
just die. | [
"If",
"there",
"is",
"a",
"request",
"pending",
"let",
"it",
"finish",
"and",
"be",
"handled",
"then",
"disconnect",
"and",
"die",
".",
"If",
"not",
"cancel",
"any",
"pending",
"queue",
"requests",
"and",
"just",
"die",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/pool.py#L449-L458 | train | 40,068 |
driftx/Telephus | telephus/pool.py | CassandraClusterPool.add_connection_score | def add_connection_score(self, node):
"""
Return a numeric value that determines this node's score for adding
a new connection. A negative value indicates that no connections
should be made to this node for at least that number of seconds.
A value of -inf indicates no connections should be made to this
node for the foreseeable future.
This score should ideally take into account the connectedness of
available nodes, so that those with less current connections will
get more.
"""
# TODO: this should ideally take node history into account
conntime = node.seconds_until_connect_ok()
if conntime > 0:
self.log("not considering %r for new connection; has %r left on "
"connect blackout" % (node, conntime))
return -conntime
numconns = self.num_connectors_to(node)
if numconns >= self.max_connections_per_node:
return float('-Inf')
return sys.maxint - numconns | python | def add_connection_score(self, node):
"""
Return a numeric value that determines this node's score for adding
a new connection. A negative value indicates that no connections
should be made to this node for at least that number of seconds.
A value of -inf indicates no connections should be made to this
node for the foreseeable future.
This score should ideally take into account the connectedness of
available nodes, so that those with less current connections will
get more.
"""
# TODO: this should ideally take node history into account
conntime = node.seconds_until_connect_ok()
if conntime > 0:
self.log("not considering %r for new connection; has %r left on "
"connect blackout" % (node, conntime))
return -conntime
numconns = self.num_connectors_to(node)
if numconns >= self.max_connections_per_node:
return float('-Inf')
return sys.maxint - numconns | [
"def",
"add_connection_score",
"(",
"self",
",",
"node",
")",
":",
"# TODO: this should ideally take node history into account",
"conntime",
"=",
"node",
".",
"seconds_until_connect_ok",
"(",
")",
"if",
"conntime",
">",
"0",
":",
"self",
".",
"log",
"(",
"\"not cons... | Return a numeric value that determines this node's score for adding
a new connection. A negative value indicates that no connections
should be made to this node for at least that number of seconds.
A value of -inf indicates no connections should be made to this
node for the foreseeable future.
This score should ideally take into account the connectedness of
available nodes, so that those with less current connections will
get more. | [
"Return",
"a",
"numeric",
"value",
"that",
"determines",
"this",
"node",
"s",
"score",
"for",
"adding",
"a",
"new",
"connection",
".",
"A",
"negative",
"value",
"indicates",
"that",
"no",
"connections",
"should",
"be",
"made",
"to",
"this",
"node",
"for",
... | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/pool.py#L893-L916 | train | 40,069 |
driftx/Telephus | telephus/pool.py | CassandraClusterPool.resubmit | def resubmit(self, req, keyspace, req_d, retries):
"""
Push this request to the front of the line, just to be a jerk.
"""
self.log('resubmitting %s request' % (req.method,))
self.pushRequest_really(req, keyspace, req_d, retries)
try:
self.request_queue.pending.remove((req, keyspace, req_d, retries))
except ValueError:
# it's already been scooped up
pass
else:
self.request_queue.pending.insert(0, (req, keyspace, req_d, retries)) | python | def resubmit(self, req, keyspace, req_d, retries):
"""
Push this request to the front of the line, just to be a jerk.
"""
self.log('resubmitting %s request' % (req.method,))
self.pushRequest_really(req, keyspace, req_d, retries)
try:
self.request_queue.pending.remove((req, keyspace, req_d, retries))
except ValueError:
# it's already been scooped up
pass
else:
self.request_queue.pending.insert(0, (req, keyspace, req_d, retries)) | [
"def",
"resubmit",
"(",
"self",
",",
"req",
",",
"keyspace",
",",
"req_d",
",",
"retries",
")",
":",
"self",
".",
"log",
"(",
"'resubmitting %s request'",
"%",
"(",
"req",
".",
"method",
",",
")",
")",
"self",
".",
"pushRequest_really",
"(",
"req",
","... | Push this request to the front of the line, just to be a jerk. | [
"Push",
"this",
"request",
"to",
"the",
"front",
"of",
"the",
"line",
"just",
"to",
"be",
"a",
"jerk",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/pool.py#L1154-L1166 | train | 40,070 |
driftx/Telephus | telephus/pool.py | CassandraClusterPool.set_keyspace | def set_keyspace(self, keyspace):
"""
Change the keyspace which will be used for subsequent requests to this
CassandraClusterPool, and return a Deferred that will fire once it can
be verified that connections can successfully use that keyspace.
If something goes wrong trying to change a connection to that keyspace,
the Deferred will errback, and the keyspace to be used for future
requests will not be changed.
Requests made between the time this method is called and the time that
the returned Deferred is fired may be made in either the previous
keyspace or the new keyspace. If you may need to make use of multiple
keyspaces at the same time in the same app, consider using the
specialized CassandraKeyspaceConnection interface provided by the
keyspaceConnection method.
"""
# push a real set_keyspace on some (any) connection; the idea is that
# if it succeeds there, it is likely to succeed everywhere, and vice
# versa. don't bother waiting for all connections to change- some of
# them may be doing long blocking tasks and by the time they're done,
# the keyspace might be changed again anyway
d = self.pushRequest(ManagedThriftRequest('set_keyspace', keyspace))
def store_keyspace(_):
self.keyspace = keyspace
d.addCallback(store_keyspace)
return d | python | def set_keyspace(self, keyspace):
"""
Change the keyspace which will be used for subsequent requests to this
CassandraClusterPool, and return a Deferred that will fire once it can
be verified that connections can successfully use that keyspace.
If something goes wrong trying to change a connection to that keyspace,
the Deferred will errback, and the keyspace to be used for future
requests will not be changed.
Requests made between the time this method is called and the time that
the returned Deferred is fired may be made in either the previous
keyspace or the new keyspace. If you may need to make use of multiple
keyspaces at the same time in the same app, consider using the
specialized CassandraKeyspaceConnection interface provided by the
keyspaceConnection method.
"""
# push a real set_keyspace on some (any) connection; the idea is that
# if it succeeds there, it is likely to succeed everywhere, and vice
# versa. don't bother waiting for all connections to change- some of
# them may be doing long blocking tasks and by the time they're done,
# the keyspace might be changed again anyway
d = self.pushRequest(ManagedThriftRequest('set_keyspace', keyspace))
def store_keyspace(_):
self.keyspace = keyspace
d.addCallback(store_keyspace)
return d | [
"def",
"set_keyspace",
"(",
"self",
",",
"keyspace",
")",
":",
"# push a real set_keyspace on some (any) connection; the idea is that",
"# if it succeeds there, it is likely to succeed everywhere, and vice",
"# versa. don't bother waiting for all connections to change- some of",
"# them may b... | Change the keyspace which will be used for subsequent requests to this
CassandraClusterPool, and return a Deferred that will fire once it can
be verified that connections can successfully use that keyspace.
If something goes wrong trying to change a connection to that keyspace,
the Deferred will errback, and the keyspace to be used for future
requests will not be changed.
Requests made between the time this method is called and the time that
the returned Deferred is fired may be made in either the previous
keyspace or the new keyspace. If you may need to make use of multiple
keyspaces at the same time in the same app, consider using the
specialized CassandraKeyspaceConnection interface provided by the
keyspaceConnection method. | [
"Change",
"the",
"keyspace",
"which",
"will",
"be",
"used",
"for",
"subsequent",
"requests",
"to",
"this",
"CassandraClusterPool",
"and",
"return",
"a",
"Deferred",
"that",
"will",
"fire",
"once",
"it",
"can",
"be",
"verified",
"that",
"connections",
"can",
"s... | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/pool.py#L1168-L1196 | train | 40,071 |
driftx/Telephus | telephus/pool.py | CassandraClusterPool.keyspaceConnection | def keyspaceConnection(self, keyspace, consistency=ConsistencyLevel.ONE):
"""
Return a CassandraClient instance which uses this CassandraClusterPool
by way of a CassandraKeyspaceConnection, so that all requests made
through it are guaranteed to go to the given keyspace, no matter what
other consumers of this pool may do.
"""
conn = CassandraKeyspaceConnection(self, keyspace)
return CassandraClient(conn, consistency=consistency) | python | def keyspaceConnection(self, keyspace, consistency=ConsistencyLevel.ONE):
"""
Return a CassandraClient instance which uses this CassandraClusterPool
by way of a CassandraKeyspaceConnection, so that all requests made
through it are guaranteed to go to the given keyspace, no matter what
other consumers of this pool may do.
"""
conn = CassandraKeyspaceConnection(self, keyspace)
return CassandraClient(conn, consistency=consistency) | [
"def",
"keyspaceConnection",
"(",
"self",
",",
"keyspace",
",",
"consistency",
"=",
"ConsistencyLevel",
".",
"ONE",
")",
":",
"conn",
"=",
"CassandraKeyspaceConnection",
"(",
"self",
",",
"keyspace",
")",
"return",
"CassandraClient",
"(",
"conn",
",",
"consisten... | Return a CassandraClient instance which uses this CassandraClusterPool
by way of a CassandraKeyspaceConnection, so that all requests made
through it are guaranteed to go to the given keyspace, no matter what
other consumers of this pool may do. | [
"Return",
"a",
"CassandraClient",
"instance",
"which",
"uses",
"this",
"CassandraClusterPool",
"by",
"way",
"of",
"a",
"CassandraKeyspaceConnection",
"so",
"that",
"all",
"requests",
"made",
"through",
"it",
"are",
"guaranteed",
"to",
"go",
"to",
"the",
"given",
... | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/pool.py#L1213-L1221 | train | 40,072 |
pre-commit/pre-commit-mirror-maker | pre_commit_mirror_maker/main.py | split_by_commas | def split_by_commas(maybe_s: str) -> Tuple[str, ...]:
"""Split a string by commas, but allow escaped commas.
- If maybe_s is falsey, returns an empty tuple
- Ignore backslashed commas
"""
if not maybe_s:
return ()
parts: List[str] = []
split_by_backslash = maybe_s.split(r'\,')
for split_by_backslash_part in split_by_backslash:
splitby_comma = split_by_backslash_part.split(',')
if parts:
parts[-1] += ',' + splitby_comma[0]
else:
parts.append(splitby_comma[0])
parts.extend(splitby_comma[1:])
return tuple(parts) | python | def split_by_commas(maybe_s: str) -> Tuple[str, ...]:
"""Split a string by commas, but allow escaped commas.
- If maybe_s is falsey, returns an empty tuple
- Ignore backslashed commas
"""
if not maybe_s:
return ()
parts: List[str] = []
split_by_backslash = maybe_s.split(r'\,')
for split_by_backslash_part in split_by_backslash:
splitby_comma = split_by_backslash_part.split(',')
if parts:
parts[-1] += ',' + splitby_comma[0]
else:
parts.append(splitby_comma[0])
parts.extend(splitby_comma[1:])
return tuple(parts) | [
"def",
"split_by_commas",
"(",
"maybe_s",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"if",
"not",
"maybe_s",
":",
"return",
"(",
")",
"parts",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"split_by_backslash",
"=",
"maybe_s",
... | Split a string by commas, but allow escaped commas.
- If maybe_s is falsey, returns an empty tuple
- Ignore backslashed commas | [
"Split",
"a",
"string",
"by",
"commas",
"but",
"allow",
"escaped",
"commas",
".",
"-",
"If",
"maybe_s",
"is",
"falsey",
"returns",
"an",
"empty",
"tuple",
"-",
"Ignore",
"backslashed",
"commas"
] | 8bafa3b87e67d291d5a747f0137b921a170a1723 | https://github.com/pre-commit/pre-commit-mirror-maker/blob/8bafa3b87e67d291d5a747f0137b921a170a1723/pre_commit_mirror_maker/main.py#L12-L28 | train | 40,073 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.multiget_slice | def multiget_slice(self, keys, column_parent, predicate, consistency_level):
"""
Performs a get_slice for column_parent and predicate for the given keys in parallel.
Parameters:
- keys
- column_parent
- predicate
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_multiget_slice(keys, column_parent, predicate, consistency_level)
return d | python | def multiget_slice(self, keys, column_parent, predicate, consistency_level):
"""
Performs a get_slice for column_parent and predicate for the given keys in parallel.
Parameters:
- keys
- column_parent
- predicate
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_multiget_slice(keys, column_parent, predicate, consistency_level)
return d | [
"def",
"multiget_slice",
"(",
"self",
",",
"keys",
",",
"column_parent",
",",
"predicate",
",",
"consistency_level",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferr... | Performs a get_slice for column_parent and predicate for the given keys in parallel.
Parameters:
- keys
- column_parent
- predicate
- consistency_level | [
"Performs",
"a",
"get_slice",
"for",
"column_parent",
"and",
"predicate",
"for",
"the",
"given",
"keys",
"in",
"parallel",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L676-L689 | train | 40,074 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.get_range_slices | def get_range_slices(self, column_parent, predicate, range, consistency_level):
"""
returns a subset of columns for a contiguous range of keys.
Parameters:
- column_parent
- predicate
- range
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_get_range_slices(column_parent, predicate, range, consistency_level)
return d | python | def get_range_slices(self, column_parent, predicate, range, consistency_level):
"""
returns a subset of columns for a contiguous range of keys.
Parameters:
- column_parent
- predicate
- range
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_get_range_slices(column_parent, predicate, range, consistency_level)
return d | [
"def",
"get_range_slices",
"(",
"self",
",",
"column_parent",
",",
"predicate",
",",
"range",
",",
"consistency_level",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Def... | returns a subset of columns for a contiguous range of keys.
Parameters:
- column_parent
- predicate
- range
- consistency_level | [
"returns",
"a",
"subset",
"of",
"columns",
"for",
"a",
"contiguous",
"range",
"of",
"keys",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L770-L783 | train | 40,075 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.get_paged_slice | def get_paged_slice(self, column_family, range, start_column, consistency_level):
"""
returns a range of columns, wrapping to the next rows if necessary to collect max_results.
Parameters:
- column_family
- range
- start_column
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_get_paged_slice(column_family, range, start_column, consistency_level)
return d | python | def get_paged_slice(self, column_family, range, start_column, consistency_level):
"""
returns a range of columns, wrapping to the next rows if necessary to collect max_results.
Parameters:
- column_family
- range
- start_column
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_get_paged_slice(column_family, range, start_column, consistency_level)
return d | [
"def",
"get_paged_slice",
"(",
"self",
",",
"column_family",
",",
"range",
",",
"start_column",
",",
"consistency_level",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"D... | returns a range of columns, wrapping to the next rows if necessary to collect max_results.
Parameters:
- column_family
- range
- start_column
- consistency_level | [
"returns",
"a",
"range",
"of",
"columns",
"wrapping",
"to",
"the",
"next",
"rows",
"if",
"necessary",
"to",
"collect",
"max_results",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L817-L830 | train | 40,076 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.insert | def insert(self, key, column_parent, column, consistency_level):
"""
Insert a Column at the given column_parent.column_family and optional column_parent.super_column.
Parameters:
- key
- column_parent
- column
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_insert(key, column_parent, column, consistency_level)
return d | python | def insert(self, key, column_parent, column, consistency_level):
"""
Insert a Column at the given column_parent.column_family and optional column_parent.super_column.
Parameters:
- key
- column_parent
- column
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_insert(key, column_parent, column, consistency_level)
return d | [
"def",
"insert",
"(",
"self",
",",
"key",
",",
"column_parent",
",",
"column",
",",
"consistency_level",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
... | Insert a Column at the given column_parent.column_family and optional column_parent.super_column.
Parameters:
- key
- column_parent
- column
- consistency_level | [
"Insert",
"a",
"Column",
"at",
"the",
"given",
"column_parent",
".",
"column_family",
"and",
"optional",
"column_parent",
".",
"super_column",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L912-L925 | train | 40,077 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.add | def add(self, key, column_parent, column, consistency_level):
"""
Increment or decrement a counter.
Parameters:
- key
- column_parent
- column
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_add(key, column_parent, column, consistency_level)
return d | python | def add(self, key, column_parent, column, consistency_level):
"""
Increment or decrement a counter.
Parameters:
- key
- column_parent
- column
- consistency_level
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_add(key, column_parent, column, consistency_level)
return d | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"column_parent",
",",
"column",
",",
"consistency_level",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
"... | Increment or decrement a counter.
Parameters:
- key
- column_parent
- column
- consistency_level | [
"Increment",
"or",
"decrement",
"a",
"counter",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L957-L970 | train | 40,078 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.truncate | def truncate(self, cfname):
"""
Truncate will mark and entire column family as deleted.
From the user's perspective a successful call to truncate will result complete data deletion from cfname.
Internally, however, disk space will not be immediatily released, as with all deletes in cassandra, this one
only marks the data as deleted.
The operation succeeds only if all hosts in the cluster at available and will throw an UnavailableException if
some hosts are down.
Parameters:
- cfname
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_truncate(cfname)
return d | python | def truncate(self, cfname):
"""
Truncate will mark and entire column family as deleted.
From the user's perspective a successful call to truncate will result complete data deletion from cfname.
Internally, however, disk space will not be immediatily released, as with all deletes in cassandra, this one
only marks the data as deleted.
The operation succeeds only if all hosts in the cluster at available and will throw an UnavailableException if
some hosts are down.
Parameters:
- cfname
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_truncate(cfname)
return d | [
"def",
"truncate",
"(",
"self",
",",
"cfname",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_truncate",
"(",
"cfname",
")",
... | Truncate will mark and entire column family as deleted.
From the user's perspective a successful call to truncate will result complete data deletion from cfname.
Internally, however, disk space will not be immediatily released, as with all deletes in cassandra, this one
only marks the data as deleted.
The operation succeeds only if all hosts in the cluster at available and will throw an UnavailableException if
some hosts are down.
Parameters:
- cfname | [
"Truncate",
"will",
"mark",
"and",
"entire",
"column",
"family",
"as",
"deleted",
".",
"From",
"the",
"user",
"s",
"perspective",
"a",
"successful",
"call",
"to",
"truncate",
"will",
"result",
"complete",
"data",
"deletion",
"from",
"cfname",
".",
"Internally"... | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1182-L1197 | train | 40,079 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.describe_schema_versions | def describe_schema_versions(self, ):
"""
for each schema version present in the cluster, returns a list of nodes at that version.
hosts that do not respond will be under the key DatabaseDescriptor.INITIAL_VERSION.
the cluster is all on the same version if the size of the map is 1.
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_schema_versions()
return d | python | def describe_schema_versions(self, ):
"""
for each schema version present in the cluster, returns a list of nodes at that version.
hosts that do not respond will be under the key DatabaseDescriptor.INITIAL_VERSION.
the cluster is all on the same version if the size of the map is 1.
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_schema_versions()
return d | [
"def",
"describe_schema_versions",
"(",
"self",
",",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_describe_schema_versions",
"(",
... | for each schema version present in the cluster, returns a list of nodes at that version.
hosts that do not respond will be under the key DatabaseDescriptor.INITIAL_VERSION.
the cluster is all on the same version if the size of the map is 1. | [
"for",
"each",
"schema",
"version",
"present",
"in",
"the",
"cluster",
"returns",
"a",
"list",
"of",
"nodes",
"at",
"that",
"version",
".",
"hosts",
"that",
"do",
"not",
"respond",
"will",
"be",
"under",
"the",
"key",
"DatabaseDescriptor",
".",
"INITIAL_VERS... | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1226-L1235 | train | 40,080 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.describe_keyspaces | def describe_keyspaces(self, ):
"""
list the defined keyspaces in this cluster
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_keyspaces()
return d | python | def describe_keyspaces(self, ):
"""
list the defined keyspaces in this cluster
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_keyspaces()
return d | [
"def",
"describe_keyspaces",
"(",
"self",
",",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_describe_keyspaces",
"(",
")",
"re... | list the defined keyspaces in this cluster | [
"list",
"the",
"defined",
"keyspaces",
"in",
"this",
"cluster"
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1261-L1268 | train | 40,081 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.describe_cluster_name | def describe_cluster_name(self, ):
"""
get the cluster name
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_cluster_name()
return d | python | def describe_cluster_name(self, ):
"""
get the cluster name
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_cluster_name()
return d | [
"def",
"describe_cluster_name",
"(",
"self",
",",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_describe_cluster_name",
"(",
")",... | get the cluster name | [
"get",
"the",
"cluster",
"name"
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1294-L1301 | train | 40,082 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.describe_version | def describe_version(self, ):
"""
get the thrift api version
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_version()
return d | python | def describe_version(self, ):
"""
get the thrift api version
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_version()
return d | [
"def",
"describe_version",
"(",
"self",
",",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_describe_version",
"(",
")",
"return... | get the thrift api version | [
"get",
"the",
"thrift",
"api",
"version"
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1325-L1332 | train | 40,083 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.describe_partitioner | def describe_partitioner(self, ):
"""
returns the partitioner used by this cluster
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_partitioner()
return d | python | def describe_partitioner(self, ):
"""
returns the partitioner used by this cluster
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_partitioner()
return d | [
"def",
"describe_partitioner",
"(",
"self",
",",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_describe_partitioner",
"(",
")",
... | returns the partitioner used by this cluster | [
"returns",
"the",
"partitioner",
"used",
"by",
"this",
"cluster"
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1435-L1442 | train | 40,084 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.describe_snitch | def describe_snitch(self, ):
"""
returns the snitch used by this cluster
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_snitch()
return d | python | def describe_snitch(self, ):
"""
returns the snitch used by this cluster
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_snitch()
return d | [
"def",
"describe_snitch",
"(",
"self",
",",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_describe_snitch",
"(",
")",
"return",... | returns the snitch used by this cluster | [
"returns",
"the",
"snitch",
"used",
"by",
"this",
"cluster"
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1466-L1473 | train | 40,085 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.describe_keyspace | def describe_keyspace(self, keyspace):
"""
describe specified keyspace
Parameters:
- keyspace
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_keyspace(keyspace)
return d | python | def describe_keyspace(self, keyspace):
"""
describe specified keyspace
Parameters:
- keyspace
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_keyspace(keyspace)
return d | [
"def",
"describe_keyspace",
"(",
"self",
",",
"keyspace",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_describe_keyspace",
"(",
... | describe specified keyspace
Parameters:
- keyspace | [
"describe",
"specified",
"keyspace"
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1497-L1507 | train | 40,086 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.trace_next_query | def trace_next_query(self, ):
"""
Enables tracing for the next query in this connection and returns the UUID for that trace session
The next query will be traced idependently of trace probability and the returned UUID can be used to query the trace keyspace
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_trace_next_query()
return d | python | def trace_next_query(self, ):
"""
Enables tracing for the next query in this connection and returns the UUID for that trace session
The next query will be traced idependently of trace probability and the returned UUID can be used to query the trace keyspace
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_trace_next_query()
return d | [
"def",
"trace_next_query",
"(",
"self",
",",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_trace_next_query",
"(",
")",
"return... | Enables tracing for the next query in this connection and returns the UUID for that trace session
The next query will be traced idependently of trace probability and the returned UUID can be used to query the trace keyspace | [
"Enables",
"tracing",
"for",
"the",
"next",
"query",
"in",
"this",
"connection",
"and",
"returns",
"the",
"UUID",
"for",
"that",
"trace",
"session",
"The",
"next",
"query",
"will",
"be",
"traced",
"idependently",
"of",
"trace",
"probability",
"and",
"the",
"... | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1583-L1591 | train | 40,087 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.system_add_column_family | def system_add_column_family(self, cf_def):
"""
adds a column family. returns the new schema id.
Parameters:
- cf_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_add_column_family(cf_def)
return d | python | def system_add_column_family(self, cf_def):
"""
adds a column family. returns the new schema id.
Parameters:
- cf_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_add_column_family(cf_def)
return d | [
"def",
"system_add_column_family",
"(",
"self",
",",
"cf_def",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_system_add_column_fami... | adds a column family. returns the new schema id.
Parameters:
- cf_def | [
"adds",
"a",
"column",
"family",
".",
"returns",
"the",
"new",
"schema",
"id",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1656-L1666 | train | 40,088 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.system_drop_column_family | def system_drop_column_family(self, column_family):
"""
drops a column family. returns the new schema id.
Parameters:
- column_family
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_drop_column_family(column_family)
return d | python | def system_drop_column_family(self, column_family):
"""
drops a column family. returns the new schema id.
Parameters:
- column_family
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_drop_column_family(column_family)
return d | [
"def",
"system_drop_column_family",
"(",
"self",
",",
"column_family",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_system_drop_co... | drops a column family. returns the new schema id.
Parameters:
- column_family | [
"drops",
"a",
"column",
"family",
".",
"returns",
"the",
"new",
"schema",
"id",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1695-L1705 | train | 40,089 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.system_add_keyspace | def system_add_keyspace(self, ks_def):
"""
adds a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- ks_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_add_keyspace(ks_def)
return d | python | def system_add_keyspace(self, ks_def):
"""
adds a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- ks_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_add_keyspace(ks_def)
return d | [
"def",
"system_add_keyspace",
"(",
"self",
",",
"ks_def",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_system_add_keyspace",
"("... | adds a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- ks_def | [
"adds",
"a",
"keyspace",
"and",
"any",
"column",
"families",
"that",
"are",
"part",
"of",
"it",
".",
"returns",
"the",
"new",
"schema",
"id",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1734-L1744 | train | 40,090 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.system_drop_keyspace | def system_drop_keyspace(self, keyspace):
"""
drops a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- keyspace
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_drop_keyspace(keyspace)
return d | python | def system_drop_keyspace(self, keyspace):
"""
drops a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- keyspace
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_drop_keyspace(keyspace)
return d | [
"def",
"system_drop_keyspace",
"(",
"self",
",",
"keyspace",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_system_drop_keyspace",
... | drops a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- keyspace | [
"drops",
"a",
"keyspace",
"and",
"any",
"column",
"families",
"that",
"are",
"part",
"of",
"it",
".",
"returns",
"the",
"new",
"schema",
"id",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1773-L1783 | train | 40,091 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.system_update_keyspace | def system_update_keyspace(self, ks_def):
"""
updates properties of a keyspace. returns the new schema id.
Parameters:
- ks_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_update_keyspace(ks_def)
return d | python | def system_update_keyspace(self, ks_def):
"""
updates properties of a keyspace. returns the new schema id.
Parameters:
- ks_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_update_keyspace(ks_def)
return d | [
"def",
"system_update_keyspace",
"(",
"self",
",",
"ks_def",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_system_update_keyspace",... | updates properties of a keyspace. returns the new schema id.
Parameters:
- ks_def | [
"updates",
"properties",
"of",
"a",
"keyspace",
".",
"returns",
"the",
"new",
"schema",
"id",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1812-L1822 | train | 40,092 |
driftx/Telephus | telephus/cassandra/Cassandra.py | Client.system_update_column_family | def system_update_column_family(self, cf_def):
"""
updates properties of a column family. returns the new schema id.
Parameters:
- cf_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_update_column_family(cf_def)
return d | python | def system_update_column_family(self, cf_def):
"""
updates properties of a column family. returns the new schema id.
Parameters:
- cf_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_update_column_family(cf_def)
return d | [
"def",
"system_update_column_family",
"(",
"self",
",",
"cf_def",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_system_update_colum... | updates properties of a column family. returns the new schema id.
Parameters:
- cf_def | [
"updates",
"properties",
"of",
"a",
"column",
"family",
".",
"returns",
"the",
"new",
"schema",
"id",
"."
] | 860a03a0fafe71605e1a4316dfdd8d0c29094703 | https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1851-L1861 | train | 40,093 |
ttinoco/OPTALG | optalg/lin_solver/__init__.py | new_linsolver | def new_linsolver(name,prop):
"""
Creates a linear solver.
Parameters
----------
name : string
prop : string
Returns
-------
solver : :class:`LinSolver <optalg.lin_solver.LinSolver>`
"""
if name == 'mumps':
return LinSolverMUMPS(prop)
elif name == 'superlu':
return LinSolverSUPERLU(prop)
elif name == 'umfpack':
return LinSolverUMFPACK(prop)
elif name == 'default':
try:
return new_linsolver('mumps',prop)
except ImportError:
return new_linsolver('superlu',prop)
else:
raise ValueError('invalid linear solver name') | python | def new_linsolver(name,prop):
"""
Creates a linear solver.
Parameters
----------
name : string
prop : string
Returns
-------
solver : :class:`LinSolver <optalg.lin_solver.LinSolver>`
"""
if name == 'mumps':
return LinSolverMUMPS(prop)
elif name == 'superlu':
return LinSolverSUPERLU(prop)
elif name == 'umfpack':
return LinSolverUMFPACK(prop)
elif name == 'default':
try:
return new_linsolver('mumps',prop)
except ImportError:
return new_linsolver('superlu',prop)
else:
raise ValueError('invalid linear solver name') | [
"def",
"new_linsolver",
"(",
"name",
",",
"prop",
")",
":",
"if",
"name",
"==",
"'mumps'",
":",
"return",
"LinSolverMUMPS",
"(",
"prop",
")",
"elif",
"name",
"==",
"'superlu'",
":",
"return",
"LinSolverSUPERLU",
"(",
"prop",
")",
"elif",
"name",
"==",
"'... | Creates a linear solver.
Parameters
----------
name : string
prop : string
Returns
-------
solver : :class:`LinSolver <optalg.lin_solver.LinSolver>` | [
"Creates",
"a",
"linear",
"solver",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/__init__.py#L14-L40 | train | 40,094 |
ttinoco/OPTALG | optalg/opt_solver/problem.py | cast_problem | def cast_problem(problem):
"""
Casts problem object with known interface as OptProblem.
Parameters
----------
problem : Object
"""
# Optproblem
if isinstance(problem,OptProblem):
return problem
# Other
else:
# Type Base
if (not hasattr(problem,'G') or
(problem.G.shape[0] == problem.G.shape[1] and
problem.G.shape[0] == problem.G.nnz and
np.all(problem.G.row == problem.G.col) and
np.all(problem.G.data == 1.))):
return create_problem_from_type_base(problem)
# Type A
else:
return create_problem_from_type_A(problem) | python | def cast_problem(problem):
"""
Casts problem object with known interface as OptProblem.
Parameters
----------
problem : Object
"""
# Optproblem
if isinstance(problem,OptProblem):
return problem
# Other
else:
# Type Base
if (not hasattr(problem,'G') or
(problem.G.shape[0] == problem.G.shape[1] and
problem.G.shape[0] == problem.G.nnz and
np.all(problem.G.row == problem.G.col) and
np.all(problem.G.data == 1.))):
return create_problem_from_type_base(problem)
# Type A
else:
return create_problem_from_type_A(problem) | [
"def",
"cast_problem",
"(",
"problem",
")",
":",
"# Optproblem",
"if",
"isinstance",
"(",
"problem",
",",
"OptProblem",
")",
":",
"return",
"problem",
"# Other",
"else",
":",
"# Type Base",
"if",
"(",
"not",
"hasattr",
"(",
"problem",
",",
"'G'",
")",
"or"... | Casts problem object with known interface as OptProblem.
Parameters
----------
problem : Object | [
"Casts",
"problem",
"object",
"with",
"known",
"interface",
"as",
"OptProblem",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/opt_solver/problem.py#L185-L211 | train | 40,095 |
ttinoco/OPTALG | optalg/opt_solver/problem.py | create_problem_from_type_base | def create_problem_from_type_base(problem):
"""
Creates OptProblem from type-base problem.
Parameters
----------
problem : Object
"""
p = OptProblem()
# Init attributes
p.phi = problem.phi
p.gphi = problem.gphi
p.Hphi = problem.Hphi
p.A = problem.A
p.b = problem.b
p.f = problem.f
p.J = problem.J
p.H_combined = problem.H_combined
p.u = problem.u
p.l = problem.l
p.x = problem.x
p.P = None
p.lam = None
p.nu = None
p.mu = None
p.pi = None
p.wrapped_problem = problem
# Methods
def eval(cls,x):
cls.wrapped_problem.eval(x)
cls.phi = cls.wrapped_problem.phi
cls.gphi = cls.wrapped_problem.gphi
cls.Hphi = cls.wrapped_problem.Hphi
cls.f = cls.wrapped_problem.f
cls.J = cls.wrapped_problem.J
def combine_H(cls,coeff,ensure_psd=False):
cls.wrapped_problem.combine_H(coeff,ensure_psd)
cls.H_combined = cls.wrapped_problem.H_combined
p.eval = MethodType(eval,p)
p.combine_H = MethodType(combine_H,p)
# Return
return p | python | def create_problem_from_type_base(problem):
"""
Creates OptProblem from type-base problem.
Parameters
----------
problem : Object
"""
p = OptProblem()
# Init attributes
p.phi = problem.phi
p.gphi = problem.gphi
p.Hphi = problem.Hphi
p.A = problem.A
p.b = problem.b
p.f = problem.f
p.J = problem.J
p.H_combined = problem.H_combined
p.u = problem.u
p.l = problem.l
p.x = problem.x
p.P = None
p.lam = None
p.nu = None
p.mu = None
p.pi = None
p.wrapped_problem = problem
# Methods
def eval(cls,x):
cls.wrapped_problem.eval(x)
cls.phi = cls.wrapped_problem.phi
cls.gphi = cls.wrapped_problem.gphi
cls.Hphi = cls.wrapped_problem.Hphi
cls.f = cls.wrapped_problem.f
cls.J = cls.wrapped_problem.J
def combine_H(cls,coeff,ensure_psd=False):
cls.wrapped_problem.combine_H(coeff,ensure_psd)
cls.H_combined = cls.wrapped_problem.H_combined
p.eval = MethodType(eval,p)
p.combine_H = MethodType(combine_H,p)
# Return
return p | [
"def",
"create_problem_from_type_base",
"(",
"problem",
")",
":",
"p",
"=",
"OptProblem",
"(",
")",
"# Init attributes",
"p",
".",
"phi",
"=",
"problem",
".",
"phi",
"p",
".",
"gphi",
"=",
"problem",
".",
"gphi",
"p",
".",
"Hphi",
"=",
"problem",
".",
... | Creates OptProblem from type-base problem.
Parameters
----------
problem : Object | [
"Creates",
"OptProblem",
"from",
"type",
"-",
"base",
"problem",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/opt_solver/problem.py#L213-L262 | train | 40,096 |
ttinoco/OPTALG | optalg/opt_solver/problem.py | OptProblem.recover_dual_variables | def recover_dual_variables(self,lam,nu,mu,pi):
"""
Recovers dual variables for original problem.
Parameters
----------
lam : ndarray
nu : ndarray
mu : ndarray
pi : ndarray
"""
return lam,nu,mu,pi | python | def recover_dual_variables(self,lam,nu,mu,pi):
"""
Recovers dual variables for original problem.
Parameters
----------
lam : ndarray
nu : ndarray
mu : ndarray
pi : ndarray
"""
return lam,nu,mu,pi | [
"def",
"recover_dual_variables",
"(",
"self",
",",
"lam",
",",
"nu",
",",
"mu",
",",
"pi",
")",
":",
"return",
"lam",
",",
"nu",
",",
"mu",
",",
"pi"
] | Recovers dual variables for original problem.
Parameters
----------
lam : ndarray
nu : ndarray
mu : ndarray
pi : ndarray | [
"Recovers",
"dual",
"variables",
"for",
"original",
"problem",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/opt_solver/problem.py#L89-L101 | train | 40,097 |
ttinoco/OPTALG | optalg/opt_solver/problem.py | OptProblem.get_num_primal_variables | def get_num_primal_variables(self):
"""
Gets number of primal variables.
Returns
-------
num : int
"""
if self.x is not None:
return self.x.size
if self.gphi is not None:
return self.gphi.size
if self.Hphi is not None:
return self.Hphi.shape[0]
if self.A is not None:
return self.A.shape[1]
if self.J is not None:
return self.J.shape[1]
if self.u is not None:
return self.u.size
if self.l is not None:
return self.l.size
return 0 | python | def get_num_primal_variables(self):
"""
Gets number of primal variables.
Returns
-------
num : int
"""
if self.x is not None:
return self.x.size
if self.gphi is not None:
return self.gphi.size
if self.Hphi is not None:
return self.Hphi.shape[0]
if self.A is not None:
return self.A.shape[1]
if self.J is not None:
return self.J.shape[1]
if self.u is not None:
return self.u.size
if self.l is not None:
return self.l.size
return 0 | [
"def",
"get_num_primal_variables",
"(",
"self",
")",
":",
"if",
"self",
".",
"x",
"is",
"not",
"None",
":",
"return",
"self",
".",
"x",
".",
"size",
"if",
"self",
".",
"gphi",
"is",
"not",
"None",
":",
"return",
"self",
".",
"gphi",
".",
"size",
"i... | Gets number of primal variables.
Returns
-------
num : int | [
"Gets",
"number",
"of",
"primal",
"variables",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/opt_solver/problem.py#L103-L126 | train | 40,098 |
ttinoco/OPTALG | optalg/opt_solver/opt_solver.py | OptSolver.get_results | def get_results(self):
"""
Gets results.
Returns
-------
results : dictionary
"""
return {'status': self.status,
'error_msg': self.error_msg,
'k': self.k,
'x': self.x,
'lam': self.lam*self.obj_sca,
'nu': self.nu*self.obj_sca,
'mu': self.mu*self.obj_sca,
'pi': self.pi*self.obj_sca} | python | def get_results(self):
"""
Gets results.
Returns
-------
results : dictionary
"""
return {'status': self.status,
'error_msg': self.error_msg,
'k': self.k,
'x': self.x,
'lam': self.lam*self.obj_sca,
'nu': self.nu*self.obj_sca,
'mu': self.mu*self.obj_sca,
'pi': self.pi*self.obj_sca} | [
"def",
"get_results",
"(",
"self",
")",
":",
"return",
"{",
"'status'",
":",
"self",
".",
"status",
",",
"'error_msg'",
":",
"self",
".",
"error_msg",
",",
"'k'",
":",
"self",
".",
"k",
",",
"'x'",
":",
"self",
".",
"x",
",",
"'lam'",
":",
"self",
... | Gets results.
Returns
-------
results : dictionary | [
"Gets",
"results",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/opt_solver/opt_solver.py#L144-L160 | train | 40,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.