code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
data = data or {} return self.post(vehicle_id, 'command/%s' % name, data, wake_if_asleep=wake_if_asleep)
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 car across different endpoints. https://tesla-api.timdo...
2.876119
4.485562
0.641195
cur_time = time.time() with self.__lock: # Update the online cars using get_vehicles() last_update = self._last_attempted_update_time if (force or cur_time - last_update > self.update_interval): cars = self.get_vehicles() for ...
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 cached values for cars that are awake assuming no update has occurred f...
3.45146
3.260448
1.058585
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)
Update the battery state.
4.780776
4.015455
1.190594
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[...
def update(self)
Update the battery range state.
4.130232
3.752042
1.100796
# pylint: disable=protected-access 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)
Return whether the data is from an online vehicle.
7.226022
5.52518
1.307835
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 an...
def update(self)
Update the current GPS location.
3.462159
3.172534
1.091291
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/h...
def update(self)
Update the odometer and the unit of measurement based on GUI.
5.455713
4.978058
1.095952
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_p...
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...
4.15586
4.095257
1.014798
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() #...
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...
8.534063
8.416806
1.013931
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() #...
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 al...
9.181373
9.225317
0.995237
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()...
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.Param...
11.240553
10.875401
1.033576
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')] #...
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...
3.606253
3.623717
0.995181
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@syste...
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 ...
10.474075
9.929634
1.05483
if not conf.devel: raise NotImplementedError("'photodynam' backend not officially supported for this release. Enable developer mode to test.") params = [] params += [BoolParameter(qualifier='enabled', copy_for={'context': 'dataset', 'kind': ['lc', 'rv', 'orb'], 'dataset': '*'}, dataset='_def...
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 a list of sources to cite when us...
7.905137
7.653488
1.03288
if not conf.devel: raise NotImplementedError("'jktebop' backend not officially supported for this release. Enable developer mode to test.") params = [] params += [BoolParameter(qualifier='enabled', copy_for={'context': 'dataset', 'kind': ['lc'], 'dataset': '*'}, dataset='_default', value=kwa...
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 list of sources to cite when usin...
16.790848
16.086046
1.043814
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...
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
1.700316
1.688685
1.006888
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, Memb...
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.
2.109724
1.961935
1.075328
if self.use_main_ns: self.namespace = __main__.__dict__ if state == 0: self.matches = self.attr_matches(text) try: return self.matches[state] except IndexError: return None
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'.
4.897698
4.349617
1.126007
def _method_or_attr(thisobject, item): # decide whether to append a '(' to the end of the attr based # on whether its callable if hasattr(getattr(thisobject, item), '__call__'): return item + '(' else: return item ...
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 instances, class members are also considered.)...
4.295833
4.212386
1.01981
# 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['kin...
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
7.845247
7.099594
1.105028
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 ...
def _make_packet(qualifier, value, time, info, **kwargs)
where kwargs overrides info
2.867164
2.762894
1.03774
raise NotImplementedError("run_checks is not implemented by the {} backend".format(self.__class__.__name__))
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. ...
5.99157
4.913984
1.21929
packet, new_syns = self._get_packet_and_syns(b, compute, times, **kwargs) for k,v in kwargs.items(): packet[k] = v packet['b'] = b.to_json() if mpi.enabled else b packet['compute'] = compute packet['backend'] = self.__class__.__name__ return packet,...
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 be included in the packet serialized * compute: the label of the compute o...
3.505471
3.342998
1.048601
# 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: # sin...
def _fill_syns(self, new_syns, rpacketlists_per_worker)
rpacket_per_worker is a list of packetlists as returned by _run_chunk
7.83201
7.765925
1.00851
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 ...
def run(self, b, compute, times=[], **kwargs)
if within mpirun, workers should call _run_worker instead of run
5.627324
5.409694
1.04023
# 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 ...
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)
13.846994
13.729475
1.00856
s1 = sin(eincl); c1 = cos(eincl); s2 = sin(elongan); c2 = cos(elongan); s3 = sin(etheta); c3 = cos(etheta); c1s3 = c1*s3; c1c3 = c1*c3; return np.array([ [-c2*c3+s2*c1s3, c2*s3+s2*c1c3, -s2*s1], [-s2*c3-c2*c1s3, s2*s3-c2*c1c3, c2...
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, 0 0, cos(u), -sin(u) 0, ...
1.836013
1.842296
0.996589
#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)
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
3.07282
3.429322
0.896043
# 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)
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.
9.048768
9.838934
0.91969
C = cos(alpha) S = sin(alpha) t = 1 - C ux = sin(theta)*cos(phi) uy = sin(theta)*sin(phi) uz = cos(theta) return np.array([ [t*ux**2 + C, t*ux*uy - S*uz, t*ux*uz + S*uy], [t*ux*uy + S*uz, t*uy**2 + C, t*uy*uz - S*ux], [t*ux*uz - S*uy, t*uy...
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 angle :return: 3x3 matrix of floats
1.729706
1.678019
1.030802
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) ...
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 ...
4.424052
4.911952
0.900671
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...
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 elem...
6.482144
7.120809
0.91031
# 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 Com...
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 floa...
5.978898
5.670826
1.054326
if not self.mesh._compute_at_vertices: return None return np.mean(self.vertices_per_triangle, axis=1)
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
11.429863
9.622085
1.187878
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.weigh...
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...
2.970321
2.81156
1.056467
if self.mesh._compute_at_vertices: self._vertices = value else: self._centers = value
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)
12.406676
3.050475
4.067129
# make sure to do the geometric things that are needed for some of the # ComputedColumns first for key in ('triangles', 'vertices', 'centers', 'vnormals', 'tnormals'): if key in kwargs.keys(): self.__setitem__(key, kwargs.pop(key)) for k, v in kwargs...
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).
6.632051
6.821448
0.972235
if self._compute_at_vertices: return self.vertices - self._pos_center else: return self.centers - self._pos_center
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 necessarily where the physical parameters were com...
9.015268
5.191638
1.736498
# TODO: need to subtract the position offset if a Mesh (in orbit) if self._compute_at_vertices: if self.pvertices is not None: return self.pvertices - self._pos_center else: return self.vertices - self._pos_center else: ...
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).
8.739176
6.571707
1.329818
rs = np.linalg.norm(self.coords_for_computations, axis=1) return ComputedColumn(self, rs)
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)
13.477377
8.71316
1.546784
# TODO: should this be moved to Mesh? Even though its surely possible # to compute without being placed in orbit, projecting in x,y doesn't # make much sense without LOS orientation. rprojs = np.linalg.norm(self.coords_for_computations[:,:2], axis=1) return ComputedColu...
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)
20.747438
15.943498
1.30131
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 somewhere else # cosbetas = np.array([np.dot(c,n) / (np.linalg.norm(c)*np.linalg.norm...
def cosbetas(self)
TODO: add documentation (ComputedColumn)
7.289527
6.585701
1.106872
if self._areas is not None: return (self.areas*u.solRad**2).to(u.m**2).value else: return None
def areas_si(self)
TODO: add documentation
4.403275
3.863979
1.13957
mesh = cls(**proto_mesh.items()) mesh._copy_roche_values() mesh._scale_mesh(scale=scale) return mesh
def from_proto(cls, proto_mesh, scale)
TODO: add documentation
12.367792
10.39291
1.190022
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)) self._volume *= scale**3 if self._area is not None: # ...
def _scale_mesh(self, scale)
TODO: add documentation
11.229255
10.605337
1.058831
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)
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...
5.340407
5.338463
1.000364
mesh = cls(**scaledproto_mesh.items()) # roche coordinates have already been copied # so do NOT call mesh._copy_roche_values() here mesh._place_in_orbit(pos, vel, euler, euler_vel, rotation_vel, component_com_x) return mesh
def from_scaledproto(cls, scaledproto_mesh, pos, vel, euler, euler_vel, rotation_vel=(0,0,0), component_com_x=None)
TODO: add documentation
7.856339
8.006446
0.981252
# TODO: store pos, vel, euler so that INCREMENTAL changes are allowed # if passing new values (and then make this a public method). See note # below! pos_ks = ['vertices', 'pvertices', 'centers'] norm_ks = ['vnormals', 'tnormals'] #, 'cnormals'] vel_ks = ['vel...
def _place_in_orbit(self, pos, vel, euler, euler_vel, rotation_vel=(0,0,0), component_com_x=None)
TODO: add documentation
5.712678
5.708069
1.000807
if self._visibilities is not None: return self._visibilities else: return np.ones(self.Ntriangles)
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)
4.389868
4.475812
0.980798
if self._weights is not None and len(self._weights): return self._weights else: return np.full((self.Ntriangles, 3), 1./3)
def weights(self)
TODO: add documentation (Nx3)
5.236969
4.909632
1.066672
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', None) is not None: # reset visibilities and velocities so that they are rese...
def update_columns_dict(self, kwargs)
TODO: add documentation
6.581643
6.355134
1.035642
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_a...
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 (ar...
5.220348
5.151257
1.013413
def get_field(c, field, computed_type): if c not in self._dict.keys() and self._parent_envelope_of[c] in self._dict.keys(): mesh = self._dict[self._parent_envelope_of[c]] return mesh.get_column_flat(field, components, computed_type) mesh = self....
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 components:
4.511752
4.486596
1.005607
return self.pack_column_flat(self.get_column(field, components, computed_type), components, offset=field=='triangles')
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:
11.074108
17.784786
0.622673
if components: if isinstance(components, str): components = [components] elif isinstance(components, list): components = components else: raise TypeError("components should be list or string, not {}".format(type(compone...
def pack_column_flat(self, value, components=None, offset=False)
TODO: add documentation
2.52275
2.459616
1.025669
if components: if isinstance(components, str): components = [components] else: components = self._dict.keys() # TODO: add this # we need to split the flat array by the lengths of each mesh N_lower = 0 N_upper = 0 ...
def unpack_column_flat(self, value, components=None, offset=False, computed_type=None)
TODO: add documentation TODO: needs testing
4.890173
4.696465
1.041246
value_dict = self.unpack_column_flat(value, components, computed_type=computed_type) self.update_columns(field, value_dict, computed_type=computed_type)
def set_column_flat(self, field, value, components=None, computed_type=None)
TODO: add documentation TODO: needs testing
3.696433
3.345959
1.104745
self._dict[component] = np.hstack([self._dict[component][~inds], new_submesh])
def replace_elements(self, inds, new_submesh, component)
TODO: add documentation TODO: remove this method???
5.991964
5.186564
1.155286
r # 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__...
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 an...
4.823923
4.936828
0.97713
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 ...
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`
2.89483
2.780914
1.040963
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='Relati...
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`
4.522248
4.461679
1.013576
if not hasattr(anim, '_encoded_video'): with NamedTemporaryFile(suffix='.mp4') as f: anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264']) video = open(f.name, "rb").read() anim._encoded_video = video.encode("base64") return VIDEO_TAG.format(anim._encoded_vid...
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 intermediate mp4 file To get thes...
2.619434
2.790653
0.938645
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': ...
def load_lc_data(filename, indep, dep, indweight=None, mzero=None, dir='./')
load dictionary with lc data
3.924024
3.900388
1.00606
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=...
def load_rv_data(filename, indep, dep, indweight=None, dir='./')
load dictionary with rv data.
4.217866
4.183986
1.008098
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', da...
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
4.363235
4.242349
1.028495
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 in np.array(1 + 1.3*N*np.sin(theta), dtype=int)]) Ntri = 2*np.array([len(p) for p in phi]).sum() return Ntri
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.
4.284462
4.358755
0.982955
# currently only used by legacy wrapper: consider moving/removing if component==1: return pot elif component==2: if reverse: return pot/q + 0.5*(q-1)/q else: return q*pot - 0.5 * (q-1) else: raise NotImplementedError
def pot_for_component(pot, q, component=1, reverse=False)
q for secondaries should already be flipped (via q_for_component)
6.534478
6.622577
0.986697
volume_critical = libphoebe.roche_misaligned_critical_volume(q, F, d, s) logger.debug("libphoebe.roche_misaligned_critical_volume(q={}, F={}, d={}, s={}) => {}".format(q, F, d, s, volume_critical)) requiv_critical = scale * (volume_critical * 3./4 * 1./np.pi)**(1./3) # logger.debug("roche.roche_mi...
def roche_misaligned_critical_requiv(q, F, d, s, scale=1.0)
NOTE: output is in units of scale (so constraints will use SI) NOTE: q should already be flipped (i.e. the output of q_for_component) if necessary NOTE: s should be in roche coordinates at the applicable time/true anomaly
3.279556
3.467352
0.945839
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)
Transforms polar radius to surface potential
4.510598
4.494107
1.003669
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)
Transforms surface potential to polar radius
6.058568
6.137187
0.98719
r 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)
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}} ...
3.113066
2.140227
1.454549
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)
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
3.16837
3.255437
0.973255
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)
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
2.230533
2.236046
0.997534
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)
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
3.158472
3.211875
0.983373
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)
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
2.843805
2.765394
1.028354
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)
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
5.37695
5.191531
1.035716
params = [] params += [StringParameter(qualifier='phoebe_version', value=kwargs.get('phoebe_version', __version__), description='Version of PHOEBE - change with caution')] params += [BoolParameter(qualifier='log_history', value=kwargs.get('log_history', False), description='Whether to log history (un...
def settings(**kwargs)
Generally, this will automatically be added to a newly initialized :class:`phoebe.frontend.bundle.Bundle` :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.Par...
5.923712
5.787376
1.023557
@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...
def send_if_client(fctn)
Intercept and send to the server if bundle is in client mode.
5.145051
5.008632
1.027237
@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() ...
def update_if_client(fctn)
Intercept and check updates from server if bundle is in client mode.
2.543285
2.298718
1.106393
return ''.join(random.SystemRandom().choice( string.ascii_uppercase + string.ascii_lowercase) for _ in range(n))
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
2.898296
3.723406
0.778399
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 ...
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
7.730249
8.421145
0.917957
return OrderedDict([(k, getattr(self, k)) for k in _meta_fields_twig if k not in ignore])
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 a...
10.492384
13.506797
0.776823
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)
Set the value of tags for all Parameters in this ParameterSet.
6.839505
5.547543
1.232889
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)
Returns a dictionary that lists all available tags that can be used for further filtering
15.129073
14.96407
1.011027
return "@".join([getattr(self, k) for k in _meta_fields_twig if self.meta.get(k) is not None])
def common_twig(self)
The twig that is common between all items in this ParameterSet. This twig gives a single string which can point back to this ParameterSet (but may include other entries as well) see also :meth:`uniquetwig` :return: twig (full) of this Parameter
10.881373
16.796669
0.647829
# 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]) ...
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
4.870366
3.810383
1.278183
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 ...
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 shoul...
4.306929
4.207338
1.023671
lst = params.to_list() if isinstance(params, ParameterSet) else params for param in lst: param._bundle = self for k, v in kwargs.items(): # Here we'll set the attributes (_context, _qualifier, etc) if getattr(param, '_{}'.format(k)) is No...
def _attach_params(self, params, **kwargs)
Attach a list of parameters (or ParameterSet) to this ParameterSet. :parameter list params: list of parameters, or ParameterSet :parameter **kwargs: attributes to set for each parameter (ie tags)
6.044359
5.603226
1.078728
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 ...
def _check_copy_for(self)
Check the value of copy_for and make appropriate copies.
4.69283
4.64307
1.010717
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 Valu...
def _check_label(self, label)
Check to see if the label is allowed.
4.346813
4.23489
1.026429
filename = os.path.expanduser(filename) f = open(filename, 'r') if _can_ujson: # NOTE: this will not parse the unicode. Bundle.open always calls # json instead of ujson for this reason. data = ujson.load(f) else: data = json.load(...
def open(cls, filename)
Open a ParameterSet from a JSON-formatted file. This is a constructor so should be called as: >>> b = ParameterSet.open('test.json') :parameter str filename: relative or full path to the file :return: instantiated :class:`ParameterSet` object
5.209931
6.485722
0.803292
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 fas...
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 boo...
2.342294
2.40492
0.973959
if self._bundle is None or not self._bundle.is_client: raise ValueError("bundle must be in client mode") if len(kwargs): return self.filter(**kwargs).ui(client=client) querystr = "&".join(["{}={}".format(k, v) for k, v in self._filt...
def ui(self, client='http://localhost:4200', **kwargs)
[NOT IMPLEMENTED] The bundle must be in client mode in order to open the web-interface. See :meth:`Bundle:as_client` to switch to client mode. :parameter str client: URL of the running client which must be connected to the same server as the bundle :return: URL of the param...
4.353191
3.587796
1.213333
if kwargs: return self.filter(**kwargs).to_list() return self._params
def to_list(self, **kwargs)
Convert the :class:`ParameterSet` to a list of :class:`Parameter`s :return: list of class:`Parameter` objects
8.384675
9.655508
0.868383
if kwargs: return self.filter(**kwargs).to_list_of_dicts() return [param.to_dict() for param in self._params]
def to_list_of_dicts(self, **kwargs)
Convert the :class:`ParameterSet` to a list of the dictionary representation of each :class:`Parameter` :return: list of dicts
4.117989
4.09875
1.004694
if kwargs: return self.filter(**kwargs).to_flat_dict() return {param.uniquetwig: param for param in self._params}
def to_flat_dict(self, **kwargs)
Convert the :class:`ParameterSet` to a flat dictionary, with keys being uniquetwigs to access the parameter and values being the :class:`Parameter` objects themselves. :return: dict of :class:`Parameter`s
12.750867
5.720257
2.229072
if kwargs: return self.filter(**kwargs).to_dict(field=field) if field is not None: keys_for_this_field = set([getattr(p, field) for p in self.to_list() if getattr(p, field) is not None]) ...
def to_dict(self, field=None, **kwargs)
Convert the ParameterSet to a structured (nested) dictionary to allow traversing the structure from the bottom up :parameter str field: (optional) build the dictionary with keys at a given level/field. Can be any of the keys in :func:`meta`. If None, the keys will be the lowes...
4.754591
4.47779
1.061816
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...
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 ...
3.23939
3.052106
1.061362
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()] ...
def to_json(self, incl_uniqueid=False)
Convert the ParameterSet to a json-compatible dictionary :return: list of dictionaries
6.184937
6.24769
0.989956
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)
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 ...
3.700725
5.797086
0.638377