Helper function to combine trajectory properties such as site_properties or lattice
553522
def _combine_attribute(attr_1, attr_2, len_1, len_2):
        
        if isinstance(attr_1, list) or isinstance(attr_2, list):
            attribute = np.concatenate((attr_1, attr_2), axis=0)
            attribute_changes = True
        else:
            if isinstance(attr_1, list) and isinstance(attr_2, list) and np.allclose(attr_1, attr_2):
                attribute = attr_1
                attribute_changes = False
            else:
                attribute = [attr_1.copy()] * len_1 if type(attr_1) != list else attr_1.copy()
                attribute.extend([attr_2.copy()] * len_2 if type(attr_2 != list) else attr_2.copy())
                attribute_changes = True
        return attribute, attribute_changes
570709
function (properties, featureCollection, mergeKey) {
		var features = featureCollection.features;
		var featureIndex = L.GeometryUtils.indexFeatureCollection(features, mergeKey);
		var property;
		var mergeValue;
		var newFeatureCollection = {
			type: 'FeatureCollection',
			features: []
		};

		for (var key in properties) {
			if (properties.hasOwnProperty(key)) {
				property = properties[key];

				mergeValue = property[mergeKey];

				if (mergeValue) {
					var feature = featureIndex[mergeValue];

					for (var prop in property) {
						feature.properties[prop] = property[prop];
					}

					newFeatureCollection.features.push(feature);
				}
			}
		}

		return newFeatureCollection;
	}
280685
def _complete_trajectory(self, trajectory, index):
    """"""

    assert isinstance(trajectory, Trajectory)

    # This *should* be the case.
    assert trajectory.last_time_step.action is None

    # Add to completed trajectories.
    self._completed_trajectories.append(trajectory)

    # Make a new one to replace it.
    self._trajectories[index] = Trajectory()
137578
def from_geojson(cls, data):
        
        properties = data['properties']
        distance = properties.pop('distance')
        duration = properties.pop('duration')

        maneuvers = []
        for feature in data['features']:
            geom = feature['geometry']
            if geom['type'] == 'LineString':
                coords = geom['coordinates']
            else:
                maneuvers.append(Maneuver.from_geojson(feature))

        return Route(coords, distance, duration, maneuvers, **properties)
1198237
def _integrate_fixed_trajectory(self, h, T, step, relax):
        """"""
        # initialize the solution using initial condition
        solution = np.hstack((self.t, self.y))

        while self.successful():

            self.integrate(self.t + h, step, relax)
            current_step = np.hstack((self.t, self.y))
            solution = np.vstack((solution, current_step))

            if (h > 0) and (self.t >= T):
                break
            elif (h < 0) and (self.t <= T):
                break
            else:
                continue

        return solution
42271
def generate_coordinates(options = {})
        key_layer = layers.find { |layer| layer.relevant_data? }
      
        options[:point_distance] = width / (key_layer.points.size - 1).to_f

        coords = []

        #TODO this will likely break with the new hash model
        key_layer.points.each_with_index do |layer, idx|
          sum, objects = points.inject([0, 0]) do |arr, elem|
            if elem.relevant_data?
              arr[0] += elem.points[idx]
              arr[1] += 1
            end
            arr
          end

          average = sum / objects.to_f

          x_coord = options[:point_distance] * idx

          relative_percent = ((average == min_value) ? 0 : ((average - min_value) / (max_value - min_value).to_f))
          y_coord = (height - (height * relative_percent))

          coords << [x_coord, y_coord].join(',')
        end

        return coords
      end
253326
def export_frame_coordinates(topology, trajectory, nframe, output=None):
    
    if output is None:
        basename, ext = os.path.splitext(trajectory)
        output = '{}.frame{}.inpcrd'.format(basename, nframe)

    # ParmEd sometimes struggles with certain PRMTOP files
    if os.path.splitext(topology)[1] in ('.top', '.prmtop'):
        top = AmberPrmtopFile(topology)
        mdtop = mdtraj.Topology.from_openmm(top.topology)
        traj = mdtraj.load_frame(trajectory, int(nframe), top=mdtop)
        structure = parmed.openmm.load_topology(top.topology, system=top.createSystem())
        structure.box_vectors = top.topology.getPeriodicBoxVectors()

    else:  # standard protocol (the topology is loaded twice, though)
        traj = mdtraj.load_frame(trajectory, int(nframe), top=topology)
        structure = parmed.load_file(topology)

    structure.positions = traj.openmm_positions(0)

    if traj.unitcell_vectors is not None:  # if frame provides box vectors, use those
        structure.box_vectors = traj.openmm_boxes(0)

    structure.save(output, overwrite=True)
