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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
zabuldon/teslajsonpy | teslajsonpy/battery_sensor.py | Battery.update | def update(self):
"""Update the battery state."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data:
self.__battery_level = data['battery_level']
self.__charging_state = data['charging_state'] | python | def update(self):
"""Update the battery state."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data:
self.__battery_level = data['battery_level']
self.__charging_state = data['charging_state'] | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_controller",
".",
"update",
"(",
"self",
".",
"_id",
",",
"wake_if_asleep",
"=",
"False",
")",
"data",
"=",
"self",
".",
"_controller",
".",
"get_charging_params",
"(",
"self",
".",
"_id",
")",
"if... | Update the battery state. | [
"Update",
"the",
"battery",
"state",
"."
] | 673ecdb5c9483160fb1b97e30e62f2c863761c39 | https://github.com/zabuldon/teslajsonpy/blob/673ecdb5c9483160fb1b97e30e62f2c863761c39/teslajsonpy/battery_sensor.py#L44-L50 | train | 39,900 |
zabuldon/teslajsonpy | teslajsonpy/battery_sensor.py | Range.update | def update(self):
"""Update the battery range state."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data:
self.__battery_range = data['battery_range']
self.__est_battery_range = data['est_battery_range']
self.__ideal_battery_range = data['ideal_battery_range']
data = self._controller.get_gui_params(self._id)
if data:
if data['gui_distance_units'] == "mi/hr":
self.measurement = 'LENGTH_MILES'
else:
self.measurement = 'LENGTH_KILOMETERS'
self.__rated = (data['gui_range_display'] == "Rated") | python | def update(self):
"""Update the battery range state."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data:
self.__battery_range = data['battery_range']
self.__est_battery_range = data['est_battery_range']
self.__ideal_battery_range = data['ideal_battery_range']
data = self._controller.get_gui_params(self._id)
if data:
if data['gui_distance_units'] == "mi/hr":
self.measurement = 'LENGTH_MILES'
else:
self.measurement = 'LENGTH_KILOMETERS'
self.__rated = (data['gui_range_display'] == "Rated") | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_controller",
".",
"update",
"(",
"self",
".",
"_id",
",",
"wake_if_asleep",
"=",
"False",
")",
"data",
"=",
"self",
".",
"_controller",
".",
"get_charging_params",
"(",
"self",
".",
"_id",
")",
"if... | Update the battery range state. | [
"Update",
"the",
"battery",
"range",
"state",
"."
] | 673ecdb5c9483160fb1b97e30e62f2c863761c39 | https://github.com/zabuldon/teslajsonpy/blob/673ecdb5c9483160fb1b97e30e62f2c863761c39/teslajsonpy/battery_sensor.py#L94-L108 | train | 39,901 |
zabuldon/teslajsonpy | teslajsonpy/vehicle.py | VehicleDevice.assumed_state | def assumed_state(self):
# pylint: disable=protected-access
"""Return whether the data is from an online vehicle."""
return (not self._controller.car_online[self.id()] and
(self._controller._last_update_time[self.id()] -
self._controller._last_wake_up_time[self.id()] >
self._controller.update_interval)) | python | def assumed_state(self):
# pylint: disable=protected-access
"""Return whether the data is from an online vehicle."""
return (not self._controller.car_online[self.id()] and
(self._controller._last_update_time[self.id()] -
self._controller._last_wake_up_time[self.id()] >
self._controller.update_interval)) | [
"def",
"assumed_state",
"(",
"self",
")",
":",
"# pylint: disable=protected-access",
"return",
"(",
"not",
"self",
".",
"_controller",
".",
"car_online",
"[",
"self",
".",
"id",
"(",
")",
"]",
"and",
"(",
"self",
".",
"_controller",
".",
"_last_update_time",
... | Return whether the data is from an online vehicle. | [
"Return",
"whether",
"the",
"data",
"is",
"from",
"an",
"online",
"vehicle",
"."
] | 673ecdb5c9483160fb1b97e30e62f2c863761c39 | https://github.com/zabuldon/teslajsonpy/blob/673ecdb5c9483160fb1b97e30e62f2c863761c39/teslajsonpy/vehicle.py#L59-L65 | train | 39,902 |
zabuldon/teslajsonpy | teslajsonpy/gps.py | GPS.update | def update(self):
"""Update the current GPS location."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_drive_params(self._id)
if data:
self.__longitude = data['longitude']
self.__latitude = data['latitude']
self.__heading = data['heading']
if self.__longitude and self.__latitude and self.__heading:
self.__location = {'longitude': self.__longitude,
'latitude': self.__latitude,
'heading': self.__heading} | python | def update(self):
"""Update the current GPS location."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_drive_params(self._id)
if data:
self.__longitude = data['longitude']
self.__latitude = data['latitude']
self.__heading = data['heading']
if self.__longitude and self.__latitude and self.__heading:
self.__location = {'longitude': self.__longitude,
'latitude': self.__latitude,
'heading': self.__heading} | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_controller",
".",
"update",
"(",
"self",
".",
"_id",
",",
"wake_if_asleep",
"=",
"False",
")",
"data",
"=",
"self",
".",
"_controller",
".",
"get_drive_params",
"(",
"self",
".",
"_id",
")",
"if",
... | Update the current GPS location. | [
"Update",
"the",
"current",
"GPS",
"location",
"."
] | 673ecdb5c9483160fb1b97e30e62f2c863761c39 | https://github.com/zabuldon/teslajsonpy/blob/673ecdb5c9483160fb1b97e30e62f2c863761c39/teslajsonpy/gps.py#L53-L64 | train | 39,903 |
zabuldon/teslajsonpy | teslajsonpy/gps.py | Odometer.update | def update(self):
"""Update the odometer and the unit of measurement based on GUI."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_state_params(self._id)
if data:
self.__odometer = data['odometer']
data = self._controller.get_gui_params(self._id)
if data:
if data['gui_distance_units'] == "mi/hr":
self.measurement = 'LENGTH_MILES'
else:
self.measurement = 'LENGTH_KILOMETERS'
self.__rated = (data['gui_range_display'] == "Rated") | python | def update(self):
"""Update the odometer and the unit of measurement based on GUI."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_state_params(self._id)
if data:
self.__odometer = data['odometer']
data = self._controller.get_gui_params(self._id)
if data:
if data['gui_distance_units'] == "mi/hr":
self.measurement = 'LENGTH_MILES'
else:
self.measurement = 'LENGTH_KILOMETERS'
self.__rated = (data['gui_range_display'] == "Rated") | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_controller",
".",
"update",
"(",
"self",
".",
"_id",
",",
"wake_if_asleep",
"=",
"False",
")",
"data",
"=",
"self",
".",
"_controller",
".",
"get_state_params",
"(",
"self",
".",
"_id",
")",
"if",
... | Update the odometer and the unit of measurement based on GUI. | [
"Update",
"the",
"odometer",
"and",
"the",
"unit",
"of",
"measurement",
"based",
"on",
"GUI",
"."
] | 673ecdb5c9483160fb1b97e30e62f2c863761c39 | https://github.com/zabuldon/teslajsonpy/blob/673ecdb5c9483160fb1b97e30e62f2c863761c39/teslajsonpy/gps.py#L102-L114 | train | 39,904 |
phoebe-project/phoebe2 | phoebe/parameters/dataset.py | lc | def lc(**kwargs):
"""
Create parameters for a new light curve dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
syn_params, constraints = lc_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += lc_dep(**kwargs).to_list()
#~ obs_params += [FloatArrayParameter(qualifier='flag', value=kwargs.get('flag', []), default_unit=None, description='Signal flag')]
#~ obs_params += [FloatArrayParameter(qualifier='weight', value=kwargs.get('weight', []), default_unit=None, description='Signal weight')]
#~ obs_params += [FloatParameter(qualifier='timeoffset', value=kwargs.get('timeoffset', 0.0), default_unit=u.d, description='Zeropoint date offset for observations')]
#~ obs_params += [FloatParameter(qualifier='statweight', value=kwargs.get('statweight', 0.0), default_unit=None, description='Statistical weight in overall fitting')]
return ParameterSet(obs_params), constraints | python | def lc(**kwargs):
"""
Create parameters for a new light curve dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
syn_params, constraints = lc_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += lc_dep(**kwargs).to_list()
#~ obs_params += [FloatArrayParameter(qualifier='flag', value=kwargs.get('flag', []), default_unit=None, description='Signal flag')]
#~ obs_params += [FloatArrayParameter(qualifier='weight', value=kwargs.get('weight', []), default_unit=None, description='Signal weight')]
#~ obs_params += [FloatParameter(qualifier='timeoffset', value=kwargs.get('timeoffset', 0.0), default_unit=u.d, description='Zeropoint date offset for observations')]
#~ obs_params += [FloatParameter(qualifier='statweight', value=kwargs.get('statweight', 0.0), default_unit=None, description='Statistical weight in overall fitting')]
return ParameterSet(obs_params), constraints | [
"def",
"lc",
"(",
"*",
"*",
"kwargs",
")",
":",
"obs_params",
"=",
"[",
"]",
"syn_params",
",",
"constraints",
"=",
"lc_syn",
"(",
"syn",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"obs_params",
"+=",
"syn_params",
".",
"to_list",
"(",
")",
"#obs_pa... | Create parameters for a new light curve dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s | [
"Create",
"parameters",
"for",
"a",
"new",
"light",
"curve",
"dataset",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/dataset.py#L58-L82 | train | 39,905 |
phoebe-project/phoebe2 | phoebe/parameters/dataset.py | rv | def rv(**kwargs):
"""
Create parameters for a new radial velocity dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
#obs_params += [FloatParameter(qualifier='statweight', value = kwargs.get('statweight', 1.0), default_unit=u.dimensionless_unscaled, description='Statistical weight in overall fitting')]
syn_params, constraints = rv_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += rv_dep(**kwargs).to_list()
return ParameterSet(obs_params), constraints | python | def rv(**kwargs):
"""
Create parameters for a new radial velocity dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
#obs_params += [FloatParameter(qualifier='statweight', value = kwargs.get('statweight', 1.0), default_unit=u.dimensionless_unscaled, description='Statistical weight in overall fitting')]
syn_params, constraints = rv_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += rv_dep(**kwargs).to_list()
return ParameterSet(obs_params), constraints | [
"def",
"rv",
"(",
"*",
"*",
"kwargs",
")",
":",
"obs_params",
"=",
"[",
"]",
"#obs_params += [FloatParameter(qualifier='statweight', value = kwargs.get('statweight', 1.0), default_unit=u.dimensionless_unscaled, description='Statistical weight in overall fitting')]",
"syn_params",
",",
... | Create parameters for a new radial velocity dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s | [
"Create",
"parameters",
"for",
"a",
"new",
"radial",
"velocity",
"dataset",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/dataset.py#L121-L140 | train | 39,906 |
phoebe-project/phoebe2 | phoebe/parameters/dataset.py | lp | def lp(**kwargs):
"""
Create parameters for a new line profile dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
#obs_params += [FloatParameter(qualifier='statweight', value = kwargs.get('statweight', 1.0), default_unit=u.dimensionless_unscaled, description='Statistical weight in overall fitting')]
syn_params, constraints = lp_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += rv_dep(**kwargs).to_list()
return ParameterSet(obs_params), constraints | python | def lp(**kwargs):
"""
Create parameters for a new line profile dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
#obs_params += [FloatParameter(qualifier='statweight', value = kwargs.get('statweight', 1.0), default_unit=u.dimensionless_unscaled, description='Statistical weight in overall fitting')]
syn_params, constraints = lp_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += rv_dep(**kwargs).to_list()
return ParameterSet(obs_params), constraints | [
"def",
"lp",
"(",
"*",
"*",
"kwargs",
")",
":",
"obs_params",
"=",
"[",
"]",
"#obs_params += [FloatParameter(qualifier='statweight', value = kwargs.get('statweight', 1.0), default_unit=u.dimensionless_unscaled, description='Statistical weight in overall fitting')]",
"syn_params",
",",
... | Create parameters for a new line profile dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s | [
"Create",
"parameters",
"for",
"a",
"new",
"line",
"profile",
"dataset",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/dataset.py#L170-L189 | train | 39,907 |
phoebe-project/phoebe2 | phoebe/parameters/dataset.py | etv | def etv(**kwargs):
"""
Create parameters for a new eclipse timing variations dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: default for the values of any of the ParameterSet
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
if not conf.devel:
raise NotImplementedError("'etv' dataset not officially supported for this release. Enable developer mode to test.")
obs_params = []
syn_params, constraints = etv_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += etv_dep(**kwargs).to_list()
return ParameterSet(obs_params), constraints | python | def etv(**kwargs):
"""
Create parameters for a new eclipse timing variations dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: default for the values of any of the ParameterSet
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
if not conf.devel:
raise NotImplementedError("'etv' dataset not officially supported for this release. Enable developer mode to test.")
obs_params = []
syn_params, constraints = etv_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += etv_dep(**kwargs).to_list()
return ParameterSet(obs_params), constraints | [
"def",
"etv",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"conf",
".",
"devel",
":",
"raise",
"NotImplementedError",
"(",
"\"'etv' dataset not officially supported for this release. Enable developer mode to test.\"",
")",
"obs_params",
"=",
"[",
"]",
"syn_params",
... | Create parameters for a new eclipse timing variations dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: default for the values of any of the ParameterSet
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s | [
"Create",
"parameters",
"for",
"a",
"new",
"eclipse",
"timing",
"variations",
"dataset",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/dataset.py#L233-L253 | train | 39,908 |
phoebe-project/phoebe2 | phoebe/parameters/dataset.py | orb | def orb(**kwargs):
"""
Create parameters for a new orbit dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
#~ obs_params += [FloatArrayParameter(qualifier='exptime', value=kwargs.get('exptime', []), default_unit=u.s, description='Signal exposure time')]
#~ obs_params += [FloatArrayParameter(qualifier='flag', value=kwargs.get('flag', []), default_unit=None, description='Signal flag')]
#~ obs_params += [FloatArrayParameter(qualifier='weight', value=kwargs.get('weight', []), default_unit=None, description='Signal weight')]
#~ obs_params += [FloatParameter(qualifier='timeoffset', value=kwargs.get('timeoffset', 0.0), default_unit=u.d, description='Zeropoint date offset for observations')]
#~ obs_params += [FloatParameter(qualifier='statweight', value=kwargs.get('statweight', 0.0), default_unit=None, description='Statistical weight in overall fitting')]
syn_params, constraints = orb_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += orb_dep(**kwargs).to_list()
return ParameterSet(obs_params), [] | python | def orb(**kwargs):
"""
Create parameters for a new orbit dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
#~ obs_params += [FloatArrayParameter(qualifier='exptime', value=kwargs.get('exptime', []), default_unit=u.s, description='Signal exposure time')]
#~ obs_params += [FloatArrayParameter(qualifier='flag', value=kwargs.get('flag', []), default_unit=None, description='Signal flag')]
#~ obs_params += [FloatArrayParameter(qualifier='weight', value=kwargs.get('weight', []), default_unit=None, description='Signal weight')]
#~ obs_params += [FloatParameter(qualifier='timeoffset', value=kwargs.get('timeoffset', 0.0), default_unit=u.d, description='Zeropoint date offset for observations')]
#~ obs_params += [FloatParameter(qualifier='statweight', value=kwargs.get('statweight', 0.0), default_unit=None, description='Statistical weight in overall fitting')]
syn_params, constraints = orb_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
#obs_params += orb_dep(**kwargs).to_list()
return ParameterSet(obs_params), [] | [
"def",
"orb",
"(",
"*",
"*",
"kwargs",
")",
":",
"obs_params",
"=",
"[",
"]",
"#~ obs_params += [FloatArrayParameter(qualifier='exptime', value=kwargs.get('exptime', []), default_unit=u.s, description='Signal exposure time')]",
"#~ obs_params += [FloatArrayParameter(qualifier='flag', value... | Create parameters for a new orbit dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s | [
"Create",
"parameters",
"for",
"a",
"new",
"orbit",
"dataset",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/dataset.py#L291-L316 | train | 39,909 |
phoebe-project/phoebe2 | phoebe/parameters/dataset.py | mesh | def mesh(**kwargs):
"""
Create parameters for a new mesh dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
syn_params, constraints = mesh_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
obs_params += [SelectParameter(qualifier='include_times', value=kwargs.get('include_times', []), description='append to times from the following datasets/time standards', choices=['t0@system'])]
obs_params += [SelectParameter(qualifier='columns', value=kwargs.get('columns', []), description='columns to expose within the mesh', choices=_mesh_columns)]
#obs_params += mesh_dep(**kwargs).to_list()
return ParameterSet(obs_params), constraints | python | def mesh(**kwargs):
"""
Create parameters for a new mesh dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
"""
obs_params = []
syn_params, constraints = mesh_syn(syn=False, **kwargs)
obs_params += syn_params.to_list()
obs_params += [SelectParameter(qualifier='include_times', value=kwargs.get('include_times', []), description='append to times from the following datasets/time standards', choices=['t0@system'])]
obs_params += [SelectParameter(qualifier='columns', value=kwargs.get('columns', []), description='columns to expose within the mesh', choices=_mesh_columns)]
#obs_params += mesh_dep(**kwargs).to_list()
return ParameterSet(obs_params), constraints | [
"def",
"mesh",
"(",
"*",
"*",
"kwargs",
")",
":",
"obs_params",
"=",
"[",
"]",
"syn_params",
",",
"constraints",
"=",
"mesh_syn",
"(",
"syn",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"obs_params",
"+=",
"syn_params",
".",
"to_list",
"(",
")",
"obs... | Create parameters for a new mesh dataset.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_dataset`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s | [
"Create",
"parameters",
"for",
"a",
"new",
"mesh",
"dataset",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/dataset.py#L345-L367 | train | 39,910 |
pinax/pinax-teams | pinax/teams/decorators.py | team_required | def team_required(func=None):
"""
Decorator for views that require a team be supplied wither via a slug in the
url pattern or already set on the request object from the TeamMiddleware
"""
def decorator(view_func):
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
slug = kwargs.pop("slug", None)
if not getattr(request, "team", None):
request.team = get_object_or_404(Team, slug=slug)
return view_func(request, *args, **kwargs)
return _wrapped_view
if func:
return decorator(func)
return decorator | python | def team_required(func=None):
"""
Decorator for views that require a team be supplied wither via a slug in the
url pattern or already set on the request object from the TeamMiddleware
"""
def decorator(view_func):
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
slug = kwargs.pop("slug", None)
if not getattr(request, "team", None):
request.team = get_object_or_404(Team, slug=slug)
return view_func(request, *args, **kwargs)
return _wrapped_view
if func:
return decorator(func)
return decorator | [
"def",
"team_required",
"(",
"func",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_func",
")",
")",
"def",
"_wrapped_view",
"(",
... | Decorator for views that require a team be supplied wither via a slug in the
url pattern or already set on the request object from the TeamMiddleware | [
"Decorator",
"for",
"views",
"that",
"require",
"a",
"team",
"be",
"supplied",
"wither",
"via",
"a",
"slug",
"in",
"the",
"url",
"pattern",
"or",
"already",
"set",
"on",
"the",
"request",
"object",
"from",
"the",
"TeamMiddleware"
] | f8354ba0d32b3979d1dc18f50d23fd0096445ab7 | https://github.com/pinax/pinax-teams/blob/f8354ba0d32b3979d1dc18f50d23fd0096445ab7/pinax/teams/decorators.py#L14-L29 | train | 39,911 |
pinax/pinax-teams | pinax/teams/decorators.py | manager_required | def manager_required(func=None):
"""
Decorator for views that require not only a team but also that a user be
logged in and be the manager or owner of that team.
"""
def decorator(view_func):
@team_required
@login_required
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
role = request.team.role_for(request.user)
if role not in [Membership.ROLE_MANAGER, Membership.ROLE_OWNER]:
raise Http404()
return view_func(request, *args, **kwargs)
return _wrapped_view
if func:
return decorator(func)
return decorator | python | def manager_required(func=None):
"""
Decorator for views that require not only a team but also that a user be
logged in and be the manager or owner of that team.
"""
def decorator(view_func):
@team_required
@login_required
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
role = request.team.role_for(request.user)
if role not in [Membership.ROLE_MANAGER, Membership.ROLE_OWNER]:
raise Http404()
return view_func(request, *args, **kwargs)
return _wrapped_view
if func:
return decorator(func)
return decorator | [
"def",
"manager_required",
"(",
"func",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"team_required",
"@",
"login_required",
"@",
"functools",
".",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_... | Decorator for views that require not only a team but also that a user be
logged in and be the manager or owner of that team. | [
"Decorator",
"for",
"views",
"that",
"require",
"not",
"only",
"a",
"team",
"but",
"also",
"that",
"a",
"user",
"be",
"logged",
"in",
"and",
"be",
"the",
"manager",
"or",
"owner",
"of",
"that",
"team",
"."
] | f8354ba0d32b3979d1dc18f50d23fd0096445ab7 | https://github.com/pinax/pinax-teams/blob/f8354ba0d32b3979d1dc18f50d23fd0096445ab7/pinax/teams/decorators.py#L32-L49 | train | 39,912 |
phoebe-project/phoebe2 | phoebe/backend/backends.py | _create_syns | def _create_syns(b, needed_syns):
"""
Create empty synthetics
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter list needed_syns: list of dictionaries containing kwargs to access
the dataset (dataset, component, kind)
:return: :class:`phoebe.parameters.parameters.ParameterSet` of all new parameters
"""
# needs_mesh = {info['dataset']: info['kind'] for info in needed_syns if info['needs_mesh']}
params = []
for needed_syn in needed_syns:
# print "*** _create_syns needed_syn", needed_syn
# used to be {}_syn
syn_kind = '{}'.format(needed_syn['kind'])
# if needed_syn['kind']=='mesh':
# parameters.dataset.mesh will handle creating the necessary columns
# needed_syn['dataset_fields'] = needs_mesh
# needed_syn['columns'] = b.get_value(qualifier='columns', dataset=needed_syn['dataset'], context='dataset')
# datasets = b.get_value(qualifier='datasets', dataset=needed_syn['dataset'], context='dataset')
# needed_syn['datasets'] = {ds: b.filter(datset=ds, context='dataset').exclude(kind='*_dep').kind for ds in datasets}
# phoebe will compute everything sorted - even if the input times array
# is out of order, so let's make sure the exposed times array is in
# the correct (sorted) order
if 'times' in needed_syn.keys():
needed_syn['times'].sort()
needed_syn['empty_arrays_len'] = len(needed_syn['times'])
these_params, these_constraints = getattr(_dataset, "{}_syn".format(syn_kind.lower()))(**needed_syn)
# TODO: do we need to handle constraints?
these_params = these_params.to_list()
for param in these_params:
if param._dataset is None:
# dataset may be set for mesh columns
param._dataset = needed_syn['dataset']
param._kind = syn_kind
param._component = needed_syn['component']
# reset copy_for... model Parameters should never copy
param._copy_for = {}
# context, model, etc will be handle by the bundle once these are returned
params += these_params
return ParameterSet(params) | python | def _create_syns(b, needed_syns):
"""
Create empty synthetics
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter list needed_syns: list of dictionaries containing kwargs to access
the dataset (dataset, component, kind)
:return: :class:`phoebe.parameters.parameters.ParameterSet` of all new parameters
"""
# needs_mesh = {info['dataset']: info['kind'] for info in needed_syns if info['needs_mesh']}
params = []
for needed_syn in needed_syns:
# print "*** _create_syns needed_syn", needed_syn
# used to be {}_syn
syn_kind = '{}'.format(needed_syn['kind'])
# if needed_syn['kind']=='mesh':
# parameters.dataset.mesh will handle creating the necessary columns
# needed_syn['dataset_fields'] = needs_mesh
# needed_syn['columns'] = b.get_value(qualifier='columns', dataset=needed_syn['dataset'], context='dataset')
# datasets = b.get_value(qualifier='datasets', dataset=needed_syn['dataset'], context='dataset')
# needed_syn['datasets'] = {ds: b.filter(datset=ds, context='dataset').exclude(kind='*_dep').kind for ds in datasets}
# phoebe will compute everything sorted - even if the input times array
# is out of order, so let's make sure the exposed times array is in
# the correct (sorted) order
if 'times' in needed_syn.keys():
needed_syn['times'].sort()
needed_syn['empty_arrays_len'] = len(needed_syn['times'])
these_params, these_constraints = getattr(_dataset, "{}_syn".format(syn_kind.lower()))(**needed_syn)
# TODO: do we need to handle constraints?
these_params = these_params.to_list()
for param in these_params:
if param._dataset is None:
# dataset may be set for mesh columns
param._dataset = needed_syn['dataset']
param._kind = syn_kind
param._component = needed_syn['component']
# reset copy_for... model Parameters should never copy
param._copy_for = {}
# context, model, etc will be handle by the bundle once these are returned
params += these_params
return ParameterSet(params) | [
"def",
"_create_syns",
"(",
"b",
",",
"needed_syns",
")",
":",
"# needs_mesh = {info['dataset']: info['kind'] for info in needed_syns if info['needs_mesh']}",
"params",
"=",
"[",
"]",
"for",
"needed_syn",
"in",
"needed_syns",
":",
"# print \"*** _create_syns needed_syn\", needed_... | Create empty synthetics
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter list needed_syns: list of dictionaries containing kwargs to access
the dataset (dataset, component, kind)
:return: :class:`phoebe.parameters.parameters.ParameterSet` of all new parameters | [
"Create",
"empty",
"synthetics"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/backends.py#L253-L303 | train | 39,913 |
phoebe-project/phoebe2 | phoebe/backend/backends.py | _make_packet | def _make_packet(qualifier, value, time, info, **kwargs):
"""
where kwargs overrides info
"""
packet = {'dataset': kwargs.get('dataset', info['dataset']),
'component': kwargs.get('component', info['component']),
'kind': kwargs.get('kind', info['kind']),
'qualifier': qualifier,
'value': value,
'time': time
}
return packet | python | def _make_packet(qualifier, value, time, info, **kwargs):
"""
where kwargs overrides info
"""
packet = {'dataset': kwargs.get('dataset', info['dataset']),
'component': kwargs.get('component', info['component']),
'kind': kwargs.get('kind', info['kind']),
'qualifier': qualifier,
'value': value,
'time': time
}
return packet | [
"def",
"_make_packet",
"(",
"qualifier",
",",
"value",
",",
"time",
",",
"info",
",",
"*",
"*",
"kwargs",
")",
":",
"packet",
"=",
"{",
"'dataset'",
":",
"kwargs",
".",
"get",
"(",
"'dataset'",
",",
"info",
"[",
"'dataset'",
"]",
")",
",",
"'componen... | where kwargs overrides info | [
"where",
"kwargs",
"overrides",
"info"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/backends.py#L305-L317 | train | 39,914 |
phoebe-project/phoebe2 | phoebe/backend/backends.py | BaseBackend.run_checks | def run_checks(self, b, compute, times=[], **kwargs):
"""
run any sanity checks to make sure the parameters and options are legal
for this backend. If they are not, raise an error here to avoid errors
within the workers.
Any physics-checks that are backend-independent should be in
Bundle.run_checks, and don't need to be repeated here.
This should be subclassed by all backends, otherwise will throw a
NotImplementedError
"""
raise NotImplementedError("run_checks is not implemented by the {} backend".format(self.__class__.__name__)) | python | def run_checks(self, b, compute, times=[], **kwargs):
"""
run any sanity checks to make sure the parameters and options are legal
for this backend. If they are not, raise an error here to avoid errors
within the workers.
Any physics-checks that are backend-independent should be in
Bundle.run_checks, and don't need to be repeated here.
This should be subclassed by all backends, otherwise will throw a
NotImplementedError
"""
raise NotImplementedError("run_checks is not implemented by the {} backend".format(self.__class__.__name__)) | [
"def",
"run_checks",
"(",
"self",
",",
"b",
",",
"compute",
",",
"times",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"run_checks is not implemented by the {} backend\"",
".",
"format",
"(",
"self",
".",
"__class__"... | run any sanity checks to make sure the parameters and options are legal
for this backend. If they are not, raise an error here to avoid errors
within the workers.
Any physics-checks that are backend-independent should be in
Bundle.run_checks, and don't need to be repeated here.
This should be subclassed by all backends, otherwise will throw a
NotImplementedError | [
"run",
"any",
"sanity",
"checks",
"to",
"make",
"sure",
"the",
"parameters",
"and",
"options",
"are",
"legal",
"for",
"this",
"backend",
".",
"If",
"they",
"are",
"not",
"raise",
"an",
"error",
"here",
"to",
"avoid",
"errors",
"within",
"the",
"workers",
... | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/backends.py#L323-L335 | train | 39,915 |
phoebe-project/phoebe2 | phoebe/backend/backends.py | BaseBackend._fill_syns | def _fill_syns(self, new_syns, rpacketlists_per_worker):
"""
rpacket_per_worker is a list of packetlists as returned by _run_chunk
"""
# TODO: move to BaseBackendByDataset or BaseBackend?
logger.debug("rank:{}/{} {}._fill_syns".format(mpi.myrank, mpi.nprocs, self.__class__.__name__))
for packetlists in rpacketlists_per_worker:
# single worker
for packetlist in packetlists:
# single time/dataset
for packet in packetlist:
# single parameter
new_syns.set_value(**packet)
return new_syns | python | def _fill_syns(self, new_syns, rpacketlists_per_worker):
"""
rpacket_per_worker is a list of packetlists as returned by _run_chunk
"""
# TODO: move to BaseBackendByDataset or BaseBackend?
logger.debug("rank:{}/{} {}._fill_syns".format(mpi.myrank, mpi.nprocs, self.__class__.__name__))
for packetlists in rpacketlists_per_worker:
# single worker
for packetlist in packetlists:
# single time/dataset
for packet in packetlist:
# single parameter
new_syns.set_value(**packet)
return new_syns | [
"def",
"_fill_syns",
"(",
"self",
",",
"new_syns",
",",
"rpacketlists_per_worker",
")",
":",
"# TODO: move to BaseBackendByDataset or BaseBackend?",
"logger",
".",
"debug",
"(",
"\"rank:{}/{} {}._fill_syns\"",
".",
"format",
"(",
"mpi",
".",
"myrank",
",",
"mpi",
".",... | rpacket_per_worker is a list of packetlists as returned by _run_chunk | [
"rpacket_per_worker",
"is",
"a",
"list",
"of",
"packetlists",
"as",
"returned",
"by",
"_run_chunk"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/backends.py#L378-L393 | train | 39,916 |
phoebe-project/phoebe2 | phoebe/backend/backends.py | BaseBackend.run | def run(self, b, compute, times=[], **kwargs):
"""
if within mpirun, workers should call _run_worker instead of run
"""
self.run_checks(b, compute, times, **kwargs)
logger.debug("rank:{}/{} calling get_packet_and_syns".format(mpi.myrank, mpi.nprocs))
packet, new_syns = self.get_packet_and_syns(b, compute, times, **kwargs)
if mpi.enabled:
# broadcast the packet to ALL workers
mpi.comm.bcast(packet, root=0)
# now even the master can become a worker and take on a chunk
packet['b'] = b
rpacketlists = self._run_chunk(**packet)
# now receive all packetlists
rpacketlists_per_worker = mpi.comm.gather(rpacketlists, root=0)
else:
rpacketlists_per_worker = [self._run_chunk(**packet)]
return self._fill_syns(new_syns, rpacketlists_per_worker) | python | def run(self, b, compute, times=[], **kwargs):
"""
if within mpirun, workers should call _run_worker instead of run
"""
self.run_checks(b, compute, times, **kwargs)
logger.debug("rank:{}/{} calling get_packet_and_syns".format(mpi.myrank, mpi.nprocs))
packet, new_syns = self.get_packet_and_syns(b, compute, times, **kwargs)
if mpi.enabled:
# broadcast the packet to ALL workers
mpi.comm.bcast(packet, root=0)
# now even the master can become a worker and take on a chunk
packet['b'] = b
rpacketlists = self._run_chunk(**packet)
# now receive all packetlists
rpacketlists_per_worker = mpi.comm.gather(rpacketlists, root=0)
else:
rpacketlists_per_worker = [self._run_chunk(**packet)]
return self._fill_syns(new_syns, rpacketlists_per_worker) | [
"def",
"run",
"(",
"self",
",",
"b",
",",
"compute",
",",
"times",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"run_checks",
"(",
"b",
",",
"compute",
",",
"times",
",",
"*",
"*",
"kwargs",
")",
"logger",
".",
"debug",
"(",
... | if within mpirun, workers should call _run_worker instead of run | [
"if",
"within",
"mpirun",
"workers",
"should",
"call",
"_run_worker",
"instead",
"of",
"run"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/backends.py#L404-L427 | train | 39,917 |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | compute_volume | def compute_volume(sizes, centers, normals):
"""
Compute the numerical volume of a convex mesh
:parameter array sizes: array of sizes of triangles
:parameter array centers: array of centers of triangles (x,y,z)
:parameter array normals: array of normals of triangles (will normalize if not already)
:return: the volume (float)
"""
# the volume of a slanted triangular cone is A_triangle * (r_vec dot norm_vec) / 3.
# TODO: implement normalizing normals into meshing routines (or at least have them supply normal_mags to the mesh)
# TODO: remove this function - should now be returned by the meshing algorithm itself
# although wd method may currently use this
normal_mags = np.linalg.norm(normals, axis=1) #np.sqrt((normals**2).sum(axis=1))
return np.sum(sizes*((centers*normals).sum(axis=1)/normal_mags)/3) | python | def compute_volume(sizes, centers, normals):
"""
Compute the numerical volume of a convex mesh
:parameter array sizes: array of sizes of triangles
:parameter array centers: array of centers of triangles (x,y,z)
:parameter array normals: array of normals of triangles (will normalize if not already)
:return: the volume (float)
"""
# the volume of a slanted triangular cone is A_triangle * (r_vec dot norm_vec) / 3.
# TODO: implement normalizing normals into meshing routines (or at least have them supply normal_mags to the mesh)
# TODO: remove this function - should now be returned by the meshing algorithm itself
# although wd method may currently use this
normal_mags = np.linalg.norm(normals, axis=1) #np.sqrt((normals**2).sum(axis=1))
return np.sum(sizes*((centers*normals).sum(axis=1)/normal_mags)/3) | [
"def",
"compute_volume",
"(",
"sizes",
",",
"centers",
",",
"normals",
")",
":",
"# the volume of a slanted triangular cone is A_triangle * (r_vec dot norm_vec) / 3.",
"# TODO: implement normalizing normals into meshing routines (or at least have them supply normal_mags to the mesh)",
"# TOD... | Compute the numerical volume of a convex mesh
:parameter array sizes: array of sizes of triangles
:parameter array centers: array of centers of triangles (x,y,z)
:parameter array normals: array of normals of triangles (will normalize if not already)
:return: the volume (float) | [
"Compute",
"the",
"numerical",
"volume",
"of",
"a",
"convex",
"mesh"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L13-L30 | train | 39,918 |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | spin_in_system | def spin_in_system(incl, long_an):
"""
Spin in the plane of sky of a star given its inclination and "long_an"
incl - inclination of the star in the plane of sky
long_an - longitude of ascending node (equator) of the star in the plane of sky
Return:
spin - in plane of sky
"""
#print "*** spin_in_system", incl, long_an, np.dot(Rz(long_an), np.dot(Rx(-incl), np.array([0,0,1])))
# Rz(long_an) Rx(incl) [0, 0, 1]
return np.dot(Rz(long_an), np.dot(Rx(-incl), np.array([0.,0.,1.]))) | python | def spin_in_system(incl, long_an):
"""
Spin in the plane of sky of a star given its inclination and "long_an"
incl - inclination of the star in the plane of sky
long_an - longitude of ascending node (equator) of the star in the plane of sky
Return:
spin - in plane of sky
"""
#print "*** spin_in_system", incl, long_an, np.dot(Rz(long_an), np.dot(Rx(-incl), np.array([0,0,1])))
# Rz(long_an) Rx(incl) [0, 0, 1]
return np.dot(Rz(long_an), np.dot(Rx(-incl), np.array([0.,0.,1.]))) | [
"def",
"spin_in_system",
"(",
"incl",
",",
"long_an",
")",
":",
"#print \"*** spin_in_system\", incl, long_an, np.dot(Rz(long_an), np.dot(Rx(-incl), np.array([0,0,1])))",
"# Rz(long_an) Rx(incl) [0, 0, 1]",
"return",
"np",
".",
"dot",
"(",
"Rz",
"(",
"long_an",
")",
",",
"np"... | Spin in the plane of sky of a star given its inclination and "long_an"
incl - inclination of the star in the plane of sky
long_an - longitude of ascending node (equator) of the star in the plane of sky
Return:
spin - in plane of sky | [
"Spin",
"in",
"the",
"plane",
"of",
"sky",
"of",
"a",
"star",
"given",
"its",
"inclination",
"and",
"long_an"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L103-L115 | train | 39,919 |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | spin_in_roche | def spin_in_roche(s, etheta, elongan, eincl):
"""
Transform the spin s of a star on Kerpler orbit with
etheta - true anomaly
elongan - longitude of ascending node
eincl - inclination
from in the plane of sky reference frame into
the Roche reference frame.
"""
# m = Rz(long).Rx(-incl).Rz(theta).Rz(pi)
m = euler_trans_matrix(etheta, elongan, eincl)
return np.dot(m.T, s) | python | def spin_in_roche(s, etheta, elongan, eincl):
"""
Transform the spin s of a star on Kerpler orbit with
etheta - true anomaly
elongan - longitude of ascending node
eincl - inclination
from in the plane of sky reference frame into
the Roche reference frame.
"""
# m = Rz(long).Rx(-incl).Rz(theta).Rz(pi)
m = euler_trans_matrix(etheta, elongan, eincl)
return np.dot(m.T, s) | [
"def",
"spin_in_roche",
"(",
"s",
",",
"etheta",
",",
"elongan",
",",
"eincl",
")",
":",
"# m = Rz(long).Rx(-incl).Rz(theta).Rz(pi)",
"m",
"=",
"euler_trans_matrix",
"(",
"etheta",
",",
"elongan",
",",
"eincl",
")",
"return",
"np",
".",
"dot",
"(",
"m",
"."... | Transform the spin s of a star on Kerpler orbit with
etheta - true anomaly
elongan - longitude of ascending node
eincl - inclination
from in the plane of sky reference frame into
the Roche reference frame. | [
"Transform",
"the",
"spin",
"s",
"of",
"a",
"star",
"on",
"Kerpler",
"orbit",
"with"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L117-L131 | train | 39,920 |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | transform_position_array | def transform_position_array(array, pos, euler, is_normal, reverse=False):
"""
Transform any Nx3 position array by translating to a center-of-mass 'pos'
and applying an euler transformation
:parameter array array: numpy array of Nx3 positions in the original (star)
coordinate frame
:parameter array pos: numpy array with length 3 giving cartesian
coordinates to offset all positions
:parameter array euler: euler angles (etheta, elongan, eincl) in radians
:parameter bool is_normal: whether each entry is a normal vector rather
than position vector. If true, the quantities won't be offset by
'pos'
:return: new positions array with same shape as 'array'.
"""
trans_matrix = euler_trans_matrix(*euler)
if not reverse:
trans_matrix = trans_matrix.T
if isinstance(array, ComputedColumn):
array = array.for_computations
if is_normal:
# then we don't do an offset by the position
return np.dot(np.asarray(array), trans_matrix)
else:
return np.dot(np.asarray(array), trans_matrix) + np.asarray(pos) | python | def transform_position_array(array, pos, euler, is_normal, reverse=False):
"""
Transform any Nx3 position array by translating to a center-of-mass 'pos'
and applying an euler transformation
:parameter array array: numpy array of Nx3 positions in the original (star)
coordinate frame
:parameter array pos: numpy array with length 3 giving cartesian
coordinates to offset all positions
:parameter array euler: euler angles (etheta, elongan, eincl) in radians
:parameter bool is_normal: whether each entry is a normal vector rather
than position vector. If true, the quantities won't be offset by
'pos'
:return: new positions array with same shape as 'array'.
"""
trans_matrix = euler_trans_matrix(*euler)
if not reverse:
trans_matrix = trans_matrix.T
if isinstance(array, ComputedColumn):
array = array.for_computations
if is_normal:
# then we don't do an offset by the position
return np.dot(np.asarray(array), trans_matrix)
else:
return np.dot(np.asarray(array), trans_matrix) + np.asarray(pos) | [
"def",
"transform_position_array",
"(",
"array",
",",
"pos",
",",
"euler",
",",
"is_normal",
",",
"reverse",
"=",
"False",
")",
":",
"trans_matrix",
"=",
"euler_trans_matrix",
"(",
"*",
"euler",
")",
"if",
"not",
"reverse",
":",
"trans_matrix",
"=",
"trans_m... | Transform any Nx3 position array by translating to a center-of-mass 'pos'
and applying an euler transformation
:parameter array array: numpy array of Nx3 positions in the original (star)
coordinate frame
:parameter array pos: numpy array with length 3 giving cartesian
coordinates to offset all positions
:parameter array euler: euler angles (etheta, elongan, eincl) in radians
:parameter bool is_normal: whether each entry is a normal vector rather
than position vector. If true, the quantities won't be offset by
'pos'
:return: new positions array with same shape as 'array'. | [
"Transform",
"any",
"Nx3",
"position",
"array",
"by",
"translating",
"to",
"a",
"center",
"-",
"of",
"-",
"mass",
"pos",
"and",
"applying",
"an",
"euler",
"transformation"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L165-L192 | train | 39,921 |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | transform_velocity_array | def transform_velocity_array(array, pos_array, vel, euler, rotation_vel=(0,0,0)):
"""
Transform any Nx3 velocity vector array by adding the center-of-mass 'vel',
accounting for solid-body rotation, and applying an euler transformation.
:parameter array array: numpy array of Nx3 velocity vectors in the original
(star) coordinate frame
:parameter array pos_array: positions of the elements with respect to the
original (star) coordinate frame. Must be the same shape as 'array'.
:parameter array vel: numpy array with length 3 giving cartesian velocity
offsets in the new (system) coordinate frame
:parameter array euler: euler angles (etheta, elongan, eincl) in radians
:parameter array rotation_vel: vector of the rotation velocity of the star
in the original (star) coordinate frame
:return: new velocity array with same shape as 'array'
"""
trans_matrix = euler_trans_matrix(*euler)
# v_{rot,i} = omega x r_i with omega = rotation_vel
rotation_component = np.cross(rotation_vel, pos_array, axisb=1)
orbital_component = np.asarray(vel)
if isinstance(array, ComputedColumn):
array = array.for_computations
new_vel = np.dot(np.asarray(array)+rotation_component, trans_matrix.T) + orbital_component
return new_vel | python | def transform_velocity_array(array, pos_array, vel, euler, rotation_vel=(0,0,0)):
"""
Transform any Nx3 velocity vector array by adding the center-of-mass 'vel',
accounting for solid-body rotation, and applying an euler transformation.
:parameter array array: numpy array of Nx3 velocity vectors in the original
(star) coordinate frame
:parameter array pos_array: positions of the elements with respect to the
original (star) coordinate frame. Must be the same shape as 'array'.
:parameter array vel: numpy array with length 3 giving cartesian velocity
offsets in the new (system) coordinate frame
:parameter array euler: euler angles (etheta, elongan, eincl) in radians
:parameter array rotation_vel: vector of the rotation velocity of the star
in the original (star) coordinate frame
:return: new velocity array with same shape as 'array'
"""
trans_matrix = euler_trans_matrix(*euler)
# v_{rot,i} = omega x r_i with omega = rotation_vel
rotation_component = np.cross(rotation_vel, pos_array, axisb=1)
orbital_component = np.asarray(vel)
if isinstance(array, ComputedColumn):
array = array.for_computations
new_vel = np.dot(np.asarray(array)+rotation_component, trans_matrix.T) + orbital_component
return new_vel | [
"def",
"transform_velocity_array",
"(",
"array",
",",
"pos_array",
",",
"vel",
",",
"euler",
",",
"rotation_vel",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
")",
":",
"trans_matrix",
"=",
"euler_trans_matrix",
"(",
"*",
"euler",
")",
"# v_{rot,i} = omega x r_i ... | Transform any Nx3 velocity vector array by adding the center-of-mass 'vel',
accounting for solid-body rotation, and applying an euler transformation.
:parameter array array: numpy array of Nx3 velocity vectors in the original
(star) coordinate frame
:parameter array pos_array: positions of the elements with respect to the
original (star) coordinate frame. Must be the same shape as 'array'.
:parameter array vel: numpy array with length 3 giving cartesian velocity
offsets in the new (system) coordinate frame
:parameter array euler: euler angles (etheta, elongan, eincl) in radians
:parameter array rotation_vel: vector of the rotation velocity of the star
in the original (star) coordinate frame
:return: new velocity array with same shape as 'array' | [
"Transform",
"any",
"Nx3",
"velocity",
"vector",
"array",
"by",
"adding",
"the",
"center",
"-",
"of",
"-",
"mass",
"vel",
"accounting",
"for",
"solid",
"-",
"body",
"rotation",
"and",
"applying",
"an",
"euler",
"transformation",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L194-L222 | train | 39,922 |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | wd_grid_to_mesh_dict | def wd_grid_to_mesh_dict(the_grid, q, F, d):
"""
Transform a wd-style mesh to the format used by PHOEBE. Namely this handles
translating vertices from Nx9 to Nx3x3 and creating the array of indices
for each triangle.
:parameter record-array the_grid: output from discretize_wd_style
:parameter float q: mass-ratio (M_this/M_sibling)
:parameter float F: syncpar
:parameter float d: instantaneous unitless separation
:return: the dictionary in PHOEBE's format to be passed to a Mesh class
"""
# WD returns a list of triangles with 9 coordinates (v1x, v1y, v1z, v2x, ...)
triangles_9N = the_grid[:,4:13]
new_mesh = {}
# force the mesh to be computed at centers rather than the PHOEBE default
# of computing at vertices and averaging for the centers. This will
# propogate to all ComputedColumns, which means we'll fill those quanities
# (ie normgrads, velocities) per-triangle.
new_mesh['compute_at_vertices'] = False
# PHOEBE's mesh structure stores vertices in an Nx3 array
new_mesh['vertices'] = triangles_9N.reshape(-1,3)
# and triangles as indices pointing to each of the 3 vertices (Nx3)
new_mesh['triangles'] = np.arange(len(triangles_9N)*3).reshape(-1,3)
new_mesh['centers'] = the_grid[:,0:3]
new_mesh['tnormals'] = the_grid[:,13:16]
norms = np.linalg.norm(new_mesh['tnormals'], axis=1)
new_mesh['normgrads'] = norms
# TODO: do this the right way by dividing along axis=1 (or using np.newaxis as done for multiplying in ComputedColumns)
new_mesh['tnormals'] = np.array([tn/n for tn,n in zip(new_mesh['tnormals'], norms)])
# NOTE: there are no vnormals in wd-style mesh
new_mesh['areas'] = the_grid[:,3]
new_mesh['tareas'] = the_grid[:,18]
# TESTING ONLY - remove this eventually ??? (currently being used
# to test WD-style eclipse detection by using theta and phi (lat and long)
# to determine which triangles are in the same "strip")
new_mesh['thetas'] = the_grid[:,16]
new_mesh['phis'] = the_grid[:,17]
# TODO: get rid of this list comprehension
# grads = np.array([libphoebe.roche_gradOmega_only(q, F, d, c) for c in new_mesh['centers']])
# new_mesh['normgrads'] = np.sqrt(grads[:,0]**2+grads[:,1]**2+grads[:,2]**2)
# new_mesh['normgrads'] = norms #np.linalg.norm(grads, axis=1)
# TODO: actually compute the numerical volume (find old code)
new_mesh['volume'] = compute_volume(new_mesh['areas'], new_mesh['centers'], new_mesh['tnormals'])
# new_mesh['area'] # TODO: compute surface area??? (not sure if needed)
new_mesh['velocities'] = np.zeros(new_mesh['centers'].shape)
return new_mesh | python | def wd_grid_to_mesh_dict(the_grid, q, F, d):
"""
Transform a wd-style mesh to the format used by PHOEBE. Namely this handles
translating vertices from Nx9 to Nx3x3 and creating the array of indices
for each triangle.
:parameter record-array the_grid: output from discretize_wd_style
:parameter float q: mass-ratio (M_this/M_sibling)
:parameter float F: syncpar
:parameter float d: instantaneous unitless separation
:return: the dictionary in PHOEBE's format to be passed to a Mesh class
"""
# WD returns a list of triangles with 9 coordinates (v1x, v1y, v1z, v2x, ...)
triangles_9N = the_grid[:,4:13]
new_mesh = {}
# force the mesh to be computed at centers rather than the PHOEBE default
# of computing at vertices and averaging for the centers. This will
# propogate to all ComputedColumns, which means we'll fill those quanities
# (ie normgrads, velocities) per-triangle.
new_mesh['compute_at_vertices'] = False
# PHOEBE's mesh structure stores vertices in an Nx3 array
new_mesh['vertices'] = triangles_9N.reshape(-1,3)
# and triangles as indices pointing to each of the 3 vertices (Nx3)
new_mesh['triangles'] = np.arange(len(triangles_9N)*3).reshape(-1,3)
new_mesh['centers'] = the_grid[:,0:3]
new_mesh['tnormals'] = the_grid[:,13:16]
norms = np.linalg.norm(new_mesh['tnormals'], axis=1)
new_mesh['normgrads'] = norms
# TODO: do this the right way by dividing along axis=1 (or using np.newaxis as done for multiplying in ComputedColumns)
new_mesh['tnormals'] = np.array([tn/n for tn,n in zip(new_mesh['tnormals'], norms)])
# NOTE: there are no vnormals in wd-style mesh
new_mesh['areas'] = the_grid[:,3]
new_mesh['tareas'] = the_grid[:,18]
# TESTING ONLY - remove this eventually ??? (currently being used
# to test WD-style eclipse detection by using theta and phi (lat and long)
# to determine which triangles are in the same "strip")
new_mesh['thetas'] = the_grid[:,16]
new_mesh['phis'] = the_grid[:,17]
# TODO: get rid of this list comprehension
# grads = np.array([libphoebe.roche_gradOmega_only(q, F, d, c) for c in new_mesh['centers']])
# new_mesh['normgrads'] = np.sqrt(grads[:,0]**2+grads[:,1]**2+grads[:,2]**2)
# new_mesh['normgrads'] = norms #np.linalg.norm(grads, axis=1)
# TODO: actually compute the numerical volume (find old code)
new_mesh['volume'] = compute_volume(new_mesh['areas'], new_mesh['centers'], new_mesh['tnormals'])
# new_mesh['area'] # TODO: compute surface area??? (not sure if needed)
new_mesh['velocities'] = np.zeros(new_mesh['centers'].shape)
return new_mesh | [
"def",
"wd_grid_to_mesh_dict",
"(",
"the_grid",
",",
"q",
",",
"F",
",",
"d",
")",
":",
"# WD returns a list of triangles with 9 coordinates (v1x, v1y, v1z, v2x, ...)",
"triangles_9N",
"=",
"the_grid",
"[",
":",
",",
"4",
":",
"13",
"]",
"new_mesh",
"=",
"{",
"}",... | Transform a wd-style mesh to the format used by PHOEBE. Namely this handles
translating vertices from Nx9 to Nx3x3 and creating the array of indices
for each triangle.
:parameter record-array the_grid: output from discretize_wd_style
:parameter float q: mass-ratio (M_this/M_sibling)
:parameter float F: syncpar
:parameter float d: instantaneous unitless separation
:return: the dictionary in PHOEBE's format to be passed to a Mesh class | [
"Transform",
"a",
"wd",
"-",
"style",
"mesh",
"to",
"the",
"format",
"used",
"by",
"PHOEBE",
".",
"Namely",
"this",
"handles",
"translating",
"vertices",
"from",
"Nx9",
"to",
"Nx3x3",
"and",
"creating",
"the",
"array",
"of",
"indices",
"for",
"each",
"tria... | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L225-L281 | train | 39,923 |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | ComputedColumn.weighted_averages | def weighted_averages(self):
"""
Access to the weighted averages of the values at the vertices for each
triangle based on the weights provided by mesh.weights. This is most
useful for partially visible triangles when using libphoebe's
eclipse detection that returns weights for each vertex.
Note that weights by default are set to 1/3 for each vertex, meaning
that this will provide the same values as :meth:`averages` unless
the weights are overridden within the mesh.
If the quantities are defined at centers instead of vertices, this will
return None.
:return: numpy array or None
"""
if not self.mesh._compute_at_vertices:
return None
vertices_per_triangle = self.vertices_per_triangle
if vertices_per_triangle.ndim==2:
# return np.dot(self.vertices_per_triangle, self.mesh.weights)
return np.sum(vertices_per_triangle*self.mesh.weights, axis=1)
elif vertices_per_triangle.ndim==3:
return np.sum(vertices_per_triangle*self.mesh.weights[:,np.newaxis], axis=1)
else:
raise NotImplementedError | python | def weighted_averages(self):
"""
Access to the weighted averages of the values at the vertices for each
triangle based on the weights provided by mesh.weights. This is most
useful for partially visible triangles when using libphoebe's
eclipse detection that returns weights for each vertex.
Note that weights by default are set to 1/3 for each vertex, meaning
that this will provide the same values as :meth:`averages` unless
the weights are overridden within the mesh.
If the quantities are defined at centers instead of vertices, this will
return None.
:return: numpy array or None
"""
if not self.mesh._compute_at_vertices:
return None
vertices_per_triangle = self.vertices_per_triangle
if vertices_per_triangle.ndim==2:
# return np.dot(self.vertices_per_triangle, self.mesh.weights)
return np.sum(vertices_per_triangle*self.mesh.weights, axis=1)
elif vertices_per_triangle.ndim==3:
return np.sum(vertices_per_triangle*self.mesh.weights[:,np.newaxis], axis=1)
else:
raise NotImplementedError | [
"def",
"weighted_averages",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"mesh",
".",
"_compute_at_vertices",
":",
"return",
"None",
"vertices_per_triangle",
"=",
"self",
".",
"vertices_per_triangle",
"if",
"vertices_per_triangle",
".",
"ndim",
"==",
"2",
":... | Access to the weighted averages of the values at the vertices for each
triangle based on the weights provided by mesh.weights. This is most
useful for partially visible triangles when using libphoebe's
eclipse detection that returns weights for each vertex.
Note that weights by default are set to 1/3 for each vertex, meaning
that this will provide the same values as :meth:`averages` unless
the weights are overridden within the mesh.
If the quantities are defined at centers instead of vertices, this will
return None.
:return: numpy array or None | [
"Access",
"to",
"the",
"weighted",
"averages",
"of",
"the",
"values",
"at",
"the",
"vertices",
"for",
"each",
"triangle",
"based",
"on",
"the",
"weights",
"provided",
"by",
"mesh",
".",
"weights",
".",
"This",
"is",
"most",
"useful",
"for",
"partially",
"v... | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L409-L435 | train | 39,924 |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | Mesh.from_proto | def from_proto(cls, proto_mesh, scale,
pos, vel, euler, euler_vel,
rotation_vel=(0,0,0),
component_com_x=None):
"""
Turn a ProtoMesh into a Mesh scaled and placed in orbit.
Update all geometry fields from the proto reference frame, to the
current system reference frame, given the current position, velocitiy,
euler angles, and rotational velocity of THIS mesh.
:parameter list pos: current position (x, y, z)
:parameter list vel: current velocity (vx, vy, vz)
:parameter list euler: current euler angles (etheta, elongan, eincl)
:parameter list rotation_vel: rotation velocity vector (polar_dir*freq_rot)
"""
mesh = cls(**proto_mesh.items())
mesh._copy_roche_values()
mesh._scale_mesh(scale=scale)
mesh._place_in_orbit(pos, vel, euler, euler_vel, rotation_vel, component_com_x)
return mesh | python | def from_proto(cls, proto_mesh, scale,
pos, vel, euler, euler_vel,
rotation_vel=(0,0,0),
component_com_x=None):
"""
Turn a ProtoMesh into a Mesh scaled and placed in orbit.
Update all geometry fields from the proto reference frame, to the
current system reference frame, given the current position, velocitiy,
euler angles, and rotational velocity of THIS mesh.
:parameter list pos: current position (x, y, z)
:parameter list vel: current velocity (vx, vy, vz)
:parameter list euler: current euler angles (etheta, elongan, eincl)
:parameter list rotation_vel: rotation velocity vector (polar_dir*freq_rot)
"""
mesh = cls(**proto_mesh.items())
mesh._copy_roche_values()
mesh._scale_mesh(scale=scale)
mesh._place_in_orbit(pos, vel, euler, euler_vel, rotation_vel, component_com_x)
return mesh | [
"def",
"from_proto",
"(",
"cls",
",",
"proto_mesh",
",",
"scale",
",",
"pos",
",",
"vel",
",",
"euler",
",",
"euler_vel",
",",
"rotation_vel",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"component_com_x",
"=",
"None",
")",
":",
"mesh",
"=",
"cls"... | Turn a ProtoMesh into a Mesh scaled and placed in orbit.
Update all geometry fields from the proto reference frame, to the
current system reference frame, given the current position, velocitiy,
euler angles, and rotational velocity of THIS mesh.
:parameter list pos: current position (x, y, z)
:parameter list vel: current velocity (vx, vy, vz)
:parameter list euler: current euler angles (etheta, elongan, eincl)
:parameter list rotation_vel: rotation velocity vector (polar_dir*freq_rot) | [
"Turn",
"a",
"ProtoMesh",
"into",
"a",
"Mesh",
"scaled",
"and",
"placed",
"in",
"orbit",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L1245-L1268 | train | 39,925 |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | Meshes.update_columns | def update_columns(self, field, value_dict, inds=None, computed_type=None):
"""
update the columns of all meshes
:parameter str field: name of the mesh columnname
:parameter value_dict: dictionary with component as keys and new
data as values. If value_dict is not a dictionary,
it will be applied to all components
:type value_dict: dict or value (array or float)
"""
if not isinstance(value_dict, dict):
value_dict = {comp_no: value_dict for comp_no in self._dict.keys()}
for comp, value in value_dict.items():
if computed_type is not None:
# then create the ComputedColumn now to override the default value of compute_at_vertices
self._dict[comp]._observables[field] = ComputedColumn(self._dict[comp], compute_at_vertices=computed_type=='vertices')
#print "***", comp, field, inds, value
if inds:
raise NotImplementedError('setting column with indices not yet ported to new meshing')
# self._dict[comp][field][inds] = value
else:
if comp in self._dict.keys():
self._dict[comp][field] = value
else:
meshes = self._dict[self._parent_envelope_of[comp]]
meshes[comp][field] = value | python | def update_columns(self, field, value_dict, inds=None, computed_type=None):
"""
update the columns of all meshes
:parameter str field: name of the mesh columnname
:parameter value_dict: dictionary with component as keys and new
data as values. If value_dict is not a dictionary,
it will be applied to all components
:type value_dict: dict or value (array or float)
"""
if not isinstance(value_dict, dict):
value_dict = {comp_no: value_dict for comp_no in self._dict.keys()}
for comp, value in value_dict.items():
if computed_type is not None:
# then create the ComputedColumn now to override the default value of compute_at_vertices
self._dict[comp]._observables[field] = ComputedColumn(self._dict[comp], compute_at_vertices=computed_type=='vertices')
#print "***", comp, field, inds, value
if inds:
raise NotImplementedError('setting column with indices not yet ported to new meshing')
# self._dict[comp][field][inds] = value
else:
if comp in self._dict.keys():
self._dict[comp][field] = value
else:
meshes = self._dict[self._parent_envelope_of[comp]]
meshes[comp][field] = value | [
"def",
"update_columns",
"(",
"self",
",",
"field",
",",
"value_dict",
",",
"inds",
"=",
"None",
",",
"computed_type",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"value_dict",
",",
"dict",
")",
":",
"value_dict",
"=",
"{",
"comp_no",
":",
"... | update the columns of all meshes
:parameter str field: name of the mesh columnname
:parameter value_dict: dictionary with component as keys and new
data as values. If value_dict is not a dictionary,
it will be applied to all components
:type value_dict: dict or value (array or float) | [
"update",
"the",
"columns",
"of",
"all",
"meshes"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L1507-L1535 | train | 39,926 |
phoebe-project/phoebe2 | phoebe/dynamics/keplerian.py | _true_anomaly | def _true_anomaly(M,ecc,itermax=8):
r"""
Calculation of true and eccentric anomaly in Kepler orbits.
``M`` is the phase of the star, ``ecc`` is the eccentricity
See p.39 of Hilditch, 'An Introduction To Close Binary Stars':
Kepler's equation:
.. math::
E - e\sin E = \frac{2\pi}{P}(t-T)
with :math:`E` the eccentric anomaly. The right hand size denotes the
observed phase :math:`M`. This function returns the true anomaly, which is
the position angle of the star in the orbit (:math:`\theta` in Hilditch'
book). The relationship between the eccentric and true anomaly is as
follows:
.. math::
\tan(\theta/2) = \sqrt{\frac{1+e}{1-e}} \tan(E/2)
@parameter M: phase
@type M: float
@parameter ecc: eccentricity
@type ecc: float
@keyword itermax: maximum number of iterations
@type itermax: integer
@return: eccentric anomaly (E), true anomaly (theta)
@rtype: float,float
"""
# Initial value
Fn = M + ecc*sin(M) + ecc**2/2.*sin(2*M)
# Iterative solving of the transcendent Kepler's equation
for i in range(itermax):
F = Fn
Mn = F-ecc*sin(F)
Fn = F+(M-Mn)/(1.-ecc*cos(F))
keep = F!=0 # take care of zerodivision
if hasattr(F,'__iter__'):
if np.all(abs((Fn-F)[keep]/F[keep])<0.00001):
break
elif (abs((Fn-F)/F)<0.00001):
break
# relationship between true anomaly (theta) and eccentric anomaly (Fn)
true_an = 2.*arctan(sqrt((1.+ecc)/(1.-ecc))*tan(Fn/2.))
return Fn,true_an | python | def _true_anomaly(M,ecc,itermax=8):
r"""
Calculation of true and eccentric anomaly in Kepler orbits.
``M`` is the phase of the star, ``ecc`` is the eccentricity
See p.39 of Hilditch, 'An Introduction To Close Binary Stars':
Kepler's equation:
.. math::
E - e\sin E = \frac{2\pi}{P}(t-T)
with :math:`E` the eccentric anomaly. The right hand size denotes the
observed phase :math:`M`. This function returns the true anomaly, which is
the position angle of the star in the orbit (:math:`\theta` in Hilditch'
book). The relationship between the eccentric and true anomaly is as
follows:
.. math::
\tan(\theta/2) = \sqrt{\frac{1+e}{1-e}} \tan(E/2)
@parameter M: phase
@type M: float
@parameter ecc: eccentricity
@type ecc: float
@keyword itermax: maximum number of iterations
@type itermax: integer
@return: eccentric anomaly (E), true anomaly (theta)
@rtype: float,float
"""
# Initial value
Fn = M + ecc*sin(M) + ecc**2/2.*sin(2*M)
# Iterative solving of the transcendent Kepler's equation
for i in range(itermax):
F = Fn
Mn = F-ecc*sin(F)
Fn = F+(M-Mn)/(1.-ecc*cos(F))
keep = F!=0 # take care of zerodivision
if hasattr(F,'__iter__'):
if np.all(abs((Fn-F)[keep]/F[keep])<0.00001):
break
elif (abs((Fn-F)/F)<0.00001):
break
# relationship between true anomaly (theta) and eccentric anomaly (Fn)
true_an = 2.*arctan(sqrt((1.+ecc)/(1.-ecc))*tan(Fn/2.))
return Fn,true_an | [
"def",
"_true_anomaly",
"(",
"M",
",",
"ecc",
",",
"itermax",
"=",
"8",
")",
":",
"# Initial value",
"Fn",
"=",
"M",
"+",
"ecc",
"*",
"sin",
"(",
"M",
")",
"+",
"ecc",
"**",
"2",
"/",
"2.",
"*",
"sin",
"(",
"2",
"*",
"M",
")",
"# Iterative solv... | r"""
Calculation of true and eccentric anomaly in Kepler orbits.
``M`` is the phase of the star, ``ecc`` is the eccentricity
See p.39 of Hilditch, 'An Introduction To Close Binary Stars':
Kepler's equation:
.. math::
E - e\sin E = \frac{2\pi}{P}(t-T)
with :math:`E` the eccentric anomaly. The right hand size denotes the
observed phase :math:`M`. This function returns the true anomaly, which is
the position angle of the star in the orbit (:math:`\theta` in Hilditch'
book). The relationship between the eccentric and true anomaly is as
follows:
.. math::
\tan(\theta/2) = \sqrt{\frac{1+e}{1-e}} \tan(E/2)
@parameter M: phase
@type M: float
@parameter ecc: eccentricity
@type ecc: float
@keyword itermax: maximum number of iterations
@type itermax: integer
@return: eccentric anomaly (E), true anomaly (theta)
@rtype: float,float | [
"r",
"Calculation",
"of",
"true",
"and",
"eccentric",
"anomaly",
"in",
"Kepler",
"orbits",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/dynamics/keplerian.py#L394-L445 | train | 39,927 |
phoebe-project/phoebe2 | phoebe/parameters/feature.py | spot | def spot(feature, **kwargs):
"""
Create parameters for a spot
Generally, this will be used as input to the method argument in
:meth:`phoebe.frontend.bundle.Bundle.add_feature`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet`
"""
params = []
params += [FloatParameter(qualifier="colat", value=kwargs.get('colat', 0.0), default_unit=u.deg, description='Colatitude of the center of the spot wrt spin axes')]
params += [FloatParameter(qualifier="long", value=kwargs.get('long', 0.0), default_unit=u.deg, description='Longitude of the center of the spot wrt spin axis')]
params += [FloatParameter(qualifier='radius', value=kwargs.get('radius', 1.0), default_unit=u.deg, description='Angular radius of the spot')]
# params += [FloatParameter(qualifier='area', value=kwargs.get('area', 1.0), default_unit=u.solRad, description='Surface area of the spot')]
params += [FloatParameter(qualifier='relteff', value=kwargs.get('relteff', 1.0), limits=(0.,None), default_unit=u.dimensionless_unscaled, description='Temperature of the spot relative to the intrinsic temperature')]
# params += [FloatParameter(qualifier='teff', value=kwargs.get('teff', 10000), default_unit=u.K, description='Temperature of the spot')]
constraints = []
return ParameterSet(params), constraints | python | def spot(feature, **kwargs):
"""
Create parameters for a spot
Generally, this will be used as input to the method argument in
:meth:`phoebe.frontend.bundle.Bundle.add_feature`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet`
"""
params = []
params += [FloatParameter(qualifier="colat", value=kwargs.get('colat', 0.0), default_unit=u.deg, description='Colatitude of the center of the spot wrt spin axes')]
params += [FloatParameter(qualifier="long", value=kwargs.get('long', 0.0), default_unit=u.deg, description='Longitude of the center of the spot wrt spin axis')]
params += [FloatParameter(qualifier='radius', value=kwargs.get('radius', 1.0), default_unit=u.deg, description='Angular radius of the spot')]
# params += [FloatParameter(qualifier='area', value=kwargs.get('area', 1.0), default_unit=u.solRad, description='Surface area of the spot')]
params += [FloatParameter(qualifier='relteff', value=kwargs.get('relteff', 1.0), limits=(0.,None), default_unit=u.dimensionless_unscaled, description='Temperature of the spot relative to the intrinsic temperature')]
# params += [FloatParameter(qualifier='teff', value=kwargs.get('teff', 10000), default_unit=u.K, description='Temperature of the spot')]
constraints = []
return ParameterSet(params), constraints | [
"def",
"spot",
"(",
"feature",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"[",
"]",
"params",
"+=",
"[",
"FloatParameter",
"(",
"qualifier",
"=",
"\"colat\"",
",",
"value",
"=",
"kwargs",
".",
"get",
"(",
"'colat'",
",",
"0.0",
")",
",",
"de... | Create parameters for a spot
Generally, this will be used as input to the method argument in
:meth:`phoebe.frontend.bundle.Bundle.add_feature`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` | [
"Create",
"parameters",
"for",
"a",
"spot"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/feature.py#L17-L40 | train | 39,928 |
phoebe-project/phoebe2 | phoebe/parameters/feature.py | pulsation | def pulsation(feature, **kwargs):
"""
Create parameters for a pulsation feature
Generally, this will be used as input to the method argument in
:meth:`phoebe.frontend.bundle.Bundle.add_feature`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet`
"""
if not conf.devel:
raise NotImplementedError("'pulsation' feature not officially supported for this release. Enable developer mode to test.")
params = []
params += [FloatParameter(qualifier='radamp', value=kwargs.get('radamp', 0.1), default_unit=u.dimensionless_unscaled, description='Relative radial amplitude of the pulsations')]
params += [FloatParameter(qualifier='freq', value=kwargs.get('freq', 1.0), default_unit=u.d**-1, description='Frequency of the pulsations')]
params += [IntParameter(qualifier='l', value=kwargs.get('l', 0), default_unit=u.dimensionless_unscaled, description='Non-radial degree l')]
params += [IntParameter(qualifier='m', value=kwargs.get('m', 0), default_unit=u.dimensionless_unscaled, description='Azimuthal order m')]
params += [BoolParameter(qualifier='teffext', value=kwargs.get('teffext', False), description='Switch to denote whether Teffs are provided by the external code')]
constraints = []
return ParameterSet(params), constraints | python | def pulsation(feature, **kwargs):
"""
Create parameters for a pulsation feature
Generally, this will be used as input to the method argument in
:meth:`phoebe.frontend.bundle.Bundle.add_feature`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet`
"""
if not conf.devel:
raise NotImplementedError("'pulsation' feature not officially supported for this release. Enable developer mode to test.")
params = []
params += [FloatParameter(qualifier='radamp', value=kwargs.get('radamp', 0.1), default_unit=u.dimensionless_unscaled, description='Relative radial amplitude of the pulsations')]
params += [FloatParameter(qualifier='freq', value=kwargs.get('freq', 1.0), default_unit=u.d**-1, description='Frequency of the pulsations')]
params += [IntParameter(qualifier='l', value=kwargs.get('l', 0), default_unit=u.dimensionless_unscaled, description='Non-radial degree l')]
params += [IntParameter(qualifier='m', value=kwargs.get('m', 0), default_unit=u.dimensionless_unscaled, description='Azimuthal order m')]
params += [BoolParameter(qualifier='teffext', value=kwargs.get('teffext', False), description='Switch to denote whether Teffs are provided by the external code')]
constraints = []
return ParameterSet(params), constraints | [
"def",
"pulsation",
"(",
"feature",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"conf",
".",
"devel",
":",
"raise",
"NotImplementedError",
"(",
"\"'pulsation' feature not officially supported for this release. Enable developer mode to test.\"",
")",
"params",
"=",
... | Create parameters for a pulsation feature
Generally, this will be used as input to the method argument in
:meth:`phoebe.frontend.bundle.Bundle.add_feature`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` | [
"Create",
"parameters",
"for",
"a",
"pulsation",
"feature"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/feature.py#L42-L67 | train | 39,929 |
phoebe-project/phoebe2 | phoebe/frontend/io.py | load_lc_data | def load_lc_data(filename, indep, dep, indweight=None, mzero=None, dir='./'):
"""
load dictionary with lc data
"""
if '/' in filename:
path, filename = os.path.split(filename)
else:
# TODO: this needs to change to be directory of the .phoebe file
path = dir
load_file = os.path.join(path, filename)
lcdata = np.loadtxt(load_file)
ncol = len(lcdata[0])
if dep == 'Magnitude':
mag = lcdata[:,1]
flux = 10**(-0.4*(mag-mzero))
lcdata[:,1] = flux
d = {}
d['phoebe_lc_time'] = lcdata[:,0]
d['phoebe_lc_flux'] = lcdata[:,1]
if indweight=="Standard deviation":
if ncol >= 3:
d['phoebe_lc_sigmalc'] = lcdata[:,2]
else:
logger.warning('A sigma column was mentioned in the .phoebe file but is not present in the lc data file')
elif indweight =="Standard weight":
if ncol >= 3:
sigma = np.sqrt(1/lcdata[:,2])
d['phoebe_lc_sigmalc'] = sigma
logger.warning('Standard weight has been converted to Standard deviation.')
else:
logger.warning('A sigma column was mentioned in the .phoebe file but is not present in the lc data file')
else:
logger.warning('Phoebe 2 currently only supports standard deviaton')
# dataset.set_value(check_visible=False, **d)
return d | python | def load_lc_data(filename, indep, dep, indweight=None, mzero=None, dir='./'):
"""
load dictionary with lc data
"""
if '/' in filename:
path, filename = os.path.split(filename)
else:
# TODO: this needs to change to be directory of the .phoebe file
path = dir
load_file = os.path.join(path, filename)
lcdata = np.loadtxt(load_file)
ncol = len(lcdata[0])
if dep == 'Magnitude':
mag = lcdata[:,1]
flux = 10**(-0.4*(mag-mzero))
lcdata[:,1] = flux
d = {}
d['phoebe_lc_time'] = lcdata[:,0]
d['phoebe_lc_flux'] = lcdata[:,1]
if indweight=="Standard deviation":
if ncol >= 3:
d['phoebe_lc_sigmalc'] = lcdata[:,2]
else:
logger.warning('A sigma column was mentioned in the .phoebe file but is not present in the lc data file')
elif indweight =="Standard weight":
if ncol >= 3:
sigma = np.sqrt(1/lcdata[:,2])
d['phoebe_lc_sigmalc'] = sigma
logger.warning('Standard weight has been converted to Standard deviation.')
else:
logger.warning('A sigma column was mentioned in the .phoebe file but is not present in the lc data file')
else:
logger.warning('Phoebe 2 currently only supports standard deviaton')
# dataset.set_value(check_visible=False, **d)
return d | [
"def",
"load_lc_data",
"(",
"filename",
",",
"indep",
",",
"dep",
",",
"indweight",
"=",
"None",
",",
"mzero",
"=",
"None",
",",
"dir",
"=",
"'./'",
")",
":",
"if",
"'/'",
"in",
"filename",
":",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",... | load dictionary with lc data | [
"load",
"dictionary",
"with",
"lc",
"data"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/io.py#L242-L282 | train | 39,930 |
phoebe-project/phoebe2 | phoebe/frontend/io.py | load_rv_data | def load_rv_data(filename, indep, dep, indweight=None, dir='./'):
"""
load dictionary with rv data.
"""
if '/' in filename:
path, filename = os.path.split(filename)
else:
path = dir
load_file = os.path.join(path, filename)
rvdata = np.loadtxt(load_file)
d ={}
d['phoebe_rv_time'] = rvdata[:,0]
d['phoebe_rv_vel'] = rvdata[:,1]
ncol = len(rvdata[0])
if indweight=="Standard deviation":
if ncol >= 3:
d['phoebe_rv_sigmarv'] = rvdata[:,2]
else:
logger.warning('A sigma column is mentioned in the .phoebe file but is not present in the rv data file')
elif indweight =="Standard weight":
if ncol >= 3:
sigma = np.sqrt(1/rvdata[:,2])
d['phoebe_rv_sigmarv'] = sigma
logger.warning('Standard weight has been converted to Standard deviation.')
else:
logger.warning('Phoebe 2 currently only supports standard deviaton')
return d | python | def load_rv_data(filename, indep, dep, indweight=None, dir='./'):
"""
load dictionary with rv data.
"""
if '/' in filename:
path, filename = os.path.split(filename)
else:
path = dir
load_file = os.path.join(path, filename)
rvdata = np.loadtxt(load_file)
d ={}
d['phoebe_rv_time'] = rvdata[:,0]
d['phoebe_rv_vel'] = rvdata[:,1]
ncol = len(rvdata[0])
if indweight=="Standard deviation":
if ncol >= 3:
d['phoebe_rv_sigmarv'] = rvdata[:,2]
else:
logger.warning('A sigma column is mentioned in the .phoebe file but is not present in the rv data file')
elif indweight =="Standard weight":
if ncol >= 3:
sigma = np.sqrt(1/rvdata[:,2])
d['phoebe_rv_sigmarv'] = sigma
logger.warning('Standard weight has been converted to Standard deviation.')
else:
logger.warning('Phoebe 2 currently only supports standard deviaton')
return d | [
"def",
"load_rv_data",
"(",
"filename",
",",
"indep",
",",
"dep",
",",
"indweight",
"=",
"None",
",",
"dir",
"=",
"'./'",
")",
":",
"if",
"'/'",
"in",
"filename",
":",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
... | load dictionary with rv data. | [
"load",
"dictionary",
"with",
"rv",
"data",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/io.py#L284-L317 | train | 39,931 |
phoebe-project/phoebe2 | phoebe/frontend/io.py | det_dataset | def det_dataset(eb, passband, dataid, comp, time):
"""
Since RV datasets can have values related to each component in phoebe2, but are component specific in phoebe1
, it is important to determine which dataset to add parameters to. This function will do that.
eb - bundle
rvpt - relevant phoebe 1 parameters
"""
rvs = eb.get_dataset(kind='rv').datasets
#first check to see if there are currently in RV datasets
if dataid == 'Undefined':
dataid = None
# if len(rvs) == 0:
#if there isn't we add one the easy part
try:
eb._check_label(dataid)
rv_dataset = eb.add_dataset('rv', dataset=dataid, times=[])
except ValueError:
logger.warning("The name picked for the radial velocity curve is forbidden. Applying default name instead")
rv_dataset = eb.add_dataset('rv', times=[])
# else:
# #now we have to determine if we add to an existing dataset or make a new one
# rvs = eb.get_dataset(kind='rv').datasets
# found = False
# #set the component of the companion
#
# if comp == 'primary':
# comp_o = 'primary'
# else:
# comp_o = 'secondary'
# for x in rvs:
# test_dataset = eb.get_dataset(x, check_visible=False)
#
#
# if len(test_dataset.get_value(qualifier='rvs', component=comp_o, check_visible=False)) == 0: #so at least it has an empty spot now check against filter and length
# # removing reference to time_o. If there are no rvs there should be no times
# # time_o = test_dataset.get_value('times', component=comp_o)
# passband_o = test_dataset.get_value('passband')
#
# # if np.all(time_o == time) and (passband == passband_o):
# if (passband == passband_o):
# rv_dataset = test_dataset
# found = True
#
# if not found:
# try:
# eb._check_label(dataid)
#
# rv_dataset = eb.add_dataset('rv', dataset=dataid, times=[])
#
# except ValueError:
#
# logger.warning("The name picked for the lightcurve is forbidden. Applying default name instead")
# rv_dataset = eb.add_dataset('rv', times=[])
return rv_dataset | python | def det_dataset(eb, passband, dataid, comp, time):
"""
Since RV datasets can have values related to each component in phoebe2, but are component specific in phoebe1
, it is important to determine which dataset to add parameters to. This function will do that.
eb - bundle
rvpt - relevant phoebe 1 parameters
"""
rvs = eb.get_dataset(kind='rv').datasets
#first check to see if there are currently in RV datasets
if dataid == 'Undefined':
dataid = None
# if len(rvs) == 0:
#if there isn't we add one the easy part
try:
eb._check_label(dataid)
rv_dataset = eb.add_dataset('rv', dataset=dataid, times=[])
except ValueError:
logger.warning("The name picked for the radial velocity curve is forbidden. Applying default name instead")
rv_dataset = eb.add_dataset('rv', times=[])
# else:
# #now we have to determine if we add to an existing dataset or make a new one
# rvs = eb.get_dataset(kind='rv').datasets
# found = False
# #set the component of the companion
#
# if comp == 'primary':
# comp_o = 'primary'
# else:
# comp_o = 'secondary'
# for x in rvs:
# test_dataset = eb.get_dataset(x, check_visible=False)
#
#
# if len(test_dataset.get_value(qualifier='rvs', component=comp_o, check_visible=False)) == 0: #so at least it has an empty spot now check against filter and length
# # removing reference to time_o. If there are no rvs there should be no times
# # time_o = test_dataset.get_value('times', component=comp_o)
# passband_o = test_dataset.get_value('passband')
#
# # if np.all(time_o == time) and (passband == passband_o):
# if (passband == passband_o):
# rv_dataset = test_dataset
# found = True
#
# if not found:
# try:
# eb._check_label(dataid)
#
# rv_dataset = eb.add_dataset('rv', dataset=dataid, times=[])
#
# except ValueError:
#
# logger.warning("The name picked for the lightcurve is forbidden. Applying default name instead")
# rv_dataset = eb.add_dataset('rv', times=[])
return rv_dataset | [
"def",
"det_dataset",
"(",
"eb",
",",
"passband",
",",
"dataid",
",",
"comp",
",",
"time",
")",
":",
"rvs",
"=",
"eb",
".",
"get_dataset",
"(",
"kind",
"=",
"'rv'",
")",
".",
"datasets",
"#first check to see if there are currently in RV datasets",
"if",
"datai... | Since RV datasets can have values related to each component in phoebe2, but are component specific in phoebe1
, it is important to determine which dataset to add parameters to. This function will do that.
eb - bundle
rvpt - relevant phoebe 1 parameters | [
"Since",
"RV",
"datasets",
"can",
"have",
"values",
"related",
"to",
"each",
"component",
"in",
"phoebe2",
"but",
"are",
"component",
"specific",
"in",
"phoebe1",
"it",
"is",
"important",
"to",
"determine",
"which",
"dataset",
"to",
"add",
"parameters",
"to",
... | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/io.py#L319-L380 | train | 39,932 |
phoebe-project/phoebe2 | phoebe/distortions/roche.py | rpole_to_pot_aligned | def rpole_to_pot_aligned(rpole, sma, q, F, d, component=1):
"""
Transforms polar radius to surface potential
"""
q = q_for_component(q, component=component)
rpole_ = np.array([0, 0, rpole/sma])
logger.debug("libphoebe.roche_Omega(q={}, F={}, d={}, rpole={})".format(q, F, d, rpole_))
pot = libphoebe.roche_Omega(q, F, d, rpole_)
return pot_for_component(pot, component, reverse=True) | python | def rpole_to_pot_aligned(rpole, sma, q, F, d, component=1):
"""
Transforms polar radius to surface potential
"""
q = q_for_component(q, component=component)
rpole_ = np.array([0, 0, rpole/sma])
logger.debug("libphoebe.roche_Omega(q={}, F={}, d={}, rpole={})".format(q, F, d, rpole_))
pot = libphoebe.roche_Omega(q, F, d, rpole_)
return pot_for_component(pot, component, reverse=True) | [
"def",
"rpole_to_pot_aligned",
"(",
"rpole",
",",
"sma",
",",
"q",
",",
"F",
",",
"d",
",",
"component",
"=",
"1",
")",
":",
"q",
"=",
"q_for_component",
"(",
"q",
",",
"component",
"=",
"component",
")",
"rpole_",
"=",
"np",
".",
"array",
"(",
"["... | Transforms polar radius to surface potential | [
"Transforms",
"polar",
"radius",
"to",
"surface",
"potential"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/distortions/roche.py#L81-L89 | train | 39,933 |
phoebe-project/phoebe2 | phoebe/distortions/roche.py | pot_to_rpole_aligned | def pot_to_rpole_aligned(pot, sma, q, F, d, component=1):
"""
Transforms surface potential to polar radius
"""
q = q_for_component(q, component=component)
Phi = pot_for_component(pot, q, component=component)
logger.debug("libphobe.roche_pole(q={}, F={}, d={}, Omega={})".format(q, F, d, pot))
return libphoebe.roche_pole(q, F, d, pot) * sma | python | def pot_to_rpole_aligned(pot, sma, q, F, d, component=1):
"""
Transforms surface potential to polar radius
"""
q = q_for_component(q, component=component)
Phi = pot_for_component(pot, q, component=component)
logger.debug("libphobe.roche_pole(q={}, F={}, d={}, Omega={})".format(q, F, d, pot))
return libphoebe.roche_pole(q, F, d, pot) * sma | [
"def",
"pot_to_rpole_aligned",
"(",
"pot",
",",
"sma",
",",
"q",
",",
"F",
",",
"d",
",",
"component",
"=",
"1",
")",
":",
"q",
"=",
"q_for_component",
"(",
"q",
",",
"component",
"=",
"component",
")",
"Phi",
"=",
"pot_for_component",
"(",
"pot",
",... | Transforms surface potential to polar radius | [
"Transforms",
"surface",
"potential",
"to",
"polar",
"radius"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/distortions/roche.py#L91-L98 | train | 39,934 |
phoebe-project/phoebe2 | phoebe/distortions/roche.py | BinaryRoche | def BinaryRoche (r, D, q, F, Omega=0.0):
r"""
Computes a value of the asynchronous, eccentric Roche potential.
If :envvar:`Omega` is passed, it computes the difference.
The asynchronous, eccentric Roche potential is given by [Wilson1979]_
.. math::
\Omega = \frac{1}{\sqrt{x^2 + y^2 + z^2}} + q\left(\frac{1}{\sqrt{(x-D)^2+y^2+z^2}} - \frac{x}{D^2}\right) + \frac{1}{2}F^2(1+q)(x^2+y^2)
@param r: relative radius vector (3 components)
@type r: 3-tuple
@param D: instantaneous separation
@type D: float
@param q: mass ratio
@type q: float
@param F: synchronicity parameter
@type F: float
@param Omega: value of the potential
@type Omega: float
"""
return 1.0/sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]) + q*(1.0/sqrt((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])-r[0]/D/D) + 0.5*F*F*(1+q)*(r[0]*r[0]+r[1]*r[1]) - Omega | python | def BinaryRoche (r, D, q, F, Omega=0.0):
r"""
Computes a value of the asynchronous, eccentric Roche potential.
If :envvar:`Omega` is passed, it computes the difference.
The asynchronous, eccentric Roche potential is given by [Wilson1979]_
.. math::
\Omega = \frac{1}{\sqrt{x^2 + y^2 + z^2}} + q\left(\frac{1}{\sqrt{(x-D)^2+y^2+z^2}} - \frac{x}{D^2}\right) + \frac{1}{2}F^2(1+q)(x^2+y^2)
@param r: relative radius vector (3 components)
@type r: 3-tuple
@param D: instantaneous separation
@type D: float
@param q: mass ratio
@type q: float
@param F: synchronicity parameter
@type F: float
@param Omega: value of the potential
@type Omega: float
"""
return 1.0/sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]) + q*(1.0/sqrt((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])-r[0]/D/D) + 0.5*F*F*(1+q)*(r[0]*r[0]+r[1]*r[1]) - Omega | [
"def",
"BinaryRoche",
"(",
"r",
",",
"D",
",",
"q",
",",
"F",
",",
"Omega",
"=",
"0.0",
")",
":",
"return",
"1.0",
"/",
"sqrt",
"(",
"r",
"[",
"0",
"]",
"*",
"r",
"[",
"0",
"]",
"+",
"r",
"[",
"1",
"]",
"*",
"r",
"[",
"1",
"]",
"+",
"... | r"""
Computes a value of the asynchronous, eccentric Roche potential.
If :envvar:`Omega` is passed, it computes the difference.
The asynchronous, eccentric Roche potential is given by [Wilson1979]_
.. math::
\Omega = \frac{1}{\sqrt{x^2 + y^2 + z^2}} + q\left(\frac{1}{\sqrt{(x-D)^2+y^2+z^2}} - \frac{x}{D^2}\right) + \frac{1}{2}F^2(1+q)(x^2+y^2)
@param r: relative radius vector (3 components)
@type r: 3-tuple
@param D: instantaneous separation
@type D: float
@param q: mass ratio
@type q: float
@param F: synchronicity parameter
@type F: float
@param Omega: value of the potential
@type Omega: float | [
"r",
"Computes",
"a",
"value",
"of",
"the",
"asynchronous",
"eccentric",
"Roche",
"potential",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/distortions/roche.py#L110-L133 | train | 39,935 |
phoebe-project/phoebe2 | phoebe/distortions/roche.py | dBinaryRochedx | def dBinaryRochedx (r, D, q, F):
"""
Computes a derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return -r[0]*(r[0]*r[0]+r[1]*r[1]+r[2]*r[2])**-1.5 -q*(r[0]-D)*((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**-1.5 -q/D/D + F*F*(1+q)*r[0] | python | def dBinaryRochedx (r, D, q, F):
"""
Computes a derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return -r[0]*(r[0]*r[0]+r[1]*r[1]+r[2]*r[2])**-1.5 -q*(r[0]-D)*((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**-1.5 -q/D/D + F*F*(1+q)*r[0] | [
"def",
"dBinaryRochedx",
"(",
"r",
",",
"D",
",",
"q",
",",
"F",
")",
":",
"return",
"-",
"r",
"[",
"0",
"]",
"*",
"(",
"r",
"[",
"0",
"]",
"*",
"r",
"[",
"0",
"]",
"+",
"r",
"[",
"1",
"]",
"*",
"r",
"[",
"1",
"]",
"+",
"r",
"[",
"2... | Computes a derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter | [
"Computes",
"a",
"derivative",
"of",
"the",
"potential",
"with",
"respect",
"to",
"x",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/distortions/roche.py#L135-L144 | train | 39,936 |
phoebe-project/phoebe2 | phoebe/distortions/roche.py | d2BinaryRochedx2 | def d2BinaryRochedx2(r, D, q, F):
"""
Computes second derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return (2*r[0]*r[0]-r[1]*r[1]-r[2]*r[2])/(r[0]*r[0]+r[1]*r[1]+r[2]*r[2])**2.5 +\
q*(2*(r[0]-D)*(r[0]-D)-r[1]*r[1]-r[2]*r[2])/((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**2.5 +\
F*F*(1+q) | python | def d2BinaryRochedx2(r, D, q, F):
"""
Computes second derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return (2*r[0]*r[0]-r[1]*r[1]-r[2]*r[2])/(r[0]*r[0]+r[1]*r[1]+r[2]*r[2])**2.5 +\
q*(2*(r[0]-D)*(r[0]-D)-r[1]*r[1]-r[2]*r[2])/((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**2.5 +\
F*F*(1+q) | [
"def",
"d2BinaryRochedx2",
"(",
"r",
",",
"D",
",",
"q",
",",
"F",
")",
":",
"return",
"(",
"2",
"*",
"r",
"[",
"0",
"]",
"*",
"r",
"[",
"0",
"]",
"-",
"r",
"[",
"1",
"]",
"*",
"r",
"[",
"1",
"]",
"-",
"r",
"[",
"2",
"]",
"*",
"r",
... | Computes second derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter | [
"Computes",
"second",
"derivative",
"of",
"the",
"potential",
"with",
"respect",
"to",
"x",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/distortions/roche.py#L146-L157 | train | 39,937 |
phoebe-project/phoebe2 | phoebe/distortions/roche.py | dBinaryRochedy | def dBinaryRochedy (r, D, q, F):
"""
Computes a derivative of the potential with respect to y.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return -r[1]*(r[0]*r[0]+r[1]*r[1]+r[2]*r[2])**-1.5 -q*r[1]*((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**-1.5 + F*F*(1+q)*r[1] | python | def dBinaryRochedy (r, D, q, F):
"""
Computes a derivative of the potential with respect to y.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return -r[1]*(r[0]*r[0]+r[1]*r[1]+r[2]*r[2])**-1.5 -q*r[1]*((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**-1.5 + F*F*(1+q)*r[1] | [
"def",
"dBinaryRochedy",
"(",
"r",
",",
"D",
",",
"q",
",",
"F",
")",
":",
"return",
"-",
"r",
"[",
"1",
"]",
"*",
"(",
"r",
"[",
"0",
"]",
"*",
"r",
"[",
"0",
"]",
"+",
"r",
"[",
"1",
"]",
"*",
"r",
"[",
"1",
"]",
"+",
"r",
"[",
"2... | Computes a derivative of the potential with respect to y.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter | [
"Computes",
"a",
"derivative",
"of",
"the",
"potential",
"with",
"respect",
"to",
"y",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/distortions/roche.py#L159-L168 | train | 39,938 |
phoebe-project/phoebe2 | phoebe/distortions/roche.py | dBinaryRochedz | def dBinaryRochedz(r, D, q, F):
"""
Computes a derivative of the potential with respect to z.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return -r[2]*(r[0]*r[0]+r[1]*r[1]+r[2]*r[2])**-1.5 -q*r[2]*((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**-1.5 | python | def dBinaryRochedz(r, D, q, F):
"""
Computes a derivative of the potential with respect to z.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return -r[2]*(r[0]*r[0]+r[1]*r[1]+r[2]*r[2])**-1.5 -q*r[2]*((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**-1.5 | [
"def",
"dBinaryRochedz",
"(",
"r",
",",
"D",
",",
"q",
",",
"F",
")",
":",
"return",
"-",
"r",
"[",
"2",
"]",
"*",
"(",
"r",
"[",
"0",
"]",
"*",
"r",
"[",
"0",
"]",
"+",
"r",
"[",
"1",
"]",
"*",
"r",
"[",
"1",
"]",
"+",
"r",
"[",
"2... | Computes a derivative of the potential with respect to z.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter | [
"Computes",
"a",
"derivative",
"of",
"the",
"potential",
"with",
"respect",
"to",
"z",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/distortions/roche.py#L170-L179 | train | 39,939 |
phoebe-project/phoebe2 | phoebe/distortions/roche.py | dBinaryRochedr | def dBinaryRochedr (r, D, q, F):
"""
Computes a derivative of the potential with respect to r.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
r2 = (r*r).sum()
r1 = np.sqrt(r2)
return -1./r2 - q*(r1-r[0]/r1*D)/((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**1.5 - q*r[0]/r1/D/D + F*F*(1+q)*(1-r[2]*r[2]/r2)*r1 | python | def dBinaryRochedr (r, D, q, F):
"""
Computes a derivative of the potential with respect to r.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
r2 = (r*r).sum()
r1 = np.sqrt(r2)
return -1./r2 - q*(r1-r[0]/r1*D)/((r[0]-D)*(r[0]-D)+r[1]*r[1]+r[2]*r[2])**1.5 - q*r[0]/r1/D/D + F*F*(1+q)*(1-r[2]*r[2]/r2)*r1 | [
"def",
"dBinaryRochedr",
"(",
"r",
",",
"D",
",",
"q",
",",
"F",
")",
":",
"r2",
"=",
"(",
"r",
"*",
"r",
")",
".",
"sum",
"(",
")",
"r1",
"=",
"np",
".",
"sqrt",
"(",
"r2",
")",
"return",
"-",
"1.",
"/",
"r2",
"-",
"q",
"*",
"(",
"r1",... | Computes a derivative of the potential with respect to r.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter | [
"Computes",
"a",
"derivative",
"of",
"the",
"potential",
"with",
"respect",
"to",
"r",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/distortions/roche.py#L181-L194 | train | 39,940 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | send_if_client | def send_if_client(fctn):
"""Intercept and send to the server if bundle is in client mode."""
@functools.wraps(fctn)
def _send_if_client(self, *args, **kwargs):
fctn_map = {'set_quantity': 'set_value'}
b = self._bundle
if b is not None and b.is_client:
# TODO: self._filter???
# TODO: args???
method = fctn_map.get(fctn.__name__, fctn.__name__)
d = self._filter if hasattr(self, '_filter') \
else {'twig': self.twig}
d['bundleid'] = b._bundleid
for k, v in kwargs.items():
d[k] = v
logger.info('emitting to {}({}) to server'.format(method, d))
b._socketio.emit(method, d)
if fctn.__name__ in ['run_compute', 'run_fitting']:
# then we're expecting a quick response with an added jobparam
# let's add that now
self._bundle.client_update()
else:
return fctn(self, *args, **kwargs)
return _send_if_client | python | def send_if_client(fctn):
"""Intercept and send to the server if bundle is in client mode."""
@functools.wraps(fctn)
def _send_if_client(self, *args, **kwargs):
fctn_map = {'set_quantity': 'set_value'}
b = self._bundle
if b is not None and b.is_client:
# TODO: self._filter???
# TODO: args???
method = fctn_map.get(fctn.__name__, fctn.__name__)
d = self._filter if hasattr(self, '_filter') \
else {'twig': self.twig}
d['bundleid'] = b._bundleid
for k, v in kwargs.items():
d[k] = v
logger.info('emitting to {}({}) to server'.format(method, d))
b._socketio.emit(method, d)
if fctn.__name__ in ['run_compute', 'run_fitting']:
# then we're expecting a quick response with an added jobparam
# let's add that now
self._bundle.client_update()
else:
return fctn(self, *args, **kwargs)
return _send_if_client | [
"def",
"send_if_client",
"(",
"fctn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fctn",
")",
"def",
"_send_if_client",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fctn_map",
"=",
"{",
"'set_quantity'",
":",
"'set_value'",
"}... | Intercept and send to the server if bundle is in client mode. | [
"Intercept",
"and",
"send",
"to",
"the",
"server",
"if",
"bundle",
"is",
"in",
"client",
"mode",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L183-L208 | train | 39,941 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | update_if_client | def update_if_client(fctn):
"""Intercept and check updates from server if bundle is in client mode."""
@functools.wraps(fctn)
def _update_if_client(self, *args, **kwargs):
b = self._bundle
if b is None or not hasattr(b, 'is_client'):
return fctn(self, *args, **kwargs)
elif b.is_client and \
(b._last_client_update is None or
(datetime.now() - b._last_client_update).seconds > 1):
b.client_update()
return fctn(self, *args, **kwargs)
return _update_if_client | python | def update_if_client(fctn):
"""Intercept and check updates from server if bundle is in client mode."""
@functools.wraps(fctn)
def _update_if_client(self, *args, **kwargs):
b = self._bundle
if b is None or not hasattr(b, 'is_client'):
return fctn(self, *args, **kwargs)
elif b.is_client and \
(b._last_client_update is None or
(datetime.now() - b._last_client_update).seconds > 1):
b.client_update()
return fctn(self, *args, **kwargs)
return _update_if_client | [
"def",
"update_if_client",
"(",
"fctn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fctn",
")",
"def",
"_update_if_client",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"b",
"=",
"self",
".",
"_bundle",
"if",
"b",
"is",
"No... | Intercept and check updates from server if bundle is in client mode. | [
"Intercept",
"and",
"check",
"updates",
"from",
"server",
"if",
"bundle",
"is",
"in",
"client",
"mode",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L211-L224 | train | 39,942 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | _uniqueid | def _uniqueid(n=30):
"""Return a unique string with length n.
:parameter int N: number of character in the uniqueid
:return: the uniqueid
:rtype: str
"""
return ''.join(random.SystemRandom().choice(
string.ascii_uppercase + string.ascii_lowercase)
for _ in range(n)) | python | def _uniqueid(n=30):
"""Return a unique string with length n.
:parameter int N: number of character in the uniqueid
:return: the uniqueid
:rtype: str
"""
return ''.join(random.SystemRandom().choice(
string.ascii_uppercase + string.ascii_lowercase)
for _ in range(n)) | [
"def",
"_uniqueid",
"(",
"n",
"=",
"30",
")",
":",
"return",
"''",
".",
"join",
"(",
"random",
".",
"SystemRandom",
"(",
")",
".",
"choice",
"(",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"ascii_lowercase",
")",
"for",
"_",
"in",
"range",
... | Return a unique string with length n.
:parameter int N: number of character in the uniqueid
:return: the uniqueid
:rtype: str | [
"Return",
"a",
"unique",
"string",
"with",
"length",
"n",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L227-L236 | train | 39,943 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | parameter_from_json | def parameter_from_json(dictionary, bundle=None):
"""Load a single parameter from a JSON dictionary.
:parameter dict dictionary: the dictionary containing the parameter
information
:parameter bundle: (optional)
:return: instantiated :class:`Parameter` object
"""
if isinstance(dictionary, str):
dictionary = json.loads(dictionary, object_pairs_hook=parse_json)
classname = dictionary.pop('Class')
if classname not in _parameter_class_that_require_bundle:
bundle = None
# now let's do some dirty magic and get the actual classitself
# from THIS module. __name__ is a string to lookup this module
# from the sys.modules dictionary
cls = getattr(sys.modules[__name__], classname)
return cls._from_json(bundle, **dictionary) | python | def parameter_from_json(dictionary, bundle=None):
"""Load a single parameter from a JSON dictionary.
:parameter dict dictionary: the dictionary containing the parameter
information
:parameter bundle: (optional)
:return: instantiated :class:`Parameter` object
"""
if isinstance(dictionary, str):
dictionary = json.loads(dictionary, object_pairs_hook=parse_json)
classname = dictionary.pop('Class')
if classname not in _parameter_class_that_require_bundle:
bundle = None
# now let's do some dirty magic and get the actual classitself
# from THIS module. __name__ is a string to lookup this module
# from the sys.modules dictionary
cls = getattr(sys.modules[__name__], classname)
return cls._from_json(bundle, **dictionary) | [
"def",
"parameter_from_json",
"(",
"dictionary",
",",
"bundle",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"dictionary",
",",
"str",
")",
":",
"dictionary",
"=",
"json",
".",
"loads",
"(",
"dictionary",
",",
"object_pairs_hook",
"=",
"parse_json",
")",
... | Load a single parameter from a JSON dictionary.
:parameter dict dictionary: the dictionary containing the parameter
information
:parameter bundle: (optional)
:return: instantiated :class:`Parameter` object | [
"Load",
"a",
"single",
"parameter",
"from",
"a",
"JSON",
"dictionary",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L252-L273 | train | 39,944 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.get_meta | def get_meta(self, ignore=['uniqueid']):
"""Dictionary of all meta-tags, with option to ignore certain tags.
See all the meta-tag properties that are shared by ALL Parameters.
If a given value is 'None', that means that it is not shared
among ALL Parameters. To see the different values among the
Parameters, you can access that attribute.
:parameter list ignore: list of keys to exclude from the returned
dictionary
:return: an ordered dictionary of tag properties
"""
return OrderedDict([(k, getattr(self, k))
for k in _meta_fields_twig
if k not in ignore]) | python | def get_meta(self, ignore=['uniqueid']):
"""Dictionary of all meta-tags, with option to ignore certain tags.
See all the meta-tag properties that are shared by ALL Parameters.
If a given value is 'None', that means that it is not shared
among ALL Parameters. To see the different values among the
Parameters, you can access that attribute.
:parameter list ignore: list of keys to exclude from the returned
dictionary
:return: an ordered dictionary of tag properties
"""
return OrderedDict([(k, getattr(self, k))
for k in _meta_fields_twig
if k not in ignore]) | [
"def",
"get_meta",
"(",
"self",
",",
"ignore",
"=",
"[",
"'uniqueid'",
"]",
")",
":",
"return",
"OrderedDict",
"(",
"[",
"(",
"k",
",",
"getattr",
"(",
"self",
",",
"k",
")",
")",
"for",
"k",
"in",
"_meta_fields_twig",
"if",
"k",
"not",
"in",
"igno... | Dictionary of all meta-tags, with option to ignore certain tags.
See all the meta-tag properties that are shared by ALL Parameters.
If a given value is 'None', that means that it is not shared
among ALL Parameters. To see the different values among the
Parameters, you can access that attribute.
:parameter list ignore: list of keys to exclude from the returned
dictionary
:return: an ordered dictionary of tag properties | [
"Dictionary",
"of",
"all",
"meta",
"-",
"tags",
"with",
"option",
"to",
"ignore",
"certain",
"tags",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L382-L396 | train | 39,945 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.set_meta | def set_meta(self, **kwargs):
"""Set the value of tags for all Parameters in this ParameterSet."""
for param in self.to_list():
for k, v in kwargs.items():
# Here we'll set the attributes (_context, _qualifier, etc)
if getattr(param, '_{}'.format(k)) is None:
setattr(param, '_{}'.format(k), v) | python | def set_meta(self, **kwargs):
"""Set the value of tags for all Parameters in this ParameterSet."""
for param in self.to_list():
for k, v in kwargs.items():
# Here we'll set the attributes (_context, _qualifier, etc)
if getattr(param, '_{}'.format(k)) is None:
setattr(param, '_{}'.format(k), v) | [
"def",
"set_meta",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"param",
"in",
"self",
".",
"to_list",
"(",
")",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"# Here we'll set the attributes (_context, _qualifier, etc)"... | Set the value of tags for all Parameters in this ParameterSet. | [
"Set",
"the",
"value",
"of",
"tags",
"for",
"all",
"Parameters",
"in",
"this",
"ParameterSet",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L398-L404 | train | 39,946 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.tags | def tags(self):
"""Returns a dictionary that lists all available tags that can be used
for further filtering
"""
ret = {}
for typ in _meta_fields_twig:
if typ in ['uniqueid', 'plugin', 'feedback', 'fitting', 'history', 'twig', 'uniquetwig']:
continue
k = '{}s'.format(typ)
ret[k] = getattr(self, k)
return ret | python | def tags(self):
"""Returns a dictionary that lists all available tags that can be used
for further filtering
"""
ret = {}
for typ in _meta_fields_twig:
if typ in ['uniqueid', 'plugin', 'feedback', 'fitting', 'history', 'twig', 'uniquetwig']:
continue
k = '{}s'.format(typ)
ret[k] = getattr(self, k)
return ret | [
"def",
"tags",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"typ",
"in",
"_meta_fields_twig",
":",
"if",
"typ",
"in",
"[",
"'uniqueid'",
",",
"'plugin'",
",",
"'feedback'",
",",
"'fitting'",
",",
"'history'",
",",
"'twig'",
",",
"'uniquetwig'",
... | Returns a dictionary that lists all available tags that can be used
for further filtering | [
"Returns",
"a",
"dictionary",
"that",
"lists",
"all",
"available",
"tags",
"that",
"can",
"be",
"used",
"for",
"further",
"filtering"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L407-L419 | train | 39,947 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet._set_meta | def _set_meta(self):
"""
set the meta fields of the ParameterSet as those that are shared
by ALL parameters in the ParameterSet. For any fields that are
not
"""
# we want to set meta-fields that are shared by ALL params in the PS
for field in _meta_fields_twig:
keys_for_this_field = set([getattr(p, field)
for p in self.to_list()
if getattr(p, field) is not None])
if len(keys_for_this_field)==1:
setattr(self, '_'+field, list(keys_for_this_field)[0])
else:
setattr(self, '_'+field, None) | python | def _set_meta(self):
"""
set the meta fields of the ParameterSet as those that are shared
by ALL parameters in the ParameterSet. For any fields that are
not
"""
# we want to set meta-fields that are shared by ALL params in the PS
for field in _meta_fields_twig:
keys_for_this_field = set([getattr(p, field)
for p in self.to_list()
if getattr(p, field) is not None])
if len(keys_for_this_field)==1:
setattr(self, '_'+field, list(keys_for_this_field)[0])
else:
setattr(self, '_'+field, None) | [
"def",
"_set_meta",
"(",
"self",
")",
":",
"# we want to set meta-fields that are shared by ALL params in the PS",
"for",
"field",
"in",
"_meta_fields_twig",
":",
"keys_for_this_field",
"=",
"set",
"(",
"[",
"getattr",
"(",
"p",
",",
"field",
")",
"for",
"p",
"in",
... | set the meta fields of the ParameterSet as those that are shared
by ALL parameters in the ParameterSet. For any fields that are
not | [
"set",
"the",
"meta",
"fields",
"of",
"the",
"ParameterSet",
"as",
"those",
"that",
"are",
"shared",
"by",
"ALL",
"parameters",
"in",
"the",
"ParameterSet",
".",
"For",
"any",
"fields",
"that",
"are",
"not"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L736-L750 | train | 39,948 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet._uniquetwig | def _uniquetwig(self, twig, force_levels=['qualifier']):
"""
get the least unique twig for the parameter given by twig that
will return this single result for THIS PS
:parameter str twig: a twig that will return a single Parameter from
THIS PS
:parameter list force_levels: (optional) a list of "levels"
(eg. context) that should be included whether or not they are
necessary
:return: the unique twig
:rtype: str
"""
for_this_param = self.filter(twig, check_visible=False)
metawargs = {}
# NOTE: self.contexts is INCREDIBLY expensive
# if len(self.contexts) and 'context' not in force_levels:
if 'context' not in force_levels:
# then let's force context to be included
force_levels.append('context')
for k in force_levels:
metawargs[k] = getattr(for_this_param, k)
prev_count = len(self)
# just to fake in case no metawargs are passed at all
ps_for_this_search = []
for k in _meta_fields_twig:
metawargs[k] = getattr(for_this_param, k)
if getattr(for_this_param, k) is None:
continue
ps_for_this_search = self.filter(check_visible=False, **metawargs)
if len(ps_for_this_search) < prev_count and k not in force_levels:
prev_count = len(ps_for_this_search)
elif k not in force_levels:
# this didn't help us
metawargs[k] = None
if len(ps_for_this_search) != 1:
# TODO: after fixing regex in twig (t0type vs t0)
# change this to raise Error instead of return
return twig
# now we go in the other direction and try to remove each to make sure
# the count goes up
for k in _meta_fields_twig:
if metawargs[k] is None or k in force_levels:
continue
ps_for_this_search = self.filter(check_visible=False,
**{ki: metawargs[k]
for ki in _meta_fields_twig
if ki != k})
if len(ps_for_this_search) == 1:
# then we didn't need to use this tag
metawargs[k] = None
# and lastly, we make sure that the tag corresponding to the context
# is present
context = for_this_param.context
if hasattr(for_this_param, context):
metawargs[context] = getattr(for_this_param, context)
return "@".join([metawargs[k]
for k in _meta_fields_twig
if metawargs[k] is not None]) | python | def _uniquetwig(self, twig, force_levels=['qualifier']):
"""
get the least unique twig for the parameter given by twig that
will return this single result for THIS PS
:parameter str twig: a twig that will return a single Parameter from
THIS PS
:parameter list force_levels: (optional) a list of "levels"
(eg. context) that should be included whether or not they are
necessary
:return: the unique twig
:rtype: str
"""
for_this_param = self.filter(twig, check_visible=False)
metawargs = {}
# NOTE: self.contexts is INCREDIBLY expensive
# if len(self.contexts) and 'context' not in force_levels:
if 'context' not in force_levels:
# then let's force context to be included
force_levels.append('context')
for k in force_levels:
metawargs[k] = getattr(for_this_param, k)
prev_count = len(self)
# just to fake in case no metawargs are passed at all
ps_for_this_search = []
for k in _meta_fields_twig:
metawargs[k] = getattr(for_this_param, k)
if getattr(for_this_param, k) is None:
continue
ps_for_this_search = self.filter(check_visible=False, **metawargs)
if len(ps_for_this_search) < prev_count and k not in force_levels:
prev_count = len(ps_for_this_search)
elif k not in force_levels:
# this didn't help us
metawargs[k] = None
if len(ps_for_this_search) != 1:
# TODO: after fixing regex in twig (t0type vs t0)
# change this to raise Error instead of return
return twig
# now we go in the other direction and try to remove each to make sure
# the count goes up
for k in _meta_fields_twig:
if metawargs[k] is None or k in force_levels:
continue
ps_for_this_search = self.filter(check_visible=False,
**{ki: metawargs[k]
for ki in _meta_fields_twig
if ki != k})
if len(ps_for_this_search) == 1:
# then we didn't need to use this tag
metawargs[k] = None
# and lastly, we make sure that the tag corresponding to the context
# is present
context = for_this_param.context
if hasattr(for_this_param, context):
metawargs[context] = getattr(for_this_param, context)
return "@".join([metawargs[k]
for k in _meta_fields_twig
if metawargs[k] is not None]) | [
"def",
"_uniquetwig",
"(",
"self",
",",
"twig",
",",
"force_levels",
"=",
"[",
"'qualifier'",
"]",
")",
":",
"for_this_param",
"=",
"self",
".",
"filter",
"(",
"twig",
",",
"check_visible",
"=",
"False",
")",
"metawargs",
"=",
"{",
"}",
"# NOTE: self.conte... | get the least unique twig for the parameter given by twig that
will return this single result for THIS PS
:parameter str twig: a twig that will return a single Parameter from
THIS PS
:parameter list force_levels: (optional) a list of "levels"
(eg. context) that should be included whether or not they are
necessary
:return: the unique twig
:rtype: str | [
"get",
"the",
"least",
"unique",
"twig",
"for",
"the",
"parameter",
"given",
"by",
"twig",
"that",
"will",
"return",
"this",
"single",
"result",
"for",
"THIS",
"PS"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L752-L822 | train | 39,949 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet._check_copy_for | def _check_copy_for(self):
"""Check the value of copy_for and make appropriate copies."""
if not self._bundle:
return
# read the following at your own risk - I just wrote it and it still
# confuses me and baffles me that it works
for param in self.to_list():
if param.copy_for:
# copy_for tells us how to filter and what set of attributes
# needs a copy of this parameter
#
# copy_for = {'kind': ['star', 'disk', 'custombody'], 'component': '*'}
# means that this should exist for each component (since that has a wildcard) which
# has a kind in [star, disk, custombody]
#
# copy_for = {'kind': ['rv_dep'], 'component': '*', 'dataset': '*'}
# means that this should exist for each component/dataset pair with the
# rv_dep kind
attrs = [k for k,v in param.copy_for.items() if '*' in v]
# attrs is a list of the attributes for which we need a copy of
# this parameter for any pair
ps = self._bundle.filter(check_visible=False, check_default=False, force_ps=True, **param.copy_for)
metawargs = {k:v for k,v in ps.meta.items() if v is not None and k in attrs}
for k,v in param.meta.items():
if k not in ['twig', 'uniquetwig'] and k not in attrs:
metawargs[k] = v
# metawargs is a list of the shared tags that will be used to filter for
# existing parameters so that we know whether they already exist or
# still need to be created
# logger.debug("_check_copy_for {}: attrs={}".format(param.twig, attrs))
for attrvalues in itertools.product(*(getattr(ps, '{}s'.format(attr)) for attr in attrs)):
# logger.debug("_check_copy_for {}: attrvalues={}".format(param.twig, attrvalues))
# for each attrs[i] (ie component), attrvalues[i] (star01)
# we need to look for this parameter, and if it does not exist
# then create it by copying param
for attr, attrvalue in zip(attrs, attrvalues):
#if attrvalue=='_default' and not getattr(param, attr):
# print "SKIPPING", attr, attrvalue
# continue
metawargs[attr] = attrvalue
# logger.debug("_check_copy_for {}: metawargs={}".format(param.twig, metawargs))
if not len(self._bundle.filter(check_visible=False, **metawargs)):
# then we need to make a new copy
logger.debug("copying '{}' parameter for {}".format(param.qualifier, {attr: attrvalue for attr, attrvalue in zip(attrs, attrvalues)}))
newparam = param.copy()
for attr, attrvalue in zip(attrs, attrvalues):
setattr(newparam, '_{}'.format(attr), attrvalue)
newparam._copy_for = False
if newparam._visible_if and newparam._visible_if.lower() == 'false':
newparam._visible_if = None
newparam._bundle = self._bundle
self._params.append(newparam)
# Now we need to handle copying constraints. This can't be
# in the previous if statement because the parameters can be
# copied before constraints are ever attached.
if hasattr(param, 'is_constraint') and param.is_constraint:
param_constraint = param.is_constraint
copied_param = self._bundle.get_parameter(check_visible=False, check_default=False, **metawargs)
if not copied_param.is_constraint:
constraint_kwargs = param_constraint.constraint_kwargs.copy()
for attr, attrvalue in zip(attrs, attrvalues):
if attr in constraint_kwargs.keys():
constraint_kwargs[attr] = attrvalue
logger.debug("copying constraint '{}' parameter for {}".format(param_constraint.constraint_func, {attr: attrvalue for attr, attrvalue in zip(attrs, attrvalues)}))
self.add_constraint(func=param_constraint.constraint_func, **constraint_kwargs)
return | python | def _check_copy_for(self):
"""Check the value of copy_for and make appropriate copies."""
if not self._bundle:
return
# read the following at your own risk - I just wrote it and it still
# confuses me and baffles me that it works
for param in self.to_list():
if param.copy_for:
# copy_for tells us how to filter and what set of attributes
# needs a copy of this parameter
#
# copy_for = {'kind': ['star', 'disk', 'custombody'], 'component': '*'}
# means that this should exist for each component (since that has a wildcard) which
# has a kind in [star, disk, custombody]
#
# copy_for = {'kind': ['rv_dep'], 'component': '*', 'dataset': '*'}
# means that this should exist for each component/dataset pair with the
# rv_dep kind
attrs = [k for k,v in param.copy_for.items() if '*' in v]
# attrs is a list of the attributes for which we need a copy of
# this parameter for any pair
ps = self._bundle.filter(check_visible=False, check_default=False, force_ps=True, **param.copy_for)
metawargs = {k:v for k,v in ps.meta.items() if v is not None and k in attrs}
for k,v in param.meta.items():
if k not in ['twig', 'uniquetwig'] and k not in attrs:
metawargs[k] = v
# metawargs is a list of the shared tags that will be used to filter for
# existing parameters so that we know whether they already exist or
# still need to be created
# logger.debug("_check_copy_for {}: attrs={}".format(param.twig, attrs))
for attrvalues in itertools.product(*(getattr(ps, '{}s'.format(attr)) for attr in attrs)):
# logger.debug("_check_copy_for {}: attrvalues={}".format(param.twig, attrvalues))
# for each attrs[i] (ie component), attrvalues[i] (star01)
# we need to look for this parameter, and if it does not exist
# then create it by copying param
for attr, attrvalue in zip(attrs, attrvalues):
#if attrvalue=='_default' and not getattr(param, attr):
# print "SKIPPING", attr, attrvalue
# continue
metawargs[attr] = attrvalue
# logger.debug("_check_copy_for {}: metawargs={}".format(param.twig, metawargs))
if not len(self._bundle.filter(check_visible=False, **metawargs)):
# then we need to make a new copy
logger.debug("copying '{}' parameter for {}".format(param.qualifier, {attr: attrvalue for attr, attrvalue in zip(attrs, attrvalues)}))
newparam = param.copy()
for attr, attrvalue in zip(attrs, attrvalues):
setattr(newparam, '_{}'.format(attr), attrvalue)
newparam._copy_for = False
if newparam._visible_if and newparam._visible_if.lower() == 'false':
newparam._visible_if = None
newparam._bundle = self._bundle
self._params.append(newparam)
# Now we need to handle copying constraints. This can't be
# in the previous if statement because the parameters can be
# copied before constraints are ever attached.
if hasattr(param, 'is_constraint') and param.is_constraint:
param_constraint = param.is_constraint
copied_param = self._bundle.get_parameter(check_visible=False, check_default=False, **metawargs)
if not copied_param.is_constraint:
constraint_kwargs = param_constraint.constraint_kwargs.copy()
for attr, attrvalue in zip(attrs, attrvalues):
if attr in constraint_kwargs.keys():
constraint_kwargs[attr] = attrvalue
logger.debug("copying constraint '{}' parameter for {}".format(param_constraint.constraint_func, {attr: attrvalue for attr, attrvalue in zip(attrs, attrvalues)}))
self.add_constraint(func=param_constraint.constraint_func, **constraint_kwargs)
return | [
"def",
"_check_copy_for",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_bundle",
":",
"return",
"# read the following at your own risk - I just wrote it and it still",
"# confuses me and baffles me that it works",
"for",
"param",
"in",
"self",
".",
"to_list",
"(",
")... | Check the value of copy_for and make appropriate copies. | [
"Check",
"the",
"value",
"of",
"copy_for",
"and",
"make",
"appropriate",
"copies",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L844-L927 | train | 39,950 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet._check_label | def _check_label(self, label):
"""Check to see if the label is allowed."""
if not isinstance(label, str):
label = str(label)
if label.lower() in _forbidden_labels:
raise ValueError("'{}' is forbidden to be used as a label"
.format(label))
if not re.match("^[a-z,A-Z,0-9,_]*$", label):
raise ValueError("label '{}' is forbidden - only alphabetic, numeric, and '_' characters are allowed in labels".format(label))
if len(self.filter(twig=label, check_visible=False)):
raise ValueError("label '{}' is already in use".format(label))
if label[0] in ['_']:
raise ValueError("first character of label is a forbidden character") | python | def _check_label(self, label):
"""Check to see if the label is allowed."""
if not isinstance(label, str):
label = str(label)
if label.lower() in _forbidden_labels:
raise ValueError("'{}' is forbidden to be used as a label"
.format(label))
if not re.match("^[a-z,A-Z,0-9,_]*$", label):
raise ValueError("label '{}' is forbidden - only alphabetic, numeric, and '_' characters are allowed in labels".format(label))
if len(self.filter(twig=label, check_visible=False)):
raise ValueError("label '{}' is already in use".format(label))
if label[0] in ['_']:
raise ValueError("first character of label is a forbidden character") | [
"def",
"_check_label",
"(",
"self",
",",
"label",
")",
":",
"if",
"not",
"isinstance",
"(",
"label",
",",
"str",
")",
":",
"label",
"=",
"str",
"(",
"label",
")",
"if",
"label",
".",
"lower",
"(",
")",
"in",
"_forbidden_labels",
":",
"raise",
"ValueE... | Check to see if the label is allowed. | [
"Check",
"to",
"see",
"if",
"the",
"label",
"is",
"allowed",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L929-L943 | train | 39,951 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.save | def save(self, filename, incl_uniqueid=False, compact=False):
"""
Save the ParameterSet to a JSON-formatted ASCII file
:parameter str filename: relative or fullpath to the file
:parameter bool incl_uniqueid: whether to including uniqueids in the
file (only needed if its necessary to maintain the uniqueids when
reloading)
:parameter bool compact: whether to use compact file-formatting (maybe
be quicker to save/load, but not as easily readable)
:return: filename
:rtype: str
"""
filename = os.path.expanduser(filename)
f = open(filename, 'w')
if compact:
if _can_ujson:
ujson.dump(self.to_json(incl_uniqueid=incl_uniqueid), f,
sort_keys=False, indent=0)
else:
logger.warning("for faster compact saving, install ujson")
json.dump(self.to_json(incl_uniqueid=incl_uniqueid), f,
sort_keys=False, indent=0)
else:
json.dump(self.to_json(incl_uniqueid=incl_uniqueid), f,
sort_keys=True, indent=0, separators=(',', ': '))
f.close()
return filename | python | def save(self, filename, incl_uniqueid=False, compact=False):
"""
Save the ParameterSet to a JSON-formatted ASCII file
:parameter str filename: relative or fullpath to the file
:parameter bool incl_uniqueid: whether to including uniqueids in the
file (only needed if its necessary to maintain the uniqueids when
reloading)
:parameter bool compact: whether to use compact file-formatting (maybe
be quicker to save/load, but not as easily readable)
:return: filename
:rtype: str
"""
filename = os.path.expanduser(filename)
f = open(filename, 'w')
if compact:
if _can_ujson:
ujson.dump(self.to_json(incl_uniqueid=incl_uniqueid), f,
sort_keys=False, indent=0)
else:
logger.warning("for faster compact saving, install ujson")
json.dump(self.to_json(incl_uniqueid=incl_uniqueid), f,
sort_keys=False, indent=0)
else:
json.dump(self.to_json(incl_uniqueid=incl_uniqueid), f,
sort_keys=True, indent=0, separators=(',', ': '))
f.close()
return filename | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"incl_uniqueid",
"=",
"False",
",",
"compact",
"=",
"False",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
... | Save the ParameterSet to a JSON-formatted ASCII file
:parameter str filename: relative or fullpath to the file
:parameter bool incl_uniqueid: whether to including uniqueids in the
file (only needed if its necessary to maintain the uniqueids when
reloading)
:parameter bool compact: whether to use compact file-formatting (maybe
be quicker to save/load, but not as easily readable)
:return: filename
:rtype: str | [
"Save",
"the",
"ParameterSet",
"to",
"a",
"JSON",
"-",
"formatted",
"ASCII",
"file"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L1004-L1032 | train | 39,952 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.set | def set(self, key, value, **kwargs):
"""
Set the value of a Parameter in the ParameterSet.
If :func:`get` would retrieve a Parameter, this will set the
value of that parameter.
Or you can provide 'value@...' or 'default_unit@...', etc
to specify what attribute to set.
:parameter str key: the twig (called key here to be analagous
to a normal dict)
:parameter value: value to set
:parameter **kwargs: other filter parameters (must result in
returning a single :class:`Parameter`)
:return: the value of the :class:`Parameter` after setting the
new value (including converting units if applicable)
"""
twig = key
method = None
twigsplit = re.findall(r"[\w']+", twig)
if twigsplit[0] == 'value':
twig = '@'.join(twigsplit[1:])
method = 'set_value'
elif twigsplit[0] == 'quantity':
twig = '@'.join(twigsplit[1:])
method = 'set_quantity'
elif twigsplit[0] in ['unit', 'default_unit']:
twig = '@'.join(twigsplit[1:])
method = 'set_default_unit'
elif twigsplit[0] in ['timederiv']:
twig = '@'.join(twigsplit[1:])
method = 'set_timederiv'
elif twigsplit[0] in ['description']:
raise KeyError("cannot set {} of {}".format(twigsplit[0], '@'.join(twigsplit[1:])))
if self._bundle is not None and self._bundle.get_setting('dict_set_all').get_value() and len(self.filter(twig=twig, **kwargs)) > 1:
# then we need to loop through all the returned parameters and call set on them
for param in self.filter(twig=twig, **kwargs).to_list():
self.set('{}@{}'.format(method, param.twig) if method is not None else param.twig, value)
else:
if method is None:
return self.set_value(twig=twig, value=value, **kwargs)
else:
param = self.get_parameter(twig=twig, **kwargs)
return getattr(param, method)(value) | python | def set(self, key, value, **kwargs):
"""
Set the value of a Parameter in the ParameterSet.
If :func:`get` would retrieve a Parameter, this will set the
value of that parameter.
Or you can provide 'value@...' or 'default_unit@...', etc
to specify what attribute to set.
:parameter str key: the twig (called key here to be analagous
to a normal dict)
:parameter value: value to set
:parameter **kwargs: other filter parameters (must result in
returning a single :class:`Parameter`)
:return: the value of the :class:`Parameter` after setting the
new value (including converting units if applicable)
"""
twig = key
method = None
twigsplit = re.findall(r"[\w']+", twig)
if twigsplit[0] == 'value':
twig = '@'.join(twigsplit[1:])
method = 'set_value'
elif twigsplit[0] == 'quantity':
twig = '@'.join(twigsplit[1:])
method = 'set_quantity'
elif twigsplit[0] in ['unit', 'default_unit']:
twig = '@'.join(twigsplit[1:])
method = 'set_default_unit'
elif twigsplit[0] in ['timederiv']:
twig = '@'.join(twigsplit[1:])
method = 'set_timederiv'
elif twigsplit[0] in ['description']:
raise KeyError("cannot set {} of {}".format(twigsplit[0], '@'.join(twigsplit[1:])))
if self._bundle is not None and self._bundle.get_setting('dict_set_all').get_value() and len(self.filter(twig=twig, **kwargs)) > 1:
# then we need to loop through all the returned parameters and call set on them
for param in self.filter(twig=twig, **kwargs).to_list():
self.set('{}@{}'.format(method, param.twig) if method is not None else param.twig, value)
else:
if method is None:
return self.set_value(twig=twig, value=value, **kwargs)
else:
param = self.get_parameter(twig=twig, **kwargs)
return getattr(param, method)(value) | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"twig",
"=",
"key",
"method",
"=",
"None",
"twigsplit",
"=",
"re",
".",
"findall",
"(",
"r\"[\\w']+\"",
",",
"twig",
")",
"if",
"twigsplit",
"[",
"0",
"]",
"=... | Set the value of a Parameter in the ParameterSet.
If :func:`get` would retrieve a Parameter, this will set the
value of that parameter.
Or you can provide 'value@...' or 'default_unit@...', etc
to specify what attribute to set.
:parameter str key: the twig (called key here to be analagous
to a normal dict)
:parameter value: value to set
:parameter **kwargs: other filter parameters (must result in
returning a single :class:`Parameter`)
:return: the value of the :class:`Parameter` after setting the
new value (including converting units if applicable) | [
"Set",
"the",
"value",
"of",
"a",
"Parameter",
"in",
"the",
"ParameterSet",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L1177-L1225 | train | 39,953 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.to_json | def to_json(self, incl_uniqueid=False):
"""
Convert the ParameterSet to a json-compatible dictionary
:return: list of dictionaries
"""
lst = []
for context in _contexts:
lst += [v.to_json(incl_uniqueid=incl_uniqueid)
for v in self.filter(context=context,
check_visible=False,
check_default=False).to_list()]
return lst | python | def to_json(self, incl_uniqueid=False):
"""
Convert the ParameterSet to a json-compatible dictionary
:return: list of dictionaries
"""
lst = []
for context in _contexts:
lst += [v.to_json(incl_uniqueid=incl_uniqueid)
for v in self.filter(context=context,
check_visible=False,
check_default=False).to_list()]
return lst | [
"def",
"to_json",
"(",
"self",
",",
"incl_uniqueid",
"=",
"False",
")",
":",
"lst",
"=",
"[",
"]",
"for",
"context",
"in",
"_contexts",
":",
"lst",
"+=",
"[",
"v",
".",
"to_json",
"(",
"incl_uniqueid",
"=",
"incl_uniqueid",
")",
"for",
"v",
"in",
"se... | Convert the ParameterSet to a json-compatible dictionary
:return: list of dictionaries | [
"Convert",
"the",
"ParameterSet",
"to",
"a",
"json",
"-",
"compatible",
"dictionary"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L1268-L1280 | train | 39,954 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.filter | def filter(self, twig=None, check_visible=True, check_default=True, **kwargs):
"""
Filter the ParameterSet based on the meta-tags of the Parameters
and return another ParameterSet.
Because another ParameterSet is returned, these filter calls are
chainable.
>>> b.filter(context='component').filter(component='starA')
:parameter str twig: (optional) the search twig - essentially a single
string with any delimiter (ie '@') that will be parsed
into any of the meta-tags. Example: instead of
b.filter(context='component', component='starA'), you
could do b.filter('starA@component').
:parameter bool check_visible: whether to hide invisible
parameters. These are usually parameters that do not
play a role unless the value of another parameter meets
some condition.
:parameter bool check_default: whether to exclude parameters which
have a _default tag (these are parameters which solely exist
to provide defaults for when new parameters or datasets are
added and the parameter needs to be copied appropriately).
Defaults to True.
:parameter **kwargs: meta-tags to search (ie. 'context', 'component',
'model', etc). See :func:`meta` for all possible options.
:return: the resulting :class:`ParameterSet`
"""
kwargs['check_visible'] = check_visible
kwargs['check_default'] = check_default
kwargs['force_ps'] = True
return self.filter_or_get(twig=twig, **kwargs) | python | def filter(self, twig=None, check_visible=True, check_default=True, **kwargs):
"""
Filter the ParameterSet based on the meta-tags of the Parameters
and return another ParameterSet.
Because another ParameterSet is returned, these filter calls are
chainable.
>>> b.filter(context='component').filter(component='starA')
:parameter str twig: (optional) the search twig - essentially a single
string with any delimiter (ie '@') that will be parsed
into any of the meta-tags. Example: instead of
b.filter(context='component', component='starA'), you
could do b.filter('starA@component').
:parameter bool check_visible: whether to hide invisible
parameters. These are usually parameters that do not
play a role unless the value of another parameter meets
some condition.
:parameter bool check_default: whether to exclude parameters which
have a _default tag (these are parameters which solely exist
to provide defaults for when new parameters or datasets are
added and the parameter needs to be copied appropriately).
Defaults to True.
:parameter **kwargs: meta-tags to search (ie. 'context', 'component',
'model', etc). See :func:`meta` for all possible options.
:return: the resulting :class:`ParameterSet`
"""
kwargs['check_visible'] = check_visible
kwargs['check_default'] = check_default
kwargs['force_ps'] = True
return self.filter_or_get(twig=twig, **kwargs) | [
"def",
"filter",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"check_visible",
"=",
"True",
",",
"check_default",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'check_visible'",
"]",
"=",
"check_visible",
"kwargs",
"[",
"'check_default'",
... | Filter the ParameterSet based on the meta-tags of the Parameters
and return another ParameterSet.
Because another ParameterSet is returned, these filter calls are
chainable.
>>> b.filter(context='component').filter(component='starA')
:parameter str twig: (optional) the search twig - essentially a single
string with any delimiter (ie '@') that will be parsed
into any of the meta-tags. Example: instead of
b.filter(context='component', component='starA'), you
could do b.filter('starA@component').
:parameter bool check_visible: whether to hide invisible
parameters. These are usually parameters that do not
play a role unless the value of another parameter meets
some condition.
:parameter bool check_default: whether to exclude parameters which
have a _default tag (these are parameters which solely exist
to provide defaults for when new parameters or datasets are
added and the parameter needs to be copied appropriately).
Defaults to True.
:parameter **kwargs: meta-tags to search (ie. 'context', 'component',
'model', etc). See :func:`meta` for all possible options.
:return: the resulting :class:`ParameterSet` | [
"Filter",
"the",
"ParameterSet",
"based",
"on",
"the",
"meta",
"-",
"tags",
"of",
"the",
"Parameters",
"and",
"return",
"another",
"ParameterSet",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L1283-L1314 | train | 39,955 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.get | def get(self, twig=None, check_visible=True, check_default=True, **kwargs):
"""
Get a single parameter from this ParameterSet. This works exactly the
same as filter except there must be only a single result, and the Parameter
itself is returned instead of a ParameterSet.
Also see :meth:`get_parameter` (which is simply an alias of this method)
:parameter str twig: (optional) the search twig - essentially a single
string with any delimiter (ie '@') that will be parsed
into any of the meta-tags. Example: instead of
b.filter(context='component', component='starA'), you
could do b.filter('starA@component').
:parameter bool check_visible: whether to hide invisible
parameters. These are usually parameters that do not
play a role unless the value of another parameter meets
some condition.
:parameter bool check_default: whether to exclude parameters which
have a _default tag (these are parameters which solely exist
to provide defaults for when new parameters or datasets are
added and the parameter needs to be copied appropriately).
Defaults to True.
:parameter **kwargs: meta-tags to search (ie. 'context', 'component',
'model', etc). See :func:`meta` for all possible options.
:return: the resulting :class:`Parameter`
:raises ValueError: if either 0 or more than 1 results are found
matching the search.
"""
kwargs['check_visible'] = check_visible
kwargs['check_default'] = check_default
# print "***", kwargs
ps = self.filter(twig=twig, **kwargs)
if not len(ps):
# TODO: custom exception?
raise ValueError("0 results found")
elif len(ps) != 1:
# TODO: custom exception?
raise ValueError("{} results found: {}".format(len(ps), ps.twigs))
else:
# then only 1 item, so return the parameter
return ps._params[0] | python | def get(self, twig=None, check_visible=True, check_default=True, **kwargs):
"""
Get a single parameter from this ParameterSet. This works exactly the
same as filter except there must be only a single result, and the Parameter
itself is returned instead of a ParameterSet.
Also see :meth:`get_parameter` (which is simply an alias of this method)
:parameter str twig: (optional) the search twig - essentially a single
string with any delimiter (ie '@') that will be parsed
into any of the meta-tags. Example: instead of
b.filter(context='component', component='starA'), you
could do b.filter('starA@component').
:parameter bool check_visible: whether to hide invisible
parameters. These are usually parameters that do not
play a role unless the value of another parameter meets
some condition.
:parameter bool check_default: whether to exclude parameters which
have a _default tag (these are parameters which solely exist
to provide defaults for when new parameters or datasets are
added and the parameter needs to be copied appropriately).
Defaults to True.
:parameter **kwargs: meta-tags to search (ie. 'context', 'component',
'model', etc). See :func:`meta` for all possible options.
:return: the resulting :class:`Parameter`
:raises ValueError: if either 0 or more than 1 results are found
matching the search.
"""
kwargs['check_visible'] = check_visible
kwargs['check_default'] = check_default
# print "***", kwargs
ps = self.filter(twig=twig, **kwargs)
if not len(ps):
# TODO: custom exception?
raise ValueError("0 results found")
elif len(ps) != 1:
# TODO: custom exception?
raise ValueError("{} results found: {}".format(len(ps), ps.twigs))
else:
# then only 1 item, so return the parameter
return ps._params[0] | [
"def",
"get",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"check_visible",
"=",
"True",
",",
"check_default",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'check_visible'",
"]",
"=",
"check_visible",
"kwargs",
"[",
"'check_default'",
"... | Get a single parameter from this ParameterSet. This works exactly the
same as filter except there must be only a single result, and the Parameter
itself is returned instead of a ParameterSet.
Also see :meth:`get_parameter` (which is simply an alias of this method)
:parameter str twig: (optional) the search twig - essentially a single
string with any delimiter (ie '@') that will be parsed
into any of the meta-tags. Example: instead of
b.filter(context='component', component='starA'), you
could do b.filter('starA@component').
:parameter bool check_visible: whether to hide invisible
parameters. These are usually parameters that do not
play a role unless the value of another parameter meets
some condition.
:parameter bool check_default: whether to exclude parameters which
have a _default tag (these are parameters which solely exist
to provide defaults for when new parameters or datasets are
added and the parameter needs to be copied appropriately).
Defaults to True.
:parameter **kwargs: meta-tags to search (ie. 'context', 'component',
'model', etc). See :func:`meta` for all possible options.
:return: the resulting :class:`Parameter`
:raises ValueError: if either 0 or more than 1 results are found
matching the search. | [
"Get",
"a",
"single",
"parameter",
"from",
"this",
"ParameterSet",
".",
"This",
"works",
"exactly",
"the",
"same",
"as",
"filter",
"except",
"there",
"must",
"be",
"only",
"a",
"single",
"result",
"and",
"the",
"Parameter",
"itself",
"is",
"returned",
"inste... | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L1316-L1357 | train | 39,956 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.exclude | def exclude(self, twig=None, check_visible=True, **kwargs):
"""
Exclude the results from this filter from the current ParameterSet.
See :meth:`filter` for options.
"""
return self - self.filter(twig=twig,
check_visible=check_visible,
**kwargs) | python | def exclude(self, twig=None, check_visible=True, **kwargs):
"""
Exclude the results from this filter from the current ParameterSet.
See :meth:`filter` for options.
"""
return self - self.filter(twig=twig,
check_visible=check_visible,
**kwargs) | [
"def",
"exclude",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"check_visible",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
"-",
"self",
".",
"filter",
"(",
"twig",
"=",
"twig",
",",
"check_visible",
"=",
"check_visible",
",",
"*... | Exclude the results from this filter from the current ParameterSet.
See :meth:`filter` for options. | [
"Exclude",
"the",
"results",
"from",
"this",
"filter",
"from",
"the",
"current",
"ParameterSet",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L1576-L1584 | train | 39,957 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet._remove_parameter | def _remove_parameter(self, param):
"""
Remove a Parameter from the ParameterSet
:parameter param: the :class:`Parameter` object to be removed
:type param: :class:`Parameter`
"""
# TODO: check to see if protected (required by a current constraint or
# by a backend)
self._params = [p for p in self._params if p != param] | python | def _remove_parameter(self, param):
"""
Remove a Parameter from the ParameterSet
:parameter param: the :class:`Parameter` object to be removed
:type param: :class:`Parameter`
"""
# TODO: check to see if protected (required by a current constraint or
# by a backend)
self._params = [p for p in self._params if p != param] | [
"def",
"_remove_parameter",
"(",
"self",
",",
"param",
")",
":",
"# TODO: check to see if protected (required by a current constraint or",
"# by a backend)",
"self",
".",
"_params",
"=",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"_params",
"if",
"p",
"!=",
"param",
... | Remove a Parameter from the ParameterSet
:parameter param: the :class:`Parameter` object to be removed
:type param: :class:`Parameter` | [
"Remove",
"a",
"Parameter",
"from",
"the",
"ParameterSet"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L1643-L1652 | train | 39,958 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.show | def show(self, **kwargs):
"""
Draw and show the plot.
"""
kwargs.setdefault('show', True)
kwargs.setdefault('save', False)
kwargs.setdefault('animate', False)
return self._show_or_save(**kwargs) | python | def show(self, **kwargs):
"""
Draw and show the plot.
"""
kwargs.setdefault('show', True)
kwargs.setdefault('save', False)
kwargs.setdefault('animate', False)
return self._show_or_save(**kwargs) | [
"def",
"show",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'show'",
",",
"True",
")",
"kwargs",
".",
"setdefault",
"(",
"'save'",
",",
"False",
")",
"kwargs",
".",
"setdefault",
"(",
"'animate'",
",",
"False",
"... | Draw and show the plot. | [
"Draw",
"and",
"show",
"the",
"plot",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L2783-L2790 | train | 39,959 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ParameterSet.savefig | def savefig(self, filename, **kwargs):
"""
Draw and save the plot.
:parameter str filename: filename to save to. Be careful of extensions here...
matplotlib accepts many different image formats while other
backends will only export to html.
"""
filename = os.path.expanduser(filename)
kwargs.setdefault('show', False)
kwargs.setdefault('save', filename)
kwargs.setdefault('animate', False)
return self._show_or_save(**kwargs) | python | def savefig(self, filename, **kwargs):
"""
Draw and save the plot.
:parameter str filename: filename to save to. Be careful of extensions here...
matplotlib accepts many different image formats while other
backends will only export to html.
"""
filename = os.path.expanduser(filename)
kwargs.setdefault('show', False)
kwargs.setdefault('save', filename)
kwargs.setdefault('animate', False)
return self._show_or_save(**kwargs) | [
"def",
"savefig",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"kwargs",
".",
"setdefault",
"(",
"'show'",
",",
"False",
")",
"kwargs",
".",
"setdefault",
... | Draw and save the plot.
:parameter str filename: filename to save to. Be careful of extensions here...
matplotlib accepts many different image formats while other
backends will only export to html. | [
"Draw",
"and",
"save",
"the",
"plot",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L2792-L2804 | train | 39,960 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | Parameter.save | def save(self, filename, incl_uniqueid=False):
"""
Save the Parameter to a JSON-formatted ASCII file
:parameter str filename: relative or fullpath to the file
:return: filename
:rtype: str
"""
filename = os.path.expanduser(filename)
f = open(filename, 'w')
json.dump(self.to_json(incl_uniqueid=incl_uniqueid), f,
sort_keys=True, indent=0, separators=(',', ': '))
f.close()
return filename | python | def save(self, filename, incl_uniqueid=False):
"""
Save the Parameter to a JSON-formatted ASCII file
:parameter str filename: relative or fullpath to the file
:return: filename
:rtype: str
"""
filename = os.path.expanduser(filename)
f = open(filename, 'w')
json.dump(self.to_json(incl_uniqueid=incl_uniqueid), f,
sort_keys=True, indent=0, separators=(',', ': '))
f.close()
return filename | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"incl_uniqueid",
"=",
"False",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"json",
".",
"dump",
"(",
"s... | Save the Parameter to a JSON-formatted ASCII file
:parameter str filename: relative or fullpath to the file
:return: filename
:rtype: str | [
"Save",
"the",
"Parameter",
"to",
"a",
"JSON",
"-",
"formatted",
"ASCII",
"file"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L3053-L3067 | train | 39,961 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | Parameter.get_meta | def get_meta(self, ignore=['uniqueid']):
"""
See all the meta-tag properties for this Parameter
:parameter list ignore: list of keys to exclude from the returned
dictionary
:return: an ordered dictionary of tag properties
"""
return OrderedDict([(k, getattr(self, k)) for k in _meta_fields_all if k not in ignore]) | python | def get_meta(self, ignore=['uniqueid']):
"""
See all the meta-tag properties for this Parameter
:parameter list ignore: list of keys to exclude from the returned
dictionary
:return: an ordered dictionary of tag properties
"""
return OrderedDict([(k, getattr(self, k)) for k in _meta_fields_all if k not in ignore]) | [
"def",
"get_meta",
"(",
"self",
",",
"ignore",
"=",
"[",
"'uniqueid'",
"]",
")",
":",
"return",
"OrderedDict",
"(",
"[",
"(",
"k",
",",
"getattr",
"(",
"self",
",",
"k",
")",
")",
"for",
"k",
"in",
"_meta_fields_all",
"if",
"k",
"not",
"in",
"ignor... | See all the meta-tag properties for this Parameter
:parameter list ignore: list of keys to exclude from the returned
dictionary
:return: an ordered dictionary of tag properties | [
"See",
"all",
"the",
"meta",
"-",
"tag",
"properties",
"for",
"this",
"Parameter"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L3130-L3138 | train | 39,962 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | SelectParameter.expand_value | def expand_value(self, **kwargs):
"""
expand the selection to account for wildcards
"""
selection = []
for v in self.get_value(**kwargs):
for choice in self.choices:
if v==choice and choice not in selection:
selection.append(choice)
elif fnmatch(choice, v) and choice not in selection:
selection.append(choice)
return selection | python | def expand_value(self, **kwargs):
"""
expand the selection to account for wildcards
"""
selection = []
for v in self.get_value(**kwargs):
for choice in self.choices:
if v==choice and choice not in selection:
selection.append(choice)
elif fnmatch(choice, v) and choice not in selection:
selection.append(choice)
return selection | [
"def",
"expand_value",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"selection",
"=",
"[",
"]",
"for",
"v",
"in",
"self",
".",
"get_value",
"(",
"*",
"*",
"kwargs",
")",
":",
"for",
"choice",
"in",
"self",
".",
"choices",
":",
"if",
"v",
"==",... | expand the selection to account for wildcards | [
"expand",
"the",
"selection",
"to",
"account",
"for",
"wildcards"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L3882-L3894 | train | 39,963 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | FloatParameter.is_constraint | def is_constraint(self):
"""
returns the expression of the constraint that constrains this parameter
"""
if self._is_constraint is None:
return None
return self._bundle.get_parameter(context='constraint', uniqueid=self._is_constraint) | python | def is_constraint(self):
"""
returns the expression of the constraint that constrains this parameter
"""
if self._is_constraint is None:
return None
return self._bundle.get_parameter(context='constraint', uniqueid=self._is_constraint) | [
"def",
"is_constraint",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_constraint",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"_bundle",
".",
"get_parameter",
"(",
"context",
"=",
"'constraint'",
",",
"uniqueid",
"=",
"self",
".",
"_is_co... | returns the expression of the constraint that constrains this parameter | [
"returns",
"the",
"expression",
"of",
"the",
"constraint",
"that",
"constrains",
"this",
"parameter"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4479-L4485 | train | 39,964 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | FloatParameter.constrained_by | def constrained_by(self):
"""
returns a list of parameters that constrain this parameter
"""
if self._is_constraint is None:
return []
params = []
for var in self.is_constraint._vars:
param = var.get_parameter()
if param.uniqueid != self.uniqueid:
params.append(param)
return params | python | def constrained_by(self):
"""
returns a list of parameters that constrain this parameter
"""
if self._is_constraint is None:
return []
params = []
for var in self.is_constraint._vars:
param = var.get_parameter()
if param.uniqueid != self.uniqueid:
params.append(param)
return params | [
"def",
"constrained_by",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_constraint",
"is",
"None",
":",
"return",
"[",
"]",
"params",
"=",
"[",
"]",
"for",
"var",
"in",
"self",
".",
"is_constraint",
".",
"_vars",
":",
"param",
"=",
"var",
".",
"get_p... | returns a list of parameters that constrain this parameter | [
"returns",
"a",
"list",
"of",
"parameters",
"that",
"constrain",
"this",
"parameter"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4488-L4499 | train | 39,965 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | FloatParameter.in_constraints | def in_constraints(self):
"""
returns a list of the expressions in which this parameter constrains another
"""
expressions = []
for uniqueid in self._in_constraints:
expressions.append(self._bundle.get_parameter(context='constraint', uniqueid=uniqueid))
return expressions | python | def in_constraints(self):
"""
returns a list of the expressions in which this parameter constrains another
"""
expressions = []
for uniqueid in self._in_constraints:
expressions.append(self._bundle.get_parameter(context='constraint', uniqueid=uniqueid))
return expressions | [
"def",
"in_constraints",
"(",
"self",
")",
":",
"expressions",
"=",
"[",
"]",
"for",
"uniqueid",
"in",
"self",
".",
"_in_constraints",
":",
"expressions",
".",
"append",
"(",
"self",
".",
"_bundle",
".",
"get_parameter",
"(",
"context",
"=",
"'constraint'",
... | returns a list of the expressions in which this parameter constrains another | [
"returns",
"a",
"list",
"of",
"the",
"expressions",
"in",
"which",
"this",
"parameter",
"constrains",
"another"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4511-L4518 | train | 39,966 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | FloatParameter.constrains | def constrains(self):
"""
returns a list of parameters that are constrained by this parameter
"""
params = []
for constraint in self.in_constraints:
for var in constraint._vars:
param = var.get_parameter()
if param.component == constraint.component and param.qualifier == constraint.qualifier:
if param not in params and param.uniqueid != self.uniqueid:
params.append(param)
return params | python | def constrains(self):
"""
returns a list of parameters that are constrained by this parameter
"""
params = []
for constraint in self.in_constraints:
for var in constraint._vars:
param = var.get_parameter()
if param.component == constraint.component and param.qualifier == constraint.qualifier:
if param not in params and param.uniqueid != self.uniqueid:
params.append(param)
return params | [
"def",
"constrains",
"(",
"self",
")",
":",
"params",
"=",
"[",
"]",
"for",
"constraint",
"in",
"self",
".",
"in_constraints",
":",
"for",
"var",
"in",
"constraint",
".",
"_vars",
":",
"param",
"=",
"var",
".",
"get_parameter",
"(",
")",
"if",
"param",... | returns a list of parameters that are constrained by this parameter | [
"returns",
"a",
"list",
"of",
"parameters",
"that",
"are",
"constrained",
"by",
"this",
"parameter"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4521-L4532 | train | 39,967 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | FloatParameter.related_to | def related_to(self):
"""
returns a list of all parameters that are either constrained by or constrain this parameter
"""
params = []
constraints = self.in_constraints
if self.is_constraint is not None:
constraints.append(self.is_constraint)
for constraint in constraints:
for var in constraint._vars:
param = var.get_parameter()
if param not in params and param.uniqueid != self.uniqueid:
params.append(param)
return params | python | def related_to(self):
"""
returns a list of all parameters that are either constrained by or constrain this parameter
"""
params = []
constraints = self.in_constraints
if self.is_constraint is not None:
constraints.append(self.is_constraint)
for constraint in constraints:
for var in constraint._vars:
param = var.get_parameter()
if param not in params and param.uniqueid != self.uniqueid:
params.append(param)
return params | [
"def",
"related_to",
"(",
"self",
")",
":",
"params",
"=",
"[",
"]",
"constraints",
"=",
"self",
".",
"in_constraints",
"if",
"self",
".",
"is_constraint",
"is",
"not",
"None",
":",
"constraints",
".",
"append",
"(",
"self",
".",
"is_constraint",
")",
"f... | returns a list of all parameters that are either constrained by or constrain this parameter | [
"returns",
"a",
"list",
"of",
"all",
"parameters",
"that",
"are",
"either",
"constrained",
"by",
"or",
"constrain",
"this",
"parameter"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4535-L4550 | train | 39,968 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | FloatArrayParameter.set_property | def set_property(self, **kwargs):
"""
set any property of the underlying nparray object
"""
if not isinstance(self._value, nparray.ndarray):
raise ValueError("value is not a nparray object")
for property, value in kwargs.items():
setattr(self._value, property, value) | python | def set_property(self, **kwargs):
"""
set any property of the underlying nparray object
"""
if not isinstance(self._value, nparray.ndarray):
raise ValueError("value is not a nparray object")
for property, value in kwargs.items():
setattr(self._value, property, value) | [
"def",
"set_property",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_value",
",",
"nparray",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"\"value is not a nparray object\"",
")",
"for",
"property",
... | set any property of the underlying nparray object | [
"set",
"any",
"property",
"of",
"the",
"underlying",
"nparray",
"object"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4756-L4764 | train | 39,969 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | HierarchyParameter._recurse_find_trace | def _recurse_find_trace(self, structure, item, trace=[]):
"""
given a nested structure from _parse_repr and find the trace route to get to item
"""
try:
i = structure.index(item)
except ValueError:
for j,substructure in enumerate(structure):
if isinstance(substructure, list):
return self._recurse_find_trace(substructure, item, trace+[j])
else:
return trace+[i] | python | def _recurse_find_trace(self, structure, item, trace=[]):
"""
given a nested structure from _parse_repr and find the trace route to get to item
"""
try:
i = structure.index(item)
except ValueError:
for j,substructure in enumerate(structure):
if isinstance(substructure, list):
return self._recurse_find_trace(substructure, item, trace+[j])
else:
return trace+[i] | [
"def",
"_recurse_find_trace",
"(",
"self",
",",
"structure",
",",
"item",
",",
"trace",
"=",
"[",
"]",
")",
":",
"try",
":",
"i",
"=",
"structure",
".",
"index",
"(",
"item",
")",
"except",
"ValueError",
":",
"for",
"j",
",",
"substructure",
"in",
"e... | given a nested structure from _parse_repr and find the trace route to get to item | [
"given",
"a",
"nested",
"structure",
"from",
"_parse_repr",
"and",
"find",
"the",
"trace",
"route",
"to",
"get",
"to",
"item"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4948-L4960 | train | 39,970 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | HierarchyParameter.get_stars | def get_stars(self):
"""
get 'component' of all stars in order primary -> secondary
"""
l = re.findall(r"[\w']+", self.get_value())
# now search for indices of star and take the next entry from this flat list
return [l[i+1] for i,s in enumerate(l) if s=='star'] | python | def get_stars(self):
"""
get 'component' of all stars in order primary -> secondary
"""
l = re.findall(r"[\w']+", self.get_value())
# now search for indices of star and take the next entry from this flat list
return [l[i+1] for i,s in enumerate(l) if s=='star'] | [
"def",
"get_stars",
"(",
"self",
")",
":",
"l",
"=",
"re",
".",
"findall",
"(",
"r\"[\\w']+\"",
",",
"self",
".",
"get_value",
"(",
")",
")",
"# now search for indices of star and take the next entry from this flat list",
"return",
"[",
"l",
"[",
"i",
"+",
"1",
... | get 'component' of all stars in order primary -> secondary | [
"get",
"component",
"of",
"all",
"stars",
"in",
"order",
"primary",
"-",
">",
"secondary"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L5008-L5014 | train | 39,971 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | HierarchyParameter.get_orbits | def get_orbits(self):
"""
get 'component' of all orbits in order primary -> secondary
"""
#~ l = re.findall(r"[\w']+", self.get_value())
# now search for indices of orbit and take the next entry from this flat list
#~ return [l[i+1] for i,s in enumerate(l) if s=='orbit']
orbits = []
for star in self.get_stars():
parent = self.get_parent_of(star)
if parent not in orbits and parent!='component' and parent is not None:
orbits.append(parent)
return orbits | python | def get_orbits(self):
"""
get 'component' of all orbits in order primary -> secondary
"""
#~ l = re.findall(r"[\w']+", self.get_value())
# now search for indices of orbit and take the next entry from this flat list
#~ return [l[i+1] for i,s in enumerate(l) if s=='orbit']
orbits = []
for star in self.get_stars():
parent = self.get_parent_of(star)
if parent not in orbits and parent!='component' and parent is not None:
orbits.append(parent)
return orbits | [
"def",
"get_orbits",
"(",
"self",
")",
":",
"#~ l = re.findall(r\"[\\w']+\", self.get_value())",
"# now search for indices of orbit and take the next entry from this flat list",
"#~ return [l[i+1] for i,s in enumerate(l) if s=='orbit']",
"orbits",
"=",
"[",
"]",
"for",
"star",
"in",
... | get 'component' of all orbits in order primary -> secondary | [
"get",
"component",
"of",
"all",
"orbits",
"in",
"order",
"primary",
"-",
">",
"secondary"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L5024-L5036 | train | 39,972 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | HierarchyParameter.get_stars_of_sibling_of | def get_stars_of_sibling_of(self, component):
"""
same as get_sibling_of except if the sibling is an orbit, this will recursively
follow the tree to return a list of all stars under that orbit
"""
sibling = self.get_sibling_of(component)
if sibling in self.get_stars():
return sibling
stars = [child for child in self.get_stars_of_children_of(sibling)]
# TODO: do we need to make sure there aren't duplicates?
# return list(set(stars))
return stars | python | def get_stars_of_sibling_of(self, component):
"""
same as get_sibling_of except if the sibling is an orbit, this will recursively
follow the tree to return a list of all stars under that orbit
"""
sibling = self.get_sibling_of(component)
if sibling in self.get_stars():
return sibling
stars = [child for child in self.get_stars_of_children_of(sibling)]
# TODO: do we need to make sure there aren't duplicates?
# return list(set(stars))
return stars | [
"def",
"get_stars_of_sibling_of",
"(",
"self",
",",
"component",
")",
":",
"sibling",
"=",
"self",
".",
"get_sibling_of",
"(",
"component",
")",
"if",
"sibling",
"in",
"self",
".",
"get_stars",
"(",
")",
":",
"return",
"sibling",
"stars",
"=",
"[",
"child"... | same as get_sibling_of except if the sibling is an orbit, this will recursively
follow the tree to return a list of all stars under that orbit | [
"same",
"as",
"get_sibling_of",
"except",
"if",
"the",
"sibling",
"is",
"an",
"orbit",
"this",
"will",
"recursively",
"follow",
"the",
"tree",
"to",
"return",
"a",
"list",
"of",
"all",
"stars",
"under",
"that",
"orbit"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L5097-L5113 | train | 39,973 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | HierarchyParameter.get_children_of | def get_children_of(self, component, kind=None):
"""
get to component labels of the children of a given component
"""
structure, trace, item = self._get_structure_and_trace(component)
item_kind, item_label = item.split(':')
if isinstance(kind, str):
kind = [kind]
if item_kind not in ['orbit']:
# return None
return []
else:
items = self._get_by_trace(structure, trace[:-1]+[trace[-1]+1])
# we want to ignore suborbits
#return [str(ch.split(':')[-1]) for ch in items if isinstance(ch, unicode)]
return [str(ch.split(':')[-1]) for ch in items if isinstance(ch, unicode) and (kind is None or ch.split(':')[0] in kind)] | python | def get_children_of(self, component, kind=None):
"""
get to component labels of the children of a given component
"""
structure, trace, item = self._get_structure_and_trace(component)
item_kind, item_label = item.split(':')
if isinstance(kind, str):
kind = [kind]
if item_kind not in ['orbit']:
# return None
return []
else:
items = self._get_by_trace(structure, trace[:-1]+[trace[-1]+1])
# we want to ignore suborbits
#return [str(ch.split(':')[-1]) for ch in items if isinstance(ch, unicode)]
return [str(ch.split(':')[-1]) for ch in items if isinstance(ch, unicode) and (kind is None or ch.split(':')[0] in kind)] | [
"def",
"get_children_of",
"(",
"self",
",",
"component",
",",
"kind",
"=",
"None",
")",
":",
"structure",
",",
"trace",
",",
"item",
"=",
"self",
".",
"_get_structure_and_trace",
"(",
"component",
")",
"item_kind",
",",
"item_label",
"=",
"item",
".",
"spl... | get to component labels of the children of a given component | [
"get",
"to",
"component",
"labels",
"of",
"the",
"children",
"of",
"a",
"given",
"component"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L5116-L5134 | train | 39,974 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | HierarchyParameter.get_primary_or_secondary | def get_primary_or_secondary(self, component, return_ind=False):
"""
return whether a given component is the 'primary' or 'secondary'
component in its parent orbit
"""
parent = self.get_parent_of(component)
if parent is None:
# then this is a single component, not in a binary
return 'primary'
children_of_parent = self.get_children_of(parent)
ind = children_of_parent.index(component)
if ind > 1:
return None
if return_ind:
return ind + 1
return ['primary', 'secondary'][ind] | python | def get_primary_or_secondary(self, component, return_ind=False):
"""
return whether a given component is the 'primary' or 'secondary'
component in its parent orbit
"""
parent = self.get_parent_of(component)
if parent is None:
# then this is a single component, not in a binary
return 'primary'
children_of_parent = self.get_children_of(parent)
ind = children_of_parent.index(component)
if ind > 1:
return None
if return_ind:
return ind + 1
return ['primary', 'secondary'][ind] | [
"def",
"get_primary_or_secondary",
"(",
"self",
",",
"component",
",",
"return_ind",
"=",
"False",
")",
":",
"parent",
"=",
"self",
".",
"get_parent_of",
"(",
"component",
")",
"if",
"parent",
"is",
"None",
":",
"# then this is a single component, not in a binary",
... | return whether a given component is the 'primary' or 'secondary'
component in its parent orbit | [
"return",
"whether",
"a",
"given",
"component",
"is",
"the",
"primary",
"or",
"secondary",
"component",
"in",
"its",
"parent",
"orbit"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L5171-L5191 | train | 39,975 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ConstraintParameter.vars | def vars(self):
"""
return all the variables in a PS
"""
# cache _var_params
if self._var_params is None:
self._var_params = ParameterSet([var.get_parameter() for var in self._vars])
return self._var_params | python | def vars(self):
"""
return all the variables in a PS
"""
# cache _var_params
if self._var_params is None:
self._var_params = ParameterSet([var.get_parameter() for var in self._vars])
return self._var_params | [
"def",
"vars",
"(",
"self",
")",
":",
"# cache _var_params",
"if",
"self",
".",
"_var_params",
"is",
"None",
":",
"self",
".",
"_var_params",
"=",
"ParameterSet",
"(",
"[",
"var",
".",
"get_parameter",
"(",
")",
"for",
"var",
"in",
"self",
".",
"_vars",
... | return all the variables in a PS | [
"return",
"all",
"the",
"variables",
"in",
"a",
"PS"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L5331-L5338 | train | 39,976 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ConstraintParameter.get_parameter | def get_parameter(self, twig=None, **kwargs):
"""
get a parameter from those that are variables
"""
kwargs['twig'] = twig
kwargs['check_default'] = False
kwargs['check_visible'] = False
ps = self.vars.filter(**kwargs)
if len(ps)==1:
return ps.get(check_visible=False, check_default=False)
elif len(ps) > 1:
# TODO: is this safe? Some constraints may have a parameter listed
# twice, so we can do this then, but maybe should check to make sure
# all items have the same uniqueid? Maybe check len(ps.uniqueids)?
return ps.to_list()[0]
else:
raise KeyError("no result found") | python | def get_parameter(self, twig=None, **kwargs):
"""
get a parameter from those that are variables
"""
kwargs['twig'] = twig
kwargs['check_default'] = False
kwargs['check_visible'] = False
ps = self.vars.filter(**kwargs)
if len(ps)==1:
return ps.get(check_visible=False, check_default=False)
elif len(ps) > 1:
# TODO: is this safe? Some constraints may have a parameter listed
# twice, so we can do this then, but maybe should check to make sure
# all items have the same uniqueid? Maybe check len(ps.uniqueids)?
return ps.to_list()[0]
else:
raise KeyError("no result found") | [
"def",
"get_parameter",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'twig'",
"]",
"=",
"twig",
"kwargs",
"[",
"'check_default'",
"]",
"=",
"False",
"kwargs",
"[",
"'check_visible'",
"]",
"=",
"False",
"ps",... | get a parameter from those that are variables | [
"get",
"a",
"parameter",
"from",
"those",
"that",
"are",
"variables"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L5404-L5420 | train | 39,977 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | ConstraintParameter.flip_for | def flip_for(self, twig=None, expression=None, **kwargs):
"""
flip the constraint to solve for for any of the parameters in the expression
expression (optional if sympy available, required if not)
"""
_orig_expression = self.get_value()
# try to get the parameter from the bundle
kwargs['twig'] = twig
newly_constrained_var = self._get_var(**kwargs)
newly_constrained_param = self.get_parameter(**kwargs)
check_kwargs = {k:v for k,v in newly_constrained_param.meta.items() if k not in ['context', 'twig', 'uniquetwig']}
check_kwargs['context'] = 'constraint'
if len(self._bundle.filter(**check_kwargs)):
raise ValueError("'{}' is already constrained".format(newly_constrained_param.twig))
currently_constrained_var = self._get_var(qualifier=self.qualifier, component=self.component)
currently_constrained_param = currently_constrained_var.get_parameter() # or self.constrained_parameter
import constraint
if self.constraint_func is not None and hasattr(constraint, self.constraint_func):
# then let's see if the method is capable of resolving for use
# try:
if True:
# TODO: this is not nearly general enough, each method takes different arguments
# and getting solve_for as newly_constrained_param.qualifier
lhs, rhs, constraint_kwargs = getattr(constraint, self.constraint_func)(self._bundle, solve_for=newly_constrained_param, **self.constraint_kwargs)
# except NotImplementedError:
# pass
# else:
# TODO: this needs to be smarter and match to self._get_var().user_label instead of the current uniquetwig
expression = rhs._value # safe expression
#~ print "*** flip by recalling method success!", expression
# print "***", lhs._value, rhs._value
if expression is not None:
expression = expression
elif _use_sympy:
eq_safe = "({}) - {}".format(self._value, currently_constrained_var.safe_label)
#~ print "*** solving {} for {}".format(eq_safe, newly_constrained_var.safe_label)
expression = sympy.solve(eq_safe, newly_constrained_var.safe_label)[0]
#~ print "*** solution: {}".format(expression)
else:
# TODO: ability for built-in constraints to flip themselves
# we could access self.kind and re-call that with a new solve_for option?
raise ValueError("must either have sympy installed or provide a new expression")
self._qualifier = newly_constrained_param.qualifier
self._component = newly_constrained_param.component
self._kind = newly_constrained_param.kind
self._value = str(expression)
# reset the default_unit so that set_default_unit doesn't complain
# about incompatible units
self._default_unit = None
self.set_default_unit(newly_constrained_param.default_unit)
self._update_bookkeeping()
self._add_history(redo_func='flip_constraint', redo_kwargs={'expression': expression, 'uniqueid': newly_constrained_param.uniqueid}, undo_func='flip_constraint', undo_kwargs={'expression': _orig_expression, 'uniqueid': currently_constrained_param.uniqueid}) | python | def flip_for(self, twig=None, expression=None, **kwargs):
"""
flip the constraint to solve for for any of the parameters in the expression
expression (optional if sympy available, required if not)
"""
_orig_expression = self.get_value()
# try to get the parameter from the bundle
kwargs['twig'] = twig
newly_constrained_var = self._get_var(**kwargs)
newly_constrained_param = self.get_parameter(**kwargs)
check_kwargs = {k:v for k,v in newly_constrained_param.meta.items() if k not in ['context', 'twig', 'uniquetwig']}
check_kwargs['context'] = 'constraint'
if len(self._bundle.filter(**check_kwargs)):
raise ValueError("'{}' is already constrained".format(newly_constrained_param.twig))
currently_constrained_var = self._get_var(qualifier=self.qualifier, component=self.component)
currently_constrained_param = currently_constrained_var.get_parameter() # or self.constrained_parameter
import constraint
if self.constraint_func is not None and hasattr(constraint, self.constraint_func):
# then let's see if the method is capable of resolving for use
# try:
if True:
# TODO: this is not nearly general enough, each method takes different arguments
# and getting solve_for as newly_constrained_param.qualifier
lhs, rhs, constraint_kwargs = getattr(constraint, self.constraint_func)(self._bundle, solve_for=newly_constrained_param, **self.constraint_kwargs)
# except NotImplementedError:
# pass
# else:
# TODO: this needs to be smarter and match to self._get_var().user_label instead of the current uniquetwig
expression = rhs._value # safe expression
#~ print "*** flip by recalling method success!", expression
# print "***", lhs._value, rhs._value
if expression is not None:
expression = expression
elif _use_sympy:
eq_safe = "({}) - {}".format(self._value, currently_constrained_var.safe_label)
#~ print "*** solving {} for {}".format(eq_safe, newly_constrained_var.safe_label)
expression = sympy.solve(eq_safe, newly_constrained_var.safe_label)[0]
#~ print "*** solution: {}".format(expression)
else:
# TODO: ability for built-in constraints to flip themselves
# we could access self.kind and re-call that with a new solve_for option?
raise ValueError("must either have sympy installed or provide a new expression")
self._qualifier = newly_constrained_param.qualifier
self._component = newly_constrained_param.component
self._kind = newly_constrained_param.kind
self._value = str(expression)
# reset the default_unit so that set_default_unit doesn't complain
# about incompatible units
self._default_unit = None
self.set_default_unit(newly_constrained_param.default_unit)
self._update_bookkeeping()
self._add_history(redo_func='flip_constraint', redo_kwargs={'expression': expression, 'uniqueid': newly_constrained_param.uniqueid}, undo_func='flip_constraint', undo_kwargs={'expression': _orig_expression, 'uniqueid': currently_constrained_param.uniqueid}) | [
"def",
"flip_for",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"expression",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_orig_expression",
"=",
"self",
".",
"get_value",
"(",
")",
"# try to get the parameter from the bundle",
"kwargs",
"[",
"'twig'",
"... | flip the constraint to solve for for any of the parameters in the expression
expression (optional if sympy available, required if not) | [
"flip",
"the",
"constraint",
"to",
"solve",
"for",
"for",
"any",
"of",
"the",
"parameters",
"in",
"the",
"expression"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L5719-L5791 | train | 39,978 |
pinax/pinax-teams | pinax/teams/views.py | TeamInviteView.get_unbound_form | def get_unbound_form(self):
"""
Overrides behavior of FormView.get_form_kwargs
when method is POST or PUT
"""
form_kwargs = self.get_form_kwargs()
# @@@ remove fields that would cause the form to be bound
# when instantiated
bound_fields = ["data", "files"]
for field in bound_fields:
form_kwargs.pop(field, None)
return self.get_form_class()(**form_kwargs) | python | def get_unbound_form(self):
"""
Overrides behavior of FormView.get_form_kwargs
when method is POST or PUT
"""
form_kwargs = self.get_form_kwargs()
# @@@ remove fields that would cause the form to be bound
# when instantiated
bound_fields = ["data", "files"]
for field in bound_fields:
form_kwargs.pop(field, None)
return self.get_form_class()(**form_kwargs) | [
"def",
"get_unbound_form",
"(",
"self",
")",
":",
"form_kwargs",
"=",
"self",
".",
"get_form_kwargs",
"(",
")",
"# @@@ remove fields that would cause the form to be bound",
"# when instantiated",
"bound_fields",
"=",
"[",
"\"data\"",
",",
"\"files\"",
"]",
"for",
"field... | Overrides behavior of FormView.get_form_kwargs
when method is POST or PUT | [
"Overrides",
"behavior",
"of",
"FormView",
".",
"get_form_kwargs",
"when",
"method",
"is",
"POST",
"or",
"PUT"
] | f8354ba0d32b3979d1dc18f50d23fd0096445ab7 | https://github.com/pinax/pinax-teams/blob/f8354ba0d32b3979d1dc18f50d23fd0096445ab7/pinax/teams/views.py#L216-L227 | train | 39,979 |
pinax/pinax-teams | pinax/teams/views.py | TeamInviteView.get_form_success_data | def get_form_success_data(self, form):
"""
Allows customization of the JSON data returned when a valid form submission occurs.
"""
data = {
"html": render_to_string(
"pinax/teams/_invite_form.html",
{
"invite_form": self.get_unbound_form(),
"team": self.team
},
request=self.request
)
}
membership = self.membership
if membership is not None:
if membership.state == Membership.STATE_APPLIED:
fragment_class = ".applicants"
elif membership.state == Membership.STATE_INVITED:
fragment_class = ".invitees"
elif membership.state in (Membership.STATE_AUTO_JOINED, Membership.STATE_ACCEPTED):
fragment_class = {
Membership.ROLE_OWNER: ".owners",
Membership.ROLE_MANAGER: ".managers",
Membership.ROLE_MEMBER: ".members"
}[membership.role]
data.update({
"append-fragments": {
fragment_class: render_to_string(
"pinax/teams/_membership.html",
{
"membership": membership,
"team": self.team
},
request=self.request
)
}
})
return data | python | def get_form_success_data(self, form):
"""
Allows customization of the JSON data returned when a valid form submission occurs.
"""
data = {
"html": render_to_string(
"pinax/teams/_invite_form.html",
{
"invite_form": self.get_unbound_form(),
"team": self.team
},
request=self.request
)
}
membership = self.membership
if membership is not None:
if membership.state == Membership.STATE_APPLIED:
fragment_class = ".applicants"
elif membership.state == Membership.STATE_INVITED:
fragment_class = ".invitees"
elif membership.state in (Membership.STATE_AUTO_JOINED, Membership.STATE_ACCEPTED):
fragment_class = {
Membership.ROLE_OWNER: ".owners",
Membership.ROLE_MANAGER: ".managers",
Membership.ROLE_MEMBER: ".members"
}[membership.role]
data.update({
"append-fragments": {
fragment_class: render_to_string(
"pinax/teams/_membership.html",
{
"membership": membership,
"team": self.team
},
request=self.request
)
}
})
return data | [
"def",
"get_form_success_data",
"(",
"self",
",",
"form",
")",
":",
"data",
"=",
"{",
"\"html\"",
":",
"render_to_string",
"(",
"\"pinax/teams/_invite_form.html\"",
",",
"{",
"\"invite_form\"",
":",
"self",
".",
"get_unbound_form",
"(",
")",
",",
"\"team\"",
":"... | Allows customization of the JSON data returned when a valid form submission occurs. | [
"Allows",
"customization",
"of",
"the",
"JSON",
"data",
"returned",
"when",
"a",
"valid",
"form",
"submission",
"occurs",
"."
] | f8354ba0d32b3979d1dc18f50d23fd0096445ab7 | https://github.com/pinax/pinax-teams/blob/f8354ba0d32b3979d1dc18f50d23fd0096445ab7/pinax/teams/views.py#L236-L275 | train | 39,980 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | _value | def _value(obj):
"""
make sure to get a float
"""
# TODO: this is ugly and makes everything ugly
# can we handle this with a clean decorator or just requiring that only floats be passed??
if hasattr(obj, 'value'):
return obj.value
elif isinstance(obj, np.ndarray):
return np.array([o.value for o in obj])
elif hasattr(obj, '__iter__'):
return [_value(o) for o in obj]
return obj | python | def _value(obj):
"""
make sure to get a float
"""
# TODO: this is ugly and makes everything ugly
# can we handle this with a clean decorator or just requiring that only floats be passed??
if hasattr(obj, 'value'):
return obj.value
elif isinstance(obj, np.ndarray):
return np.array([o.value for o in obj])
elif hasattr(obj, '__iter__'):
return [_value(o) for o in obj]
return obj | [
"def",
"_value",
"(",
"obj",
")",
":",
"# TODO: this is ugly and makes everything ugly",
"# can we handle this with a clean decorator or just requiring that only floats be passed??",
"if",
"hasattr",
"(",
"obj",
",",
"'value'",
")",
":",
"return",
"obj",
".",
"value",
"elif",... | make sure to get a float | [
"make",
"sure",
"to",
"get",
"a",
"float"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L74-L86 | train | 39,981 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | _estimate_delta | def _estimate_delta(ntriangles, area):
"""
estimate the value for delta to send to marching based on the number of
requested triangles and the expected surface area of mesh
"""
return np.sqrt(4./np.sqrt(3) * float(area) / float(ntriangles)) | python | def _estimate_delta(ntriangles, area):
"""
estimate the value for delta to send to marching based on the number of
requested triangles and the expected surface area of mesh
"""
return np.sqrt(4./np.sqrt(3) * float(area) / float(ntriangles)) | [
"def",
"_estimate_delta",
"(",
"ntriangles",
",",
"area",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"4.",
"/",
"np",
".",
"sqrt",
"(",
"3",
")",
"*",
"float",
"(",
"area",
")",
"/",
"float",
"(",
"ntriangles",
")",
")"
] | estimate the value for delta to send to marching based on the number of
requested triangles and the expected surface area of mesh | [
"estimate",
"the",
"value",
"for",
"delta",
"to",
"send",
"to",
"marching",
"based",
"on",
"the",
"number",
"of",
"requested",
"triangles",
"and",
"the",
"expected",
"surface",
"area",
"of",
"mesh"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L88-L93 | train | 39,982 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | System.handle_eclipses | def handle_eclipses(self, expose_horizon=False, **kwargs):
"""
Detect the triangles at the horizon and the eclipsed triangles, handling
any necessary subdivision.
:parameter str eclipse_method: name of the algorithm to use to detect
the horizon or eclipses (defaults to the value set by computeoptions)
:parameter str subdiv_alg: name of the algorithm to use for subdivision
(defaults to the value set by computeoptions)
:parameter int subdiv_num: number of subdivision iterations (defaults
the value set by computeoptions)
"""
eclipse_method = kwargs.get('eclipse_method', self.eclipse_method)
horizon_method = kwargs.get('horizon_method', self.horizon_method)
# Let's first check to see if eclipses are even possible at these
# positions. If they are not, then we only have to do horizon
#
# To do that, we'll take the conservative max_r for each object
# and their current positions, and see if the separations are larger
# than sum of max_rs
possible_eclipse = False
if len(self.bodies) == 1:
if self.bodies[0].__class__.__name__ == 'Envelope':
possible_eclipse = True
else:
possible_eclipse = False
else:
logger.debug("system.handle_eclipses: determining if eclipses are possible from instantaneous_maxr")
max_rs = [body.instantaneous_maxr for body in self.bodies]
# logger.debug("system.handle_eclipses: max_rs={}".format(max_rs))
for i in range(0, len(max_rs)-1):
for j in range(i+1, len(max_rs)):
proj_sep_sq = sum([(c[i]-c[j])**2 for c in (self.xs,self.ys)])
max_sep_ecl = max_rs[i] + max_rs[j]
if proj_sep_sq < (1.05*max_sep_ecl)**2:
# then this pair has the potential for eclipsing triangles
possible_eclipse = True
break
if not possible_eclipse and not expose_horizon and horizon_method=='boolean':
eclipse_method = 'only_horizon'
# meshes is an object which allows us to easily access and update columns
# in the meshes *in memory*. That is meshes.update_columns will propogate
# back to the current mesh for each body.
meshes = self.meshes
# Reset all visibilities to be fully visible to start
meshes.update_columns('visiblities', 1.0)
ecl_func = getattr(eclipse, eclipse_method)
if eclipse_method=='native':
ecl_kwargs = {'horizon_method': horizon_method}
else:
ecl_kwargs = {}
logger.debug("system.handle_eclipses: possible_eclipse={}, expose_horizon={}, calling {} with kwargs {}".format(possible_eclipse, expose_horizon, eclipse_method, ecl_kwargs))
visibilities, weights, horizon = ecl_func(meshes,
self.xs, self.ys, self.zs,
expose_horizon=expose_horizon,
**ecl_kwargs)
# NOTE: analytic horizons are called in backends.py since they don't
# actually depend on the mesh at all.
# visiblilities here is a dictionary with keys being the component
# labels and values being the np arrays of visibilities. We can pass
# this dictionary directly and the columns will be applied respectively.
meshes.update_columns('visibilities', visibilities)
# weights is also a dictionary with keys being the component labels
# and values and np array of weights.
if weights is not None:
meshes.update_columns('weights', weights)
return horizon | python | def handle_eclipses(self, expose_horizon=False, **kwargs):
"""
Detect the triangles at the horizon and the eclipsed triangles, handling
any necessary subdivision.
:parameter str eclipse_method: name of the algorithm to use to detect
the horizon or eclipses (defaults to the value set by computeoptions)
:parameter str subdiv_alg: name of the algorithm to use for subdivision
(defaults to the value set by computeoptions)
:parameter int subdiv_num: number of subdivision iterations (defaults
the value set by computeoptions)
"""
eclipse_method = kwargs.get('eclipse_method', self.eclipse_method)
horizon_method = kwargs.get('horizon_method', self.horizon_method)
# Let's first check to see if eclipses are even possible at these
# positions. If they are not, then we only have to do horizon
#
# To do that, we'll take the conservative max_r for each object
# and their current positions, and see if the separations are larger
# than sum of max_rs
possible_eclipse = False
if len(self.bodies) == 1:
if self.bodies[0].__class__.__name__ == 'Envelope':
possible_eclipse = True
else:
possible_eclipse = False
else:
logger.debug("system.handle_eclipses: determining if eclipses are possible from instantaneous_maxr")
max_rs = [body.instantaneous_maxr for body in self.bodies]
# logger.debug("system.handle_eclipses: max_rs={}".format(max_rs))
for i in range(0, len(max_rs)-1):
for j in range(i+1, len(max_rs)):
proj_sep_sq = sum([(c[i]-c[j])**2 for c in (self.xs,self.ys)])
max_sep_ecl = max_rs[i] + max_rs[j]
if proj_sep_sq < (1.05*max_sep_ecl)**2:
# then this pair has the potential for eclipsing triangles
possible_eclipse = True
break
if not possible_eclipse and not expose_horizon and horizon_method=='boolean':
eclipse_method = 'only_horizon'
# meshes is an object which allows us to easily access and update columns
# in the meshes *in memory*. That is meshes.update_columns will propogate
# back to the current mesh for each body.
meshes = self.meshes
# Reset all visibilities to be fully visible to start
meshes.update_columns('visiblities', 1.0)
ecl_func = getattr(eclipse, eclipse_method)
if eclipse_method=='native':
ecl_kwargs = {'horizon_method': horizon_method}
else:
ecl_kwargs = {}
logger.debug("system.handle_eclipses: possible_eclipse={}, expose_horizon={}, calling {} with kwargs {}".format(possible_eclipse, expose_horizon, eclipse_method, ecl_kwargs))
visibilities, weights, horizon = ecl_func(meshes,
self.xs, self.ys, self.zs,
expose_horizon=expose_horizon,
**ecl_kwargs)
# NOTE: analytic horizons are called in backends.py since they don't
# actually depend on the mesh at all.
# visiblilities here is a dictionary with keys being the component
# labels and values being the np arrays of visibilities. We can pass
# this dictionary directly and the columns will be applied respectively.
meshes.update_columns('visibilities', visibilities)
# weights is also a dictionary with keys being the component labels
# and values and np array of weights.
if weights is not None:
meshes.update_columns('weights', weights)
return horizon | [
"def",
"handle_eclipses",
"(",
"self",
",",
"expose_horizon",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"eclipse_method",
"=",
"kwargs",
".",
"get",
"(",
"'eclipse_method'",
",",
"self",
".",
"eclipse_method",
")",
"horizon_method",
"=",
"kwargs",
"."... | Detect the triangles at the horizon and the eclipsed triangles, handling
any necessary subdivision.
:parameter str eclipse_method: name of the algorithm to use to detect
the horizon or eclipses (defaults to the value set by computeoptions)
:parameter str subdiv_alg: name of the algorithm to use for subdivision
(defaults to the value set by computeoptions)
:parameter int subdiv_num: number of subdivision iterations (defaults
the value set by computeoptions) | [
"Detect",
"the",
"triangles",
"at",
"the",
"horizon",
"and",
"the",
"eclipsed",
"triangles",
"handling",
"any",
"necessary",
"subdivision",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L464-L544 | train | 39,983 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | Star.compute_pblum_scale | def compute_pblum_scale(self, dataset, pblum, **kwargs):
"""
intensities should already be computed for this dataset at the time for which pblum is being provided
TODO: add documentation
"""
logger.debug("{}.compute_pblum_scale(dataset={}, pblum={})".format(self.component, dataset, pblum))
abs_luminosity = self.compute_luminosity(dataset, **kwargs)
# We now want to remember the scale for all intensities such that the
# luminosity in relative units gives the provided pblum
pblum_scale = pblum / abs_luminosity
self.set_pblum_scale(dataset, pblum_scale) | python | def compute_pblum_scale(self, dataset, pblum, **kwargs):
"""
intensities should already be computed for this dataset at the time for which pblum is being provided
TODO: add documentation
"""
logger.debug("{}.compute_pblum_scale(dataset={}, pblum={})".format(self.component, dataset, pblum))
abs_luminosity = self.compute_luminosity(dataset, **kwargs)
# We now want to remember the scale for all intensities such that the
# luminosity in relative units gives the provided pblum
pblum_scale = pblum / abs_luminosity
self.set_pblum_scale(dataset, pblum_scale) | [
"def",
"compute_pblum_scale",
"(",
"self",
",",
"dataset",
",",
"pblum",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}.compute_pblum_scale(dataset={}, pblum={})\"",
".",
"format",
"(",
"self",
".",
"component",
",",
"dataset",
",",
"pbl... | intensities should already be computed for this dataset at the time for which pblum is being provided
TODO: add documentation | [
"intensities",
"should",
"already",
"be",
"computed",
"for",
"this",
"dataset",
"at",
"the",
"time",
"for",
"which",
"pblum",
"is",
"being",
"provided"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L1655-L1669 | train | 39,984 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | Star._populate_lp | def _populate_lp(self, dataset, **kwargs):
"""
Populate columns necessary for an LP dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables`
"""
logger.debug("{}._populate_lp(dataset={})".format(self.component, dataset))
profile_rest = kwargs.get('profile_rest', self.lp_profile_rest.get(dataset))
rv_cols = self._populate_rv(dataset, **kwargs)
cols = rv_cols
# rvs = (rv_cols['rvs']*u.solRad/u.d).to(u.m/u.s).value
# cols['dls'] = rv_cols['rvs']*profile_rest/c.c.si.value
return cols | python | def _populate_lp(self, dataset, **kwargs):
"""
Populate columns necessary for an LP dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables`
"""
logger.debug("{}._populate_lp(dataset={})".format(self.component, dataset))
profile_rest = kwargs.get('profile_rest', self.lp_profile_rest.get(dataset))
rv_cols = self._populate_rv(dataset, **kwargs)
cols = rv_cols
# rvs = (rv_cols['rvs']*u.solRad/u.d).to(u.m/u.s).value
# cols['dls'] = rv_cols['rvs']*profile_rest/c.c.si.value
return cols | [
"def",
"_populate_lp",
"(",
"self",
",",
"dataset",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}._populate_lp(dataset={})\"",
".",
"format",
"(",
"self",
".",
"component",
",",
"dataset",
")",
")",
"profile_rest",
"=",
"kwargs",
".... | Populate columns necessary for an LP dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables` | [
"Populate",
"columns",
"necessary",
"for",
"an",
"LP",
"dataset"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L1699-L1716 | train | 39,985 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | Star._populate_rv | def _populate_rv(self, dataset, **kwargs):
"""
Populate columns necessary for an RV dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables`
"""
logger.debug("{}._populate_rv(dataset={})".format(self.component, dataset))
# We need to fill all the flux-related columns so that we can weigh each
# triangle's rv by its flux in the requested passband.
lc_cols = self._populate_lc(dataset, **kwargs)
# rv per element is just the z-component of the velocity vectory. Note
# the change in sign from our right-handed system to rv conventions.
# These will be weighted by the fluxes when integrating
rvs = -1*self.mesh.velocities.for_computations[:,2]
# Gravitational redshift
if self.do_rv_grav:
rv_grav = c.G*(self.mass*u.solMass)/(self.instantaneous_rpole*u.solRad)/c.c
# rvs are in solRad/d internally
rv_grav = rv_grav.to('solRad/d').value
rvs += rv_grav
cols = lc_cols
cols['rvs'] = rvs
return cols | python | def _populate_rv(self, dataset, **kwargs):
"""
Populate columns necessary for an RV dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables`
"""
logger.debug("{}._populate_rv(dataset={})".format(self.component, dataset))
# We need to fill all the flux-related columns so that we can weigh each
# triangle's rv by its flux in the requested passband.
lc_cols = self._populate_lc(dataset, **kwargs)
# rv per element is just the z-component of the velocity vectory. Note
# the change in sign from our right-handed system to rv conventions.
# These will be weighted by the fluxes when integrating
rvs = -1*self.mesh.velocities.for_computations[:,2]
# Gravitational redshift
if self.do_rv_grav:
rv_grav = c.G*(self.mass*u.solMass)/(self.instantaneous_rpole*u.solRad)/c.c
# rvs are in solRad/d internally
rv_grav = rv_grav.to('solRad/d').value
rvs += rv_grav
cols = lc_cols
cols['rvs'] = rvs
return cols | [
"def",
"_populate_rv",
"(",
"self",
",",
"dataset",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}._populate_rv(dataset={})\"",
".",
"format",
"(",
"self",
".",
"component",
",",
"dataset",
")",
")",
"# We need to fill all the flux-related... | Populate columns necessary for an RV dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables` | [
"Populate",
"columns",
"necessary",
"for",
"an",
"RV",
"dataset"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L1718-L1748 | train | 39,986 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | Spot.from_bundle | def from_bundle(cls, b, feature):
"""
Initialize a Spot feature from the bundle.
"""
feature_ps = b.get_feature(feature)
colat = feature_ps.get_value('colat', unit=u.rad)
longitude = feature_ps.get_value('long', unit=u.rad)
if len(b.hierarchy.get_stars())>=2:
star_ps = b.get_component(feature_ps.component)
orbit_ps = b.get_component(b.hierarchy.get_parent_of(feature_ps.component))
syncpar = star_ps.get_value('syncpar')
period = orbit_ps.get_value('period')
dlongdt = (syncpar - 1) / period * 2 * np.pi
else:
star_ps = b.get_component(feature_ps.component)
dlongdt = star_ps.get_value('freq', unit=u.rad/u.d)
longitude = np.pi/2
radius = feature_ps.get_value('radius', unit=u.rad)
relteff = feature_ps.get_value('relteff', unit=u.dimensionless_unscaled)
t0 = b.get_value('t0', context='system', unit=u.d)
return cls(colat, longitude, dlongdt, radius, relteff, t0) | python | def from_bundle(cls, b, feature):
"""
Initialize a Spot feature from the bundle.
"""
feature_ps = b.get_feature(feature)
colat = feature_ps.get_value('colat', unit=u.rad)
longitude = feature_ps.get_value('long', unit=u.rad)
if len(b.hierarchy.get_stars())>=2:
star_ps = b.get_component(feature_ps.component)
orbit_ps = b.get_component(b.hierarchy.get_parent_of(feature_ps.component))
syncpar = star_ps.get_value('syncpar')
period = orbit_ps.get_value('period')
dlongdt = (syncpar - 1) / period * 2 * np.pi
else:
star_ps = b.get_component(feature_ps.component)
dlongdt = star_ps.get_value('freq', unit=u.rad/u.d)
longitude = np.pi/2
radius = feature_ps.get_value('radius', unit=u.rad)
relteff = feature_ps.get_value('relteff', unit=u.dimensionless_unscaled)
t0 = b.get_value('t0', context='system', unit=u.d)
return cls(colat, longitude, dlongdt, radius, relteff, t0) | [
"def",
"from_bundle",
"(",
"cls",
",",
"b",
",",
"feature",
")",
":",
"feature_ps",
"=",
"b",
".",
"get_feature",
"(",
"feature",
")",
"colat",
"=",
"feature_ps",
".",
"get_value",
"(",
"'colat'",
",",
"unit",
"=",
"u",
".",
"rad",
")",
"longitude",
... | Initialize a Spot feature from the bundle. | [
"Initialize",
"a",
"Spot",
"feature",
"from",
"the",
"bundle",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L2840-L2866 | train | 39,987 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | Spot.pointing_vector | def pointing_vector(self, s, time):
"""
s is the spin vector in roche coordinates
time is the current time
"""
t = time - self._t0
longitude = self._longitude + self._dlongdt * t
# define the basis vectors in the spin (primed) coordinates in terms of
# the Roche coordinates.
# ez' = s
# ex' = (ex - s(s.ex)) /|i - s(s.ex)|
# ey' = s x ex'
ex = np.array([1., 0., 0.])
ezp = s
exp = (ex - s*np.dot(s,ex))
eyp = np.cross(s, exp)
return np.sin(self._colat)*np.cos(longitude)*exp +\
np.sin(self._colat)*np.sin(longitude)*eyp +\
np.cos(self._colat)*ezp | python | def pointing_vector(self, s, time):
"""
s is the spin vector in roche coordinates
time is the current time
"""
t = time - self._t0
longitude = self._longitude + self._dlongdt * t
# define the basis vectors in the spin (primed) coordinates in terms of
# the Roche coordinates.
# ez' = s
# ex' = (ex - s(s.ex)) /|i - s(s.ex)|
# ey' = s x ex'
ex = np.array([1., 0., 0.])
ezp = s
exp = (ex - s*np.dot(s,ex))
eyp = np.cross(s, exp)
return np.sin(self._colat)*np.cos(longitude)*exp +\
np.sin(self._colat)*np.sin(longitude)*eyp +\
np.cos(self._colat)*ezp | [
"def",
"pointing_vector",
"(",
"self",
",",
"s",
",",
"time",
")",
":",
"t",
"=",
"time",
"-",
"self",
".",
"_t0",
"longitude",
"=",
"self",
".",
"_longitude",
"+",
"self",
".",
"_dlongdt",
"*",
"t",
"# define the basis vectors in the spin (primed) coordinates... | s is the spin vector in roche coordinates
time is the current time | [
"s",
"is",
"the",
"spin",
"vector",
"in",
"roche",
"coordinates",
"time",
"is",
"the",
"current",
"time"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L2874-L2894 | train | 39,988 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | Spot.process_teffs | def process_teffs(self, teffs, coords, s=np.array([0., 0., 1.]), t=None):
"""
Change the local effective temperatures for any values within the
"cone" defined by the spot. Any teff within the spot will have its
current value multiplied by the "relteff" factor
:parameter array teffs: array of teffs for computations
:parameter array coords: array of coords for computations
:t float: current time
"""
if t is None:
# then assume at t0
t = self._t0
pointing_vector = self.pointing_vector(s,t)
logger.debug("spot.process_teffs at t={} with pointing_vector={} and radius={}".format(t, pointing_vector, self._radius))
cos_alpha_coords = np.dot(coords, pointing_vector) / np.linalg.norm(coords, axis=1)
cos_alpha_spot = np.cos(self._radius)
filter_ = cos_alpha_coords > cos_alpha_spot
teffs[filter_] = teffs[filter_] * self._relteff
return teffs | python | def process_teffs(self, teffs, coords, s=np.array([0., 0., 1.]), t=None):
"""
Change the local effective temperatures for any values within the
"cone" defined by the spot. Any teff within the spot will have its
current value multiplied by the "relteff" factor
:parameter array teffs: array of teffs for computations
:parameter array coords: array of coords for computations
:t float: current time
"""
if t is None:
# then assume at t0
t = self._t0
pointing_vector = self.pointing_vector(s,t)
logger.debug("spot.process_teffs at t={} with pointing_vector={} and radius={}".format(t, pointing_vector, self._radius))
cos_alpha_coords = np.dot(coords, pointing_vector) / np.linalg.norm(coords, axis=1)
cos_alpha_spot = np.cos(self._radius)
filter_ = cos_alpha_coords > cos_alpha_spot
teffs[filter_] = teffs[filter_] * self._relteff
return teffs | [
"def",
"process_teffs",
"(",
"self",
",",
"teffs",
",",
"coords",
",",
"s",
"=",
"np",
".",
"array",
"(",
"[",
"0.",
",",
"0.",
",",
"1.",
"]",
")",
",",
"t",
"=",
"None",
")",
":",
"if",
"t",
"is",
"None",
":",
"# then assume at t0",
"t",
"=",... | Change the local effective temperatures for any values within the
"cone" defined by the spot. Any teff within the spot will have its
current value multiplied by the "relteff" factor
:parameter array teffs: array of teffs for computations
:parameter array coords: array of coords for computations
:t float: current time | [
"Change",
"the",
"local",
"effective",
"temperatures",
"for",
"any",
"values",
"within",
"the",
"cone",
"defined",
"by",
"the",
"spot",
".",
"Any",
"teff",
"within",
"the",
"spot",
"will",
"have",
"its",
"current",
"value",
"multiplied",
"by",
"the",
"reltef... | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L2896-L2919 | train | 39,989 |
phoebe-project/phoebe2 | phoebe/backend/universe.py | Pulsation.from_bundle | def from_bundle(cls, b, feature):
"""
Initialize a Pulsation feature from the bundle.
"""
feature_ps = b.get_feature(feature)
freq = feature_ps.get_value('freq', unit=u.d**-1)
radamp = feature_ps.get_value('radamp', unit=u.dimensionless_unscaled)
l = feature_ps.get_value('l', unit=u.dimensionless_unscaled)
m = feature_ps.get_value('m', unit=u.dimensionless_unscaled)
teffext = feature_ps.get_value('teffext')
GM = c.G.to('solRad3 / (solMass d2)').value*b.get_value(qualifier='mass', component=feature_ps.component, context='component', unit=u.solMass)
R = b.get_value(qualifier='rpole', component=feature_ps.component, section='component', unit=u.solRad)
tanamp = GM/R**3/freq**2
return cls(radamp, freq, l, m, tanamp, teffext) | python | def from_bundle(cls, b, feature):
"""
Initialize a Pulsation feature from the bundle.
"""
feature_ps = b.get_feature(feature)
freq = feature_ps.get_value('freq', unit=u.d**-1)
radamp = feature_ps.get_value('radamp', unit=u.dimensionless_unscaled)
l = feature_ps.get_value('l', unit=u.dimensionless_unscaled)
m = feature_ps.get_value('m', unit=u.dimensionless_unscaled)
teffext = feature_ps.get_value('teffext')
GM = c.G.to('solRad3 / (solMass d2)').value*b.get_value(qualifier='mass', component=feature_ps.component, context='component', unit=u.solMass)
R = b.get_value(qualifier='rpole', component=feature_ps.component, section='component', unit=u.solRad)
tanamp = GM/R**3/freq**2
return cls(radamp, freq, l, m, tanamp, teffext) | [
"def",
"from_bundle",
"(",
"cls",
",",
"b",
",",
"feature",
")",
":",
"feature_ps",
"=",
"b",
".",
"get_feature",
"(",
"feature",
")",
"freq",
"=",
"feature_ps",
".",
"get_value",
"(",
"'freq'",
",",
"unit",
"=",
"u",
".",
"d",
"**",
"-",
"1",
")",... | Initialize a Pulsation feature from the bundle. | [
"Initialize",
"a",
"Pulsation",
"feature",
"from",
"the",
"bundle",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L2932-L2949 | train | 39,990 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.from_server | def from_server(cls, bundleid, server='http://localhost:5555',
as_client=True):
"""Load a new bundle from a server.
[NOT IMPLEMENTED]
Load a bundle from a phoebe server. This is a constructor so should be
called as:
>>> b = Bundle.from_server('asdf', as_client=False)
:parameter str bundleid: the identifier given to the bundle by the
server
:parameter str server: the host (and port) of the server
:parameter bool as_client: whether to attach in client mode
(default: True)
"""
if not conf.devel:
raise NotImplementedError("'from_server' not officially supported for this release. Enable developer mode to test.")
# TODO: run test message on server, if localhost and fails, attempt to
# launch?
url = "{}/{}/json".format(server, bundleid)
logger.info("downloading bundle from {}".format(url))
r = requests.get(url, timeout=5)
rjson = r.json()
b = cls(rjson['data'])
if as_client:
b.as_client(as_client, server=server,
bundleid=rjson['meta']['bundleid'])
logger.warning("This bundle is in client mode, meaning all\
computations will be handled by the server at {}. To disable\
client mode, call as_client(False) or in the future pass\
as_client=False to from_server".format(server))
return b | python | def from_server(cls, bundleid, server='http://localhost:5555',
as_client=True):
"""Load a new bundle from a server.
[NOT IMPLEMENTED]
Load a bundle from a phoebe server. This is a constructor so should be
called as:
>>> b = Bundle.from_server('asdf', as_client=False)
:parameter str bundleid: the identifier given to the bundle by the
server
:parameter str server: the host (and port) of the server
:parameter bool as_client: whether to attach in client mode
(default: True)
"""
if not conf.devel:
raise NotImplementedError("'from_server' not officially supported for this release. Enable developer mode to test.")
# TODO: run test message on server, if localhost and fails, attempt to
# launch?
url = "{}/{}/json".format(server, bundleid)
logger.info("downloading bundle from {}".format(url))
r = requests.get(url, timeout=5)
rjson = r.json()
b = cls(rjson['data'])
if as_client:
b.as_client(as_client, server=server,
bundleid=rjson['meta']['bundleid'])
logger.warning("This bundle is in client mode, meaning all\
computations will be handled by the server at {}. To disable\
client mode, call as_client(False) or in the future pass\
as_client=False to from_server".format(server))
return b | [
"def",
"from_server",
"(",
"cls",
",",
"bundleid",
",",
"server",
"=",
"'http://localhost:5555'",
",",
"as_client",
"=",
"True",
")",
":",
"if",
"not",
"conf",
".",
"devel",
":",
"raise",
"NotImplementedError",
"(",
"\"'from_server' not officially supported for this... | Load a new bundle from a server.
[NOT IMPLEMENTED]
Load a bundle from a phoebe server. This is a constructor so should be
called as:
>>> b = Bundle.from_server('asdf', as_client=False)
:parameter str bundleid: the identifier given to the bundle by the
server
:parameter str server: the host (and port) of the server
:parameter bool as_client: whether to attach in client mode
(default: True) | [
"Load",
"a",
"new",
"bundle",
"from",
"a",
"server",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L320-L358 | train | 39,991 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.from_legacy | def from_legacy(cls, filename, add_compute_legacy=True, add_compute_phoebe=True):
"""Load a bundle from a PHOEBE 1.0 Legacy file.
This is a constructor so should be called as:
>>> b = Bundle.from_legacy('myfile.phoebe')
:parameter str filename: relative or full path to the file
:return: instantiated :class:`Bundle` object
"""
logger.warning("importing from legacy is experimental until official 1.0 release")
filename = os.path.expanduser(filename)
return io.load_legacy(filename, add_compute_legacy, add_compute_phoebe) | python | def from_legacy(cls, filename, add_compute_legacy=True, add_compute_phoebe=True):
"""Load a bundle from a PHOEBE 1.0 Legacy file.
This is a constructor so should be called as:
>>> b = Bundle.from_legacy('myfile.phoebe')
:parameter str filename: relative or full path to the file
:return: instantiated :class:`Bundle` object
"""
logger.warning("importing from legacy is experimental until official 1.0 release")
filename = os.path.expanduser(filename)
return io.load_legacy(filename, add_compute_legacy, add_compute_phoebe) | [
"def",
"from_legacy",
"(",
"cls",
",",
"filename",
",",
"add_compute_legacy",
"=",
"True",
",",
"add_compute_phoebe",
"=",
"True",
")",
":",
"logger",
".",
"warning",
"(",
"\"importing from legacy is experimental until official 1.0 release\"",
")",
"filename",
"=",
"o... | Load a bundle from a PHOEBE 1.0 Legacy file.
This is a constructor so should be called as:
>>> b = Bundle.from_legacy('myfile.phoebe')
:parameter str filename: relative or full path to the file
:return: instantiated :class:`Bundle` object | [
"Load",
"a",
"bundle",
"from",
"a",
"PHOEBE",
"1",
".",
"0",
"Legacy",
"file",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L382-L394 | train | 39,992 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.default_triple | def default_triple(cls, inner_as_primary=True, inner_as_overcontact=False,
starA='starA', starB='starB', starC='starC',
inner='inner', outer='outer',
contact_envelope='contact_envelope'):
"""Load a bundle with a default triple system.
Set inner_as_primary based on what hierarchical configuration you want.
inner_as_primary = True:
starA - starB -- starC
inner_as_primary = False:
starC -- starA - starB
This is a constructor, so should be called as:
>>> b = Bundle.default_triple_primary()
:parameter bool inner_as_primary: whether the inner-binary should be
the primary component of the outer-orbit
:return: instantiated :class:`Bundle` object
"""
if not conf.devel:
raise NotImplementedError("'default_triple' not officially supported for this release. Enable developer mode to test.")
b = cls()
b.add_star(component=starA)
b.add_star(component=starB)
b.add_star(component=starC)
b.add_orbit(component=inner, period=1)
b.add_orbit(component=outer, period=10)
if inner_as_overcontact:
b.add_envelope(component=contact_envelope)
inner_hier = _hierarchy.binaryorbit(b[inner],
b[starA],
b[starB],
b[contact_envelope])
else:
inner_hier = _hierarchy.binaryorbit(b[inner], b[starA], b[starB])
if inner_as_primary:
hierstring = _hierarchy.binaryorbit(b[outer], inner_hier, b[starC])
else:
hierstring = _hierarchy.binaryorbit(b[outer], b[starC], inner_hier)
b.set_hierarchy(hierstring)
b.add_constraint(constraint.keplers_third_law_hierarchical,
outer, inner)
# TODO: does this constraint need to be rebuilt when things change?
# (ie in set_hierarchy)
b.add_compute()
return b | python | def default_triple(cls, inner_as_primary=True, inner_as_overcontact=False,
starA='starA', starB='starB', starC='starC',
inner='inner', outer='outer',
contact_envelope='contact_envelope'):
"""Load a bundle with a default triple system.
Set inner_as_primary based on what hierarchical configuration you want.
inner_as_primary = True:
starA - starB -- starC
inner_as_primary = False:
starC -- starA - starB
This is a constructor, so should be called as:
>>> b = Bundle.default_triple_primary()
:parameter bool inner_as_primary: whether the inner-binary should be
the primary component of the outer-orbit
:return: instantiated :class:`Bundle` object
"""
if not conf.devel:
raise NotImplementedError("'default_triple' not officially supported for this release. Enable developer mode to test.")
b = cls()
b.add_star(component=starA)
b.add_star(component=starB)
b.add_star(component=starC)
b.add_orbit(component=inner, period=1)
b.add_orbit(component=outer, period=10)
if inner_as_overcontact:
b.add_envelope(component=contact_envelope)
inner_hier = _hierarchy.binaryorbit(b[inner],
b[starA],
b[starB],
b[contact_envelope])
else:
inner_hier = _hierarchy.binaryorbit(b[inner], b[starA], b[starB])
if inner_as_primary:
hierstring = _hierarchy.binaryorbit(b[outer], inner_hier, b[starC])
else:
hierstring = _hierarchy.binaryorbit(b[outer], b[starC], inner_hier)
b.set_hierarchy(hierstring)
b.add_constraint(constraint.keplers_third_law_hierarchical,
outer, inner)
# TODO: does this constraint need to be rebuilt when things change?
# (ie in set_hierarchy)
b.add_compute()
return b | [
"def",
"default_triple",
"(",
"cls",
",",
"inner_as_primary",
"=",
"True",
",",
"inner_as_overcontact",
"=",
"False",
",",
"starA",
"=",
"'starA'",
",",
"starB",
"=",
"'starB'",
",",
"starC",
"=",
"'starC'",
",",
"inner",
"=",
"'inner'",
",",
"outer",
"=",... | Load a bundle with a default triple system.
Set inner_as_primary based on what hierarchical configuration you want.
inner_as_primary = True:
starA - starB -- starC
inner_as_primary = False:
starC -- starA - starB
This is a constructor, so should be called as:
>>> b = Bundle.default_triple_primary()
:parameter bool inner_as_primary: whether the inner-binary should be
the primary component of the outer-orbit
:return: instantiated :class:`Bundle` object | [
"Load",
"a",
"bundle",
"with",
"a",
"default",
"triple",
"system",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L521-L578 | train | 39,993 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.save | def save(self, filename, clear_history=True, incl_uniqueid=False,
compact=False):
"""Save the bundle to a JSON-formatted ASCII file.
:parameter str filename: relative or full path to the file
:parameter bool clear_history: whether to clear history log
items before saving (default: True)
:parameter bool incl_uniqueid: whether to including uniqueids in the
file (only needed if its necessary to maintain the uniqueids when
reloading)
:parameter bool compact: whether to use compact file-formatting (maybe
be quicker to save/load, but not as easily readable)
:return: the filename
"""
if clear_history:
# TODO: let's not actually clear history,
# but rather skip the context when saving
self.remove_history()
# TODO: add option for clear_models, clear_feedback
# NOTE: PS.save will handle os.path.expanduser
return super(Bundle, self).save(filename, incl_uniqueid=incl_uniqueid,
compact=compact) | python | def save(self, filename, clear_history=True, incl_uniqueid=False,
compact=False):
"""Save the bundle to a JSON-formatted ASCII file.
:parameter str filename: relative or full path to the file
:parameter bool clear_history: whether to clear history log
items before saving (default: True)
:parameter bool incl_uniqueid: whether to including uniqueids in the
file (only needed if its necessary to maintain the uniqueids when
reloading)
:parameter bool compact: whether to use compact file-formatting (maybe
be quicker to save/load, but not as easily readable)
:return: the filename
"""
if clear_history:
# TODO: let's not actually clear history,
# but rather skip the context when saving
self.remove_history()
# TODO: add option for clear_models, clear_feedback
# NOTE: PS.save will handle os.path.expanduser
return super(Bundle, self).save(filename, incl_uniqueid=incl_uniqueid,
compact=compact) | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"clear_history",
"=",
"True",
",",
"incl_uniqueid",
"=",
"False",
",",
"compact",
"=",
"False",
")",
":",
"if",
"clear_history",
":",
"# TODO: let's not actually clear history,",
"# but rather skip the context when sav... | Save the bundle to a JSON-formatted ASCII file.
:parameter str filename: relative or full path to the file
:parameter bool clear_history: whether to clear history log
items before saving (default: True)
:parameter bool incl_uniqueid: whether to including uniqueids in the
file (only needed if its necessary to maintain the uniqueids when
reloading)
:parameter bool compact: whether to use compact file-formatting (maybe
be quicker to save/load, but not as easily readable)
:return: the filename | [
"Save",
"the",
"bundle",
"to",
"a",
"JSON",
"-",
"formatted",
"ASCII",
"file",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L580-L602 | train | 39,994 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle._default_label | def _default_label(self, base, context, **kwargs):
"""
Determine a default label given a base label and the passed kwargs
this simply counts the current number of matches on metawargs and
appends that number to the base
:parameter str base: the base string for the label
:parameter str context: name of the context (where the label is going)
:parameter **kwargs: the kwargs to run a filter on. The returned label
will be "{}{:02d}".format(base, number_of_results_with_kwargs+1)
:return: label
"""
kwargs['context'] = context
params = len(getattr(self.filter(check_visible=False,**kwargs), '{}s'.format(context)))
return "{}{:02d}".format(base, params+1) | python | def _default_label(self, base, context, **kwargs):
"""
Determine a default label given a base label and the passed kwargs
this simply counts the current number of matches on metawargs and
appends that number to the base
:parameter str base: the base string for the label
:parameter str context: name of the context (where the label is going)
:parameter **kwargs: the kwargs to run a filter on. The returned label
will be "{}{:02d}".format(base, number_of_results_with_kwargs+1)
:return: label
"""
kwargs['context'] = context
params = len(getattr(self.filter(check_visible=False,**kwargs), '{}s'.format(context)))
return "{}{:02d}".format(base, params+1) | [
"def",
"_default_label",
"(",
"self",
",",
"base",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'context'",
"]",
"=",
"context",
"params",
"=",
"len",
"(",
"getattr",
"(",
"self",
".",
"filter",
"(",
"check_visible",
"=",
"False",... | Determine a default label given a base label and the passed kwargs
this simply counts the current number of matches on metawargs and
appends that number to the base
:parameter str base: the base string for the label
:parameter str context: name of the context (where the label is going)
:parameter **kwargs: the kwargs to run a filter on. The returned label
will be "{}{:02d}".format(base, number_of_results_with_kwargs+1)
:return: label | [
"Determine",
"a",
"default",
"label",
"given",
"a",
"base",
"label",
"and",
"the",
"passed",
"kwargs"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L764-L781 | train | 39,995 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.get_setting | def get_setting(self, twig=None, **kwargs):
"""
Filter in the 'setting' context
:parameter str twig: the twig used for filtering
:parameter **kwargs: any other tags to do the filter (except tag or
context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if twig is not None:
kwargs['twig'] = twig
kwargs['context'] = 'setting'
return self.filter_or_get(**kwargs) | python | def get_setting(self, twig=None, **kwargs):
"""
Filter in the 'setting' context
:parameter str twig: the twig used for filtering
:parameter **kwargs: any other tags to do the filter (except tag or
context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
"""
if twig is not None:
kwargs['twig'] = twig
kwargs['context'] = 'setting'
return self.filter_or_get(**kwargs) | [
"def",
"get_setting",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"twig",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'twig'",
"]",
"=",
"twig",
"kwargs",
"[",
"'context'",
"]",
"=",
"'setting'",
"return",
"self",
... | Filter in the 'setting' context
:parameter str twig: the twig used for filtering
:parameter **kwargs: any other tags to do the filter (except tag or
context)
:return: :class:`phoebe.parameters.parameters.ParameterSet` | [
"Filter",
"in",
"the",
"setting",
"context"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L797-L809 | train | 39,996 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.get_history | def get_history(self, i=None):
"""
Get a history item by index.
You can toggle whether history is recorded using
* :meth:`enable_history`
* :meth:`disable_history`
:parameter int i: integer for indexing (can be positive or
negative). If i is None or not provided, the entire list
of history items will be returned
:return: :class:`phoebe.parameters.parameters.Parameter` if i is
an int, or :class:`phoebe.parameters.parameters.ParameterSet` if i
is not provided
:raises ValueError: if no history items have been recorded.
"""
ps = self.filter(context='history')
# if not len(ps):
# raise ValueError("no history recorded")
if i is not None:
return ps.to_list()[i]
else:
return ps | python | def get_history(self, i=None):
"""
Get a history item by index.
You can toggle whether history is recorded using
* :meth:`enable_history`
* :meth:`disable_history`
:parameter int i: integer for indexing (can be positive or
negative). If i is None or not provided, the entire list
of history items will be returned
:return: :class:`phoebe.parameters.parameters.Parameter` if i is
an int, or :class:`phoebe.parameters.parameters.ParameterSet` if i
is not provided
:raises ValueError: if no history items have been recorded.
"""
ps = self.filter(context='history')
# if not len(ps):
# raise ValueError("no history recorded")
if i is not None:
return ps.to_list()[i]
else:
return ps | [
"def",
"get_history",
"(",
"self",
",",
"i",
"=",
"None",
")",
":",
"ps",
"=",
"self",
".",
"filter",
"(",
"context",
"=",
"'history'",
")",
"# if not len(ps):",
"# raise ValueError(\"no history recorded\")",
"if",
"i",
"is",
"not",
"None",
":",
"return",
... | Get a history item by index.
You can toggle whether history is recorded using
* :meth:`enable_history`
* :meth:`disable_history`
:parameter int i: integer for indexing (can be positive or
negative). If i is None or not provided, the entire list
of history items will be returned
:return: :class:`phoebe.parameters.parameters.Parameter` if i is
an int, or :class:`phoebe.parameters.parameters.ParameterSet` if i
is not provided
:raises ValueError: if no history items have been recorded. | [
"Get",
"a",
"history",
"item",
"by",
"index",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L853-L876 | train | 39,997 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.remove_history | def remove_history(self, i=None):
"""
Remove a history item from the bundle by index.
You can toggle whether history is recorded using
* :meth:`enable_history`
* :meth:`disable_history`
:parameter int i: integer for indexing (can be positive or
negative). If i is None or not provided, the entire list
of history items will be removed
:raises ValueError: if no history items have been recorded.
"""
if i is None:
self.remove_parameters_all(context='history')
else:
param = self.get_history(i=i)
self.remove_parameter(uniqueid=param.uniqueid) | python | def remove_history(self, i=None):
"""
Remove a history item from the bundle by index.
You can toggle whether history is recorded using
* :meth:`enable_history`
* :meth:`disable_history`
:parameter int i: integer for indexing (can be positive or
negative). If i is None or not provided, the entire list
of history items will be removed
:raises ValueError: if no history items have been recorded.
"""
if i is None:
self.remove_parameters_all(context='history')
else:
param = self.get_history(i=i)
self.remove_parameter(uniqueid=param.uniqueid) | [
"def",
"remove_history",
"(",
"self",
",",
"i",
"=",
"None",
")",
":",
"if",
"i",
"is",
"None",
":",
"self",
".",
"remove_parameters_all",
"(",
"context",
"=",
"'history'",
")",
"else",
":",
"param",
"=",
"self",
".",
"get_history",
"(",
"i",
"=",
"i... | Remove a history item from the bundle by index.
You can toggle whether history is recorded using
* :meth:`enable_history`
* :meth:`disable_history`
:parameter int i: integer for indexing (can be positive or
negative). If i is None or not provided, the entire list
of history items will be removed
:raises ValueError: if no history items have been recorded. | [
"Remove",
"a",
"history",
"item",
"from",
"the",
"bundle",
"by",
"index",
"."
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L878-L896 | train | 39,998 |
phoebe-project/phoebe2 | phoebe/frontend/bundle.py | Bundle.undo | def undo(self, i=-1):
"""
Undo an item in the history logs
:parameter int i: integer for indexing (can be positive or
negative). Defaults to -1 if not provided (the latest
recorded history item)
:raises ValueError: if no history items have been recorded
"""
_history_enabled = self.history_enabled
param = self.get_history(i)
self.disable_history()
param.undo()
# TODO: do we really want to remove this? then what's the point of redo?
self.remove_parameter(uniqueid=param.uniqueid)
if _history_enabled:
self.enable_history() | python | def undo(self, i=-1):
"""
Undo an item in the history logs
:parameter int i: integer for indexing (can be positive or
negative). Defaults to -1 if not provided (the latest
recorded history item)
:raises ValueError: if no history items have been recorded
"""
_history_enabled = self.history_enabled
param = self.get_history(i)
self.disable_history()
param.undo()
# TODO: do we really want to remove this? then what's the point of redo?
self.remove_parameter(uniqueid=param.uniqueid)
if _history_enabled:
self.enable_history() | [
"def",
"undo",
"(",
"self",
",",
"i",
"=",
"-",
"1",
")",
":",
"_history_enabled",
"=",
"self",
".",
"history_enabled",
"param",
"=",
"self",
".",
"get_history",
"(",
"i",
")",
"self",
".",
"disable_history",
"(",
")",
"param",
".",
"undo",
"(",
")",... | Undo an item in the history logs
:parameter int i: integer for indexing (can be positive or
negative). Defaults to -1 if not provided (the latest
recorded history item)
:raises ValueError: if no history items have been recorded | [
"Undo",
"an",
"item",
"in",
"the",
"history",
"logs"
] | e64b8be683977064e2d55dd1b3ac400f64c3e379 | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/frontend/bundle.py#L936-L953 | train | 39,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.