sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def markdown_safe(value, arg=None):
""" Render markdown over a given value, optionally using varios extensions.
Default extensions could be defined which MARKDOWN_EXTENSIONS option.
Enables safe mode, which strips raw HTML and only returns HTML generated
by markdown.
:returns: A rendered markdown... | Render markdown over a given value, optionally using varios extensions.
Default extensions could be defined which MARKDOWN_EXTENSIONS option.
Enables safe mode, which strips raw HTML and only returns HTML generated
by markdown.
:returns: A rendered markdown. | entailment |
def markdown_editor(selector):
""" Enable markdown editor for given textarea.
:returns: Editor template context.
"""
return dict(
selector=selector,
extra_settings=mark_safe(simplejson.dumps(
dict(previewParserPath=reverse('django_markdown_preview'))))) | Enable markdown editor for given textarea.
:returns: Editor template context. | entailment |
def markdown_media_css():
""" Add css requirements to HTML.
:returns: Editor template context.
"""
return dict(
CSS_SET=posixpath.join(
settings.MARKDOWN_SET_PATH, settings.MARKDOWN_SET_NAME, 'style.css'
),
CSS_SKIN=posixpath.join(
'django_markdown', 'sk... | Add css requirements to HTML.
:returns: Editor template context. | entailment |
def convert(source, to, format=None, extra_args=(), encoding='utf-8'):
"""Convert given `source` from `format` `to` another.
`source` may be either a file path or a string to be converted.
It's possible to pass `extra_args` if needed. In case `format` is not
provided, it will try to invert the format ... | Convert given `source` from `format` `to` another.
`source` may be either a file path or a string to be converted.
It's possible to pass `extra_args` if needed. In case `format` is not
provided, it will try to invert the format based on given `source`.
Raises OSError if pandoc is not found! Make sure... | entailment |
def get_pandoc_formats():
""" Dynamic preprocessor for Pandoc formats.
Return 2 lists. "from_formats" and "to_formats".
"""
try:
p = subprocess.Popen(
['pandoc', '-h'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
except OSError:
raise OSError("... | Dynamic preprocessor for Pandoc formats.
Return 2 lists. "from_formats" and "to_formats". | entailment |
def render(self, name, value, attrs=None, renderer=None):
""" Render widget.
:returns: A rendered HTML
"""
html = super(MarkdownWidget, self).render(name, value, attrs, renderer)
attrs = self.build_attrs(attrs)
html += editor_js_initialization("#%s" % attrs['id'])
... | Render widget.
:returns: A rendered HTML | entailment |
def extendMarkdown(self, md, md_globals):
""" Add InlineGraphvizPreprocessor to the Markdown instance. """
md.registerExtension(self)
md.preprocessors.add('graphviz_block',
InlineGraphvizPreprocessor(md),
"_begin") | Add InlineGraphvizPreprocessor to the Markdown instance. | entailment |
def run(self, lines):
""" Match and generate dot code blocks."""
text = "\n".join(lines)
while 1:
m = BLOCK_RE.search(text)
if m:
command = m.group('command')
# Whitelist command, prevent command injection.
if command not i... | Match and generate dot code blocks. | entailment |
def post(self, command, data=None):
"""Post data to API."""
now = calendar.timegm(datetime.datetime.now().timetuple())
if now > self.expiration:
auth = self.__open("/oauth/token", data=self.oauth)
self.__sethead(auth['access_token'])
return self.__open("%s%s" % (s... | Post data to API. | entailment |
def __sethead(self, access_token):
"""Set HTTP header."""
self.access_token = access_token
now = calendar.timegm(datetime.datetime.now().timetuple())
self.expiration = now + 1800
self.head = {"Authorization": "Bearer %s" % access_token,
"User-Agent": self.use... | Set HTTP header. | entailment |
def __open(self, url, headers=None, data=None, baseurl=""):
"""Use raw urlopen command."""
headers = headers or {}
if not baseurl:
baseurl = self.baseurl
req = Request("%s%s" % (baseurl, url), headers=headers)
_LOGGER.debug(url)
try:
req.data = ur... | Use raw urlopen command. | entailment |
def update(self):
"""Update the parking brake sensor."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_drive_params(self._id)
if data:
if not data['shift_state'] or data['shift_state'] == 'P':
self.__state = True
... | Update the parking brake sensor. | entailment |
def update(self):
"""Update the HVAC state."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_climate_params(self._id)
if data:
if time.time() - self.__manual_update_time > 60:
self.__is_auto_conditioning_on = (data
... | Update the HVAC state. | entailment |
def set_temperature(self, temp):
"""Set both the driver and passenger temperature to temp."""
temp = round(temp, 1)
self.__manual_update_time = time.time()
data = self._controller.command(self._id, 'set_temps',
{"driver_temp": temp,
... | Set both the driver and passenger temperature to temp. | entailment |
def set_status(self, enabled):
"""Enable or disable the HVAC."""
self.__manual_update_time = time.time()
if enabled:
data = self._controller.command(self._id,
'auto_conditioning_start',
wake_if_as... | Enable or disable the HVAC. | entailment |
def update(self):
"""Update the temperature."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_climate_params(self._id)
if data:
self.__inside_temp = (data['inside_temp'] if data['inside_temp']
else self._... | Update the temperature. | entailment |
def update(self):
"""Update the charging state of the Tesla Vehicle."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data and (time.time() - self.__manual_update_time > 60):
if data['charging_state'] != "Char... | Update the charging state of the Tesla Vehicle. | entailment |
def start_charge(self):
"""Start charging the Tesla Vehicle."""
if not self.__charger_state:
data = self._controller.command(self._id, 'charge_start',
wake_if_asleep=True)
if data and data['response']['result']:
self.__c... | Start charging the Tesla Vehicle. | entailment |
def stop_charge(self):
"""Stop charging the Tesla Vehicle."""
if self.__charger_state:
data = self._controller.command(self._id, 'charge_stop',
wake_if_asleep=True)
if data and data['response']['result']:
self.__charger_... | Stop charging the Tesla Vehicle. | entailment |
def update(self):
"""Update the status of the range setting."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data and (time.time() - self.__manual_update_time > 60):
self.__maxrange_state = data['charge_to_ma... | Update the status of the range setting. | entailment |
def set_max(self):
"""Set the charger to max range for trips."""
if not self.__maxrange_state:
data = self._controller.command(self._id, 'charge_max_range',
wake_if_asleep=True)
if data['response']['result']:
self.__maxr... | Set the charger to max range for trips. | entailment |
def set_standard(self):
"""Set the charger to standard range for daily commute."""
if self.__maxrange_state:
data = self._controller.command(self._id, 'charge_standard',
wake_if_asleep=True)
if data and data['response']['result']:
... | Set the charger to standard range for daily commute. | entailment |
def unlock(self):
"""Unlock the doors and extend handles where applicable."""
if self.__lock_state:
data = self._controller.command(self._id, 'door_unlock',
wake_if_asleep=True)
if data['response']['result']:
self.__lock... | Unlock the doors and extend handles where applicable. | entailment |
def lock(self):
"""Close the charger door."""
if not self.__lock_state:
data = self._controller.command(self._id, 'charge_port_door_close',
wake_if_asleep=True)
if data['response']['result']:
self.__lock_state = True
... | Close the charger door. | entailment |
def wake_up(func):
# pylint: disable=no-self-argument
# issue is use of wraps on classmethods which should be replaced:
# https://hynek.me/articles/decorators/
"""Wrap a API f so it will attempt to wake the vehicle if asleep.
The command f is run once if the vehicle_id was la... | Wrap a API f so it will attempt to wake the vehicle if asleep.
The command f is run once if the vehicle_id was last reported
online. Assuming f returns None and wake_if_asleep is True, 5 attempts
will be made to wake the vehicle to reissue the command. In addition,
if there is a `could_... | entailment |
def post(self, vehicle_id, command, data=None, wake_if_asleep=True):
# pylint: disable=unused-argument
"""Send post command to the vehicle_id.
This is a wrapped function by wake_up.
Parameters
----------
vehicle_id : string
Identifier for the car on the own... | Send post command to the vehicle_id.
This is a wrapped function by wake_up.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car across
differen... | entailment |
def get(self, vehicle_id, command, wake_if_asleep=False):
# pylint: disable=unused-argument
"""Send get command to the vehicle_id.
This is a wrapped function by wake_up.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpo... | Send get command to the vehicle_id.
This is a wrapped function by wake_up.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car across
different... | entailment |
def data_request(self, vehicle_id, name, wake_if_asleep=False):
"""Get requested data from vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car a... | Get requested data from vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car across
different endpoints.
https://tesla-api.timdor... | entailment |
def command(self, vehicle_id, name, data=None, wake_if_asleep=True):
"""Post name command to the vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the... | Post name command to the vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car across
different endpoints.
https://tesla-api.timdo... | entailment |
def update(self, car_id=None, wake_if_asleep=False, force=False):
"""Update all vehicle attributes in the cache.
This command will connect to the Tesla API and first update the list of
online vehicles assuming no attempt for at least the [update_interval].
It will then update all the ca... | Update all vehicle attributes in the cache.
This command will connect to the Tesla API and first update the list of
online vehicles assuming no attempt for at least the [update_interval].
It will then update all the cached values for cars that are awake
assuming no update has occurred f... | entailment |
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'] | Update the battery state. | entailment |
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... | Update the battery range state. | entailment |
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.i... | Return whether the data is from an online vehicle. | entailment |
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.__... | Update the current GPS location. | entailment |
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... | Update the odometer and the unit of measurement based on GUI. | entailment |
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.p... | 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... | entailment |
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.paramete... | 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... | entailment |
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.... | 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 al... | entailment |
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:`pho... | 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.Param... | entailment |
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.parame... | 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... | entailment |
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.parame... | 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
... | entailment |
def phoebe(**kwargs):
"""
Compute options for using the PHOEBE 2.0 backend.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.phoebe` for a list of sources to
cite when using this backend... | Compute options for using the PHOEBE 2.0 backend.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.phoebe` for a list of sources to
cite when using this backend.
:parameter **kwargs: defaul... | entailment |
def legacy(**kwargs):
"""
Compute options for using the PHOEBE 1.0 legacy backend (must be
installed).
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.legacy` for a list of sources to
... | Compute options for using the PHOEBE 1.0 legacy backend (must be
installed).
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.legacy` for a list of sources to
cite when using this backend.
... | entailment |
def photodynam(**kwargs):
"""
Compute options for using Josh Carter's 'photodynam' code as a
backend (must be installed).
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.photodynam` for... | Compute options for using Josh Carter's 'photodynam' code as a
backend (must be installed).
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.photodynam` for a list of sources to
cite when us... | entailment |
def jktebop(**kwargs):
"""
Compute options for using John Southworth's 'jktebop' code as a
backend (must be installed).
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.jktebop` for a li... | Compute options for using John Southworth's 'jktebop' code as a
backend (must be installed).
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.jktebop` for a list of sources to
cite when usin... | entailment |
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 _... | 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 | entailment |
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(... | 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. | entailment |
def complete(self, text, state):
"""Return the next possible completion for 'text'.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'.
"""
if self.use_main_ns:
self.namespace = __main__.__dict__
... | Return the next possible completion for 'text'.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'. | entailment |
def attr_matches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluable in self.namespace, it will be evaluated and its attributes
(as revealed by dir()) are used as possible completions. (For class
insta... | Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluable in self.namespace, it will be evaluated and its attributes
(as revealed by dir()) are used as possible completions. (For class
instances, class members are also considered.)... | entailment |
def _extract_from_bundle(b, compute, times=None, allow_oversample=False,
by_time=True, **kwargs):
"""
Extract a list of sorted times and the datasets that need to be
computed at each of those times. Any backend can then loop through
these times and see what quantities are neede... | Extract a list of sorted times and the datasets that need to be
computed at each of those times. Any backend can then loop through
these times and see what quantities are needed for that time step.
Empty copies of synthetics for each applicable dataset are then
created and returned so that they can be... | entailment |
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.Parameter... | 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 | entailment |
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']),
'qualifi... | where kwargs overrides info | entailment |
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... | 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.
... | entailment |
def get_packet_and_syns(self, b, compute, times=[], **kwargs):
"""
get_packet is called by the master and must get all information necessary
to send to all workers. The returned packet will be passed on as
_run_chunk(**packet) with the following exceptions:
* b: the bundle will... | get_packet is called by the master and must get all information necessary
to send to all workers. The returned packet will be passed on as
_run_chunk(**packet) with the following exceptions:
* b: the bundle will be included in the packet serialized
* compute: the label of the compute o... | entailment |
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... | rpacket_per_worker is a list of packetlists as returned by _run_chunk | entailment |
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 = s... | if within mpirun, workers should call _run_worker instead of run | entailment |
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)
... | 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) | entailment |
def euler_trans_matrix(etheta, elongan, eincl):
"""
Get the transformation matrix R to translate/rotate a mesh according to
euler angles.
The matrix is
R(long,incl,theta) =
Rz(pi).Rz(long).Rx(incl).Rz(theta)
Rz(long).Rx(-incl).Rz(theta).Rz(pi)
where
Rx(u) = 1, 0, ... | Get the transformation matrix R to translate/rotate a mesh according to
euler angles.
The matrix is
R(long,incl,theta) =
Rz(pi).Rz(long).Rx(incl).Rz(theta)
Rz(long).Rx(-incl).Rz(theta).Rz(pi)
where
Rx(u) = 1, 0, 0
0, cos(u), -sin(u)
0, ... | entailment |
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
"""
... | 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 | entailment |
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(-i... | 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. | entailment |
def general_rotation_matrix(theta, phi, alpha):
"""
Rotation around vector
u = (sin(theta) cos(phi), sin(theta) sin(phi), cos(theta))
by an angle
alpha
Ref:
http://ksuweb.kennesaw.edu/~plaval//math4490/rotgen.pdf
:parameter float theta:
:parameter float phi:
:parameter float alpha: rotation a... | Rotation around vector
u = (sin(theta) cos(phi), sin(theta) sin(phi), cos(theta))
by an angle
alpha
Ref:
http://ksuweb.kennesaw.edu/~plaval//math4490/rotgen.pdf
:parameter float theta:
:parameter float phi:
:parameter float alpha: rotation angle
:return: 3x3 matrix of floats | entailment |
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
:paramet... | 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 ... | entailment |
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 ... | 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 elem... | entailment |
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 f... | 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 floa... | entailment |
def averages(self):
"""
Access to the average of the values at the vertices for each triangle.
If the quantities are defined at centers instead of vertices, this
will return None. Also see :method:`centers`.
:return: numpy array or None
"""
if not self.mesh._com... | Access to the average of the values at the vertices for each triangle.
If the quantities are defined at centers instead of vertices, this
will return None. Also see :method:`centers`.
:return: numpy array or None | entailment |
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 e... | 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... | entailment |
def set_for_computations(self, value):
"""
Set the quantities, either at the vertices or centers depending on the
settings of the mesh (mesh._compute_at_vertices)
"""
if self.mesh._compute_at_vertices:
self._vertices = value
else:
self._centers = v... | Set the quantities, either at the vertices or centers depending on the
settings of the mesh (mesh._compute_at_vertices) | entailment |
def update_columns_dict(self, kwargs):
"""
Update the value of a column or multiple columns by passing as a dict.
For observable columns, provide the label of the observable itself and
it will be found (so long as it does not conflict with an existing
non-observable column).
... | Update the value of a column or multiple columns by passing as a dict.
For observable columns, provide the label of the observable itself and
it will be found (so long as it does not conflict with an existing
non-observable column). | entailment |
def coords_for_observations(self):
"""
Return the coordinates from the center of the star for each element
(either centers or vertices depending on the setting in the mesh)
after perturbations (either by features or by offsetting to get
the correct volume). NOTE: this is NOT nec... | Return the coordinates from the center of the star for each element
(either centers or vertices depending on the setting in the mesh)
after perturbations (either by features or by offsetting to get
the correct volume). NOTE: this is NOT necessarily where the physical
parameters were com... | entailment |
def coords_for_computations(self):
"""
Return the coordinates from the center of the star for each element
(either centers or vertices depending on the setting in the mesh).
"""
# TODO: need to subtract the position offset if a Mesh (in orbit)
if self._compute_at_vertice... | Return the coordinates from the center of the star for each element
(either centers or vertices depending on the setting in the mesh). | entailment |
def rs(self):
"""
Return the radius of each element (either vertices or centers
depending on the setting in the mesh) with respect to the center of
the star.
NOTE: unscaled
(ComputedColumn)
"""
rs = np.linalg.norm(self.coords_for_computations, axis=1)
... | Return the radius of each element (either vertices or centers
depending on the setting in the mesh) with respect to the center of
the star.
NOTE: unscaled
(ComputedColumn) | entailment |
def rprojs(self):
"""
Return the projected (in xy/uv plane) radius of each element (either
vertices or centers depending on the setting in the mesh) with respect
to the center of the star.
NOTE: unscaled
(ComputedColumn)
"""
# TODO: should this be moved ... | Return the projected (in xy/uv plane) radius of each element (either
vertices or centers depending on the setting in the mesh) with respect
to the center of the star.
NOTE: unscaled
(ComputedColumn) | entailment |
def cosbetas(self):
"""
TODO: add documentation
(ComputedColumn)
"""
coords = self.coords_for_computations
norms = self.normals_for_computations
# TODO: ditch the list comprehension... I know I figured out how to do
# this (ie along an axis) with np.dot ... | TODO: add documentation
(ComputedColumn) | entailment |
def areas_si(self):
"""
TODO: add documentation
"""
if self._areas is not None:
return (self.areas*u.solRad**2).to(u.m**2).value
else:
return None | TODO: add documentation | entailment |
def from_proto(cls, proto_mesh, scale):
"""
TODO: add documentation
"""
mesh = cls(**proto_mesh.items())
mesh._copy_roche_values()
mesh._scale_mesh(scale=scale)
return mesh | TODO: add documentation | entailment |
def _scale_mesh(self, scale):
"""
TODO: add documentation
"""
pos_ks = ['vertices', 'centers']
# TODO: scale velocities???
# handle scale
self.update_columns_dict({k: self[k]*scale for k in pos_ks})
self.update_columns(areas=self.areas*(scale**2))
... | TODO: add documentation | entailment |
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 fram... | 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... | entailment |
def from_scaledproto(cls, scaledproto_mesh,
pos, vel, euler, euler_vel,
rotation_vel=(0,0,0),
component_com_x=None):
"""
TODO: add documentation
"""
mesh = cls(**scaledproto_mesh.items())
# roche coordin... | TODO: add documentation | entailment |
def _place_in_orbit(self, pos, vel, euler, euler_vel, rotation_vel=(0,0,0), component_com_x=None):
"""
TODO: add documentation
"""
# TODO: store pos, vel, euler so that INCREMENTAL changes are allowed
# if passing new values (and then make this a public method). See note
... | TODO: add documentation | entailment |
def visibilities(self):
"""
Return the array of visibilities, where each item is a scalar/float
between 0 (completely hidden/invisible) and 1 (completely visible).
(Nx1)
"""
if self._visibilities is not None:
return self._visibilities
else:
... | Return the array of visibilities, where each item is a scalar/float
between 0 (completely hidden/invisible) and 1 (completely visible).
(Nx1) | entailment |
def weights(self):
"""
TODO: add documentation
(Nx3)
"""
if self._weights is not None and len(self._weights):
return self._weights
else:
return np.full((self.Ntriangles, 3), 1./3) | TODO: add documentation
(Nx3) | entailment |
def update_columns_dict(self, kwargs):
"""
TODO: add documentation
"""
super(Mesh, self).update_columns_dict(kwargs)
# if kwargs.get('vnormals', None) is not None or kwargs.get('tnormals', None) is not None:
# self._compute_mus()
if kwargs.get('triangles', No... | TODO: add documentation | entailment |
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 dictiona... | 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 (ar... | entailment |
def get_column(self, field, components=None, computed_type='for_observations'):
"""
TODO: add documentation
return a dictionary for a single column, with component as keys and the
column array as values
:parameter str field: name of the mesh columnname
:parameter compon... | TODO: add documentation
return a dictionary for a single column, with component as keys and the
column array as values
:parameter str field: name of the mesh columnname
:parameter components: | entailment |
def get_column_flat(self, field, components=None, computed_type='for_observations'):
"""
TODO: add documentation
return a single merged value (hstacked) from all meshes
:parameter str field: name of the mesh columnname
:parameter components:
"""
return self.pack... | TODO: add documentation
return a single merged value (hstacked) from all meshes
:parameter str field: name of the mesh columnname
:parameter components: | entailment |
def pack_column_flat(self, value, components=None, offset=False):
"""
TODO: add documentation
"""
if components:
if isinstance(components, str):
components = [components]
elif isinstance(components, list):
components = components
... | TODO: add documentation | entailment |
def unpack_column_flat(self, value, components=None, offset=False, computed_type=None):
"""
TODO: add documentation
TODO: needs testing
"""
if components:
if isinstance(components, str):
components = [components]
else:
components = ... | TODO: add documentation
TODO: needs testing | entailment |
def set_column_flat(self, field, value, components=None, computed_type=None):
"""
TODO: add documentation
TODO: needs testing
"""
value_dict = self.unpack_column_flat(value, components, computed_type=computed_type)
self.update_columns(field, value_dict, computed_type=comp... | TODO: add documentation
TODO: needs testing | entailment |
def replace_elements(self, inds, new_submesh, component):
"""
TODO: add documentation
TODO: remove this method???
"""
self._dict[component] = np.hstack([self._dict[component][~inds], new_submesh]) | TODO: add documentation
TODO: remove this method??? | entailment |
def dynamics_from_bundle(b, times, compute=None, return_euler=False, **kwargs):
"""
Parse parameters in the bundle and call :func:`dynamics`.
See :func:`dynamics` for more detailed information.
NOTE: you must either provide compute (the label) OR all relevant options
as kwargs (ltte)
Args:
... | Parse parameters in the bundle and call :func:`dynamics`.
See :func:`dynamics` for more detailed information.
NOTE: you must either provide compute (the label) OR all relevant options
as kwargs (ltte)
Args:
b: (Bundle) the bundle with a set hierarchy
times: (list or array) times at wh... | entailment |
def dynamics(times, periods, eccs, smas, t0_perpasses, per0s, long_ans, incls,
dpdts, deccdts, dperdts, components, t0=0.0, vgamma=0.0,
mass_conservation=True, ltte=False, return_euler=False):
"""
Compute the positions and velocites of each star in their nested
Keplerian orbits at a ... | Compute the positions and velocites of each star in their nested
Keplerian orbits at a given list of times.
See :func:`dynamics_from_bundle` for a wrapper around this function
which automatically handles passing everything in the correct order
and in the correct units.
Args:
times: (iterab... | entailment |
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... | 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 an... | entailment |
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.... | 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` | entailment |
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.para... | 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` | entailment |
def anim_to_html(anim):
"""
adapted from: http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/
This function converts and animation object from matplotlib into HTML which can then
be embedded in an IPython notebook.
This requires ffmpeg to be installed in order to build the in... | adapted from: http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/
This function converts and animation object from matplotlib into HTML which can then
be embedded in an IPython notebook.
This requires ffmpeg to be installed in order to build the intermediate mp4 file
To get thes... | entailment |
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 = ... | load dictionary with lc data | entailment |
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['p... | load dictionary with rv data. | entailment |
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 pa... | 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 | entailment |
def N_to_Ntriangles(N):
"""
@N: WD style gridsize
Converts WD style grid size @N to the number of triangles on the
surface.
Returns: number of triangles.
"""
theta = np.array([np.pi/2*(k-0.5)/N for k in range(1, N+1)])
phi = np.array([[np.pi*(l-0.5)/Mk for l in range(1, Mk+1)] for Mk ... | @N: WD style gridsize
Converts WD style grid size @N to the number of triangles on the
surface.
Returns: number of triangles. | entailment |
def pot_for_component(pot, q, component=1, reverse=False):
"""
q for secondaries should already be flipped (via q_for_component)
"""
# currently only used by legacy wrapper: consider moving/removing
if component==1:
return pot
elif component==2:
if reverse:
return pot... | q for secondaries should already be flipped (via q_for_component) | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.