742019
def sigma_from_site_prop(self):
        
        num_coi = 0
        if None in self.site_properties['grain_label']:
            raise RuntimeError('Site were merged, this property do not work')
        for tag in self.site_properties['grain_label']:
            if 'incident' in tag:
                num_coi += 1
        return int(round(self.num_sites / num_coi))
735829
def _combine_to_jointcaller(processed):
    
    by_vrn_file = collections.OrderedDict()
    for data in (x[0] for x in processed):
        key = (tz.get_in(("config", "algorithm", "jointcaller"), data), data["vrn_file"])
        if key not in by_vrn_file:
            by_vrn_file[key] = []
        by_vrn_file[key].append(data)
    out = []
    for grouped_data in by_vrn_file.values():
        cur = grouped_data[0]
        out.append([cur])
    return out
759666
def _generate_time_steps(self, trajectory_list):
    """"""
    for single_trajectory in trajectory_list:
      assert isinstance(single_trajectory, trajectory.Trajectory)

      # Skip writing trajectories that have only a single time-step -- this
      # could just be a repeated reset.

      if single_trajectory.num_time_steps <= 1:
        continue

      for index, time_step in enumerate(single_trajectory.time_steps):

        # The first time-step doesn't have reward/processed_reward, if so, just
        # setting it to 0.0 / 0 should be OK.
        raw_reward = time_step.raw_reward
        if not raw_reward:
          raw_reward = 0.0

        processed_reward = time_step.processed_reward
        if not processed_reward:
          processed_reward = 0

        action = time_step.action
        if action is None:
          # The last time-step doesn't have action, and this action shouldn't be
          # used, gym's spaces have a `sample` function, so let's just sample an
          # action and use that.
          action = self.action_space.sample()
        action = gym_spaces_utils.gym_space_encode(self.action_space, action)

        if six.PY3:
          # py3 complains that, to_example cannot handle np.int64 !

          action_dtype = self.action_space.dtype
          if action_dtype in [np.int64, np.int32]:
            action = list(map(int, action))
          elif action_dtype in [np.float64, np.float32]:
            action = list(map(float, action))

          # same with processed_reward.
          processed_reward = int(processed_reward)

        assert time_step.observation is not None

        yield {
            TIMESTEP_FIELD: [index],
            ACTION_FIELD:
                action,
            # to_example errors on np.float32
            RAW_REWARD_FIELD: [float(raw_reward)],
            PROCESSED_REWARD_FIELD: [processed_reward],
            # to_example doesn't know bools
            DONE_FIELD: [int(time_step.done)],
            OBSERVATION_FIELD:
                gym_spaces_utils.gym_space_encode(self.observation_space,
                                                  time_step.observation),
        }
588703
function(starts, moves) {
		if(starts.length >= 2 && moves.length >= 2) {
			var props = ['pageX', 'pageY'];
			return getDistance(moves[1], moves[0], props) / getDistance(starts[1], starts[0], props);
		}
		return 1;
	}
764512
function ( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) {

			for ( var i = 2; i < faceLength; i ++ ) {

				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] );

				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );

				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] );
				buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] );

				if ( geoInfo.skeleton ) {

					buffers.vertexWeights.push( faceWeights[ 0 ] );
					buffers.vertexWeights.push( faceWeights[ 1 ] );
					buffers.vertexWeights.push( faceWeights[ 2 ] );
					buffers.vertexWeights.push( faceWeights[ 3 ] );

					buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] );
					buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
					buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
					buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );

					buffers.vertexWeights.push( faceWeights[ i * 4 ] );
					buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] );
					buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] );
					buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] );

					buffers.weightsIndices.push( faceWeightIndices[ 0 ] );
					buffers.weightsIndices.push( faceWeightIndices[ 1 ] );
					buffers.weightsIndices.push( faceWeightIndices[ 2 ] );
					buffers.weightsIndices.push( faceWeightIndices[ 3 ] );

					buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
					buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
					buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
					buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );

					buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] );
					buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] );
					buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] );
					buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] );

				}

				if ( geoInfo.color ) {

					buffers.colors.push( faceColors[ 0 ] );
					buffers.colors.push( faceColors[ 1 ] );
					buffers.colors.push( faceColors[ 2 ] );

					buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] );
					buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
					buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] );

					buffers.colors.push( faceColors[ i * 3 ] );
					buffers.colors.push( faceColors[ i * 3 + 1 ] );
					buffers.colors.push( faceColors[ i * 3 + 2 ] );

				}

				if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {

					buffers.materialIndex.push( materialIndex );
					buffers.materialIndex.push( materialIndex );
					buffers.materialIndex.push( materialIndex );

				}

				if ( geoInfo.normal ) {

					buffers.normal.push( faceNormals[ 0 ] );
					buffers.normal.push( faceNormals[ 1 ] );
					buffers.normal.push( faceNormals[ 2 ] );

					buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] );
					buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
					buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );

					buffers.normal.push( faceNormals[ i * 3 ] );
					buffers.normal.push( faceNormals[ i * 3 + 1 ] );
					buffers.normal.push( faceNormals[ i * 3 + 2 ] );

				}

				if ( geoInfo.uv ) {

					geoInfo.uv.forEach( function ( uv, j ) {

						if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = [];

						buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] );
						buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] );

						buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
						buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );

						buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] );
						buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );

					} );

				}

			}

		}
133086
def merge_coords_for_inplace_math(objs, priority_vars=None):
    
    expanded = expand_variable_dicts(objs)
    variables = merge_variables(expanded, priority_vars)
    assert_unique_multiindex_level_names(variables)
    return variables
334020
def sample_trajectories(self, rollout_length, batch_info) -> Trajectories:
        
        indexes = self.backend.sample_batch_trajectories(rollout_length)
        transition_tensors = self.backend.get_trajectories(indexes, rollout_length)

        return Trajectories(
            num_steps=rollout_length,
            num_envs=self.backend.num_envs,
            environment_information=None,
            transition_tensors={k: torch.from_numpy(v) for k, v in transition_tensors.items()},
            rollout_tensors={}
        )
1275246
function gatherPopulateParams (populate, pointers, model, deepPath) {
  var modelName = model.modelName;
  var paths = model.schema.paths;
  var path = '';
  var options;
  var params;
  var ref;
  var deep = false;
  
  while (deepPath.length) {
    path += (path ? '.' : '')+deepPath.shift();
    options = paths[path] && (
      paths[path].caster && paths[path].caster.options
      || paths[path].options
    );
    if (!options) {
      continue;
    }

    params = pointers[path] || (pointers[path] = {});
    ref = options.ref || options.type[0] && options.type[0].ref;
    if (!ref) {
      if (selectPointers(params)) {
        deep = true;
      }
      continue;
    }

    if (!params.path) {
      params.path = path;
      params.model = ref;
      params.populate = [];
      params.pointers = {};
      populate.push(params);
    }
    if (gatherPopulateParams(
      params.populate,
      params.pointers,
      model.model(ref),
      deepPath
    )) {
      deep = true;
    }
    if (selectPointers(params)) {
      deep = true;
    }
  }

  return deep;
}
770463
def _map_trajectory(self):
        
        self.trajectory_map = {}
        with open(self.filepath, 'r') as trajectory_file:
            with closing(
                    mmap(
                        trajectory_file.fileno(), 0,
                        access=ACCESS_READ)) as mapped_file:
                progress = 0
                line = 0
                frame = -1
                frame_start = 0
                while progress <= len(mapped_file):
                    line = line + 1
                    # We read a binary data from a mapped file.
                    bline = mapped_file.readline()
                    # If the bline length equals zero we terminate.
                    # We reached end of the file but still add the last frame!
                    if len(bline) == 0:
                        frame = frame + 1
                        if progress - frame_start > 10:
                            self.trajectory_map[frame] = [
                                frame_start, progress
                            ]
                        break
                    # We need to decode byte line into an utf-8 string.
                    sline = bline.decode("utf-8").strip('\n').split()
                    # We extract map's byte coordinates for each frame
                    if len(sline) == 1 and sline[0] == 'END':
                        frame = frame + 1
                        self.trajectory_map[frame] = [frame_start, progress]
                        frame_start = progress
                    # Here we extract the map's byte coordinates for the header
                    # And also the periodic system type needed for later.
                    progress = progress + len(bline)
            self.no_of_frames = frame
892533
def _arithmetic_operation(self, other, operation):
        
        if isinstance(other, Trajectory):
            if self.description != other.description:
                raise Exception("Cannot add trajectories with different descriptions")
            if not np.array_equal(self.timepoints, other.timepoints):
                raise Exception("Cannot add trajectories with different time points")
            new_values = operation(self.values, other.values)
        elif isinstance(other, numbers.Real):
            new_values = operation(self.values, float(other))
        else:
            raise Exception("Arithmetic operations is between two `Trajectory` objects or a `Trajectory` and a scalar.")

        return Trajectory(self.timepoints, new_values, self.description)