Computes the distribution of trajectory lengths, i.e.
        the number of saccades that were made as a part of one trajectory
        
        Parameters:
            fm : ocupy.fixmat 
                The fixation data to be analysed
432492
def trajLenDist(fm):
      
    trajLen = np.roll(fm.fix, 1)[fm.fix == min(fm.fix)]
    val, borders = np.histogram(trajLen, 
                    bins=np.linspace(-0.5, max(trajLen)+0.5, max(trajLen)+2))
    cumsum = np.cumsum(val.astype(float) / val.sum())
    return cumsum, borders
689155
function computeSlotSegCollisions(seg, otherSegs, results) {
	results = results || [];

	for (var i=0; i<otherSegs.length; i++) {
		if (isSlotSegCollision(seg, otherSegs[i])) {
			results.push(otherSegs[i]);
		}
	}

	return results;
}
435428
def find_num_contigs(self):
        
        for sample in self.metadata:
            # Use the len() method to count the number of entries in the list
            sample[self.analysistype].num_contigs = len(sample[self.analysistype].contig_lengths)
1055341
def _analytical_fit_adjacent(self, ref_dists):
        
        dists = ref_dists**2
        rot_dists = self._rotate_rows(dists)
        b = dists - rot_dists + self._partial_b
        self._b = b
        return self._pinvA.dot(b)
634468
def is_single_trajectory(nc, variable):
    '''
    
    '''
    # x(o), y(o), z(o), t(o)
    # X(o)
    # cf_role must be trajectory
    dims = nc.variables[variable].dimensions

    cmatrix = coordinate_dimension_matrix(nc)
    # Time is required for trajectories
    if 't' not in cmatrix:
        return False
    # Coordinates changing with time are optional
    if 'x' in cmatrix:
        if cmatrix['x'] != cmatrix['t']:
            return False
    if 'y' in cmatrix:
        if cmatrix['y'] != cmatrix['t']:
            return False
    if 'z' in cmatrix:
        if cmatrix['z'] != cmatrix['t']:
            return False
    if dims != cmatrix['t']:
        return False
    traj_ids = nc.get_variables_by_attributes(cf_role="trajectory_id")
    if len(traj_ids) != 1:
        return False
    return True
533790
def _calculate_apm(index, player_actions, other_actions, duration):
    """"""
    apm_per_player = {}
    for player_index, histogram in player_actions.items():
        apm_per_player[player_index] = sum(histogram.values())
    total_unattributed = sum(other_actions.values())
    total_attributed = sum(apm_per_player.values())
    player_proportion = apm_per_player[index] / total_attributed
    player_unattributed = total_unattributed * player_proportion
    apm = (apm_per_player[index] + player_unattributed) / (duration / 60)
    return int(apm)
19436
def plotAccuracyDuringSensorimotorInference(resultsFig5B, title="", yaxis=""):
  
  # Read out results and get the ranges we want.
  with open(resultsFig5B, "rb") as f:
    results = cPickle.load(f)

  objectRange = []
  featureRange = []
  for r in results:
    if r["numObjects"] not in objectRange: objectRange.append(r["numObjects"])
    if r["numFeatures"] not in featureRange: featureRange.append(r["numFeatures"])
  objectRange.sort()
  featureRange.sort()
  print "objectRange=",objectRange
  print "featureRange=",featureRange

  ########################################################################
  #
  # Accumulate the TM accuracies for each condition in a list and compute mean
  # and stdeviations
  # For L2 we average across all feature ranges
  accuracies = defaultdict(list)
  l2Accuracies = defaultdict(list)
  for r in results:
    accuracies[(r["numObjects"], r["numFeatures"])].append(r["objectCorrectSparsityTM"])
    l2Accuracies[r["numObjects"]].append(r["objectAccuracyL2"])

  # meanAccuracy[o,f] = accuracy of TM with o objects and f unique features.
  meanAccuracy = numpy.zeros((max(objectRange)+1, max(featureRange) + 1))
  stdev = numpy.zeros((max(objectRange)+1, max(featureRange) + 1))
  meanL2Accuracy = numpy.zeros(max(objectRange)+1)
  stdevL2 = numpy.zeros(max(objectRange)+1)
  for o in objectRange:
    for f in featureRange:
      a = numpy.array(accuracies[(o, f)])
      meanAccuracy[o, f] = 100.0*a.mean()
      stdev[o, f] = 100.0*a.std()

    # Accuracies for L2
    a = numpy.array(l2Accuracies[o])
    meanL2Accuracy[o] = 100.0*a.mean()
    stdevL2[o] = 100.0*a.std()


  # Create the plot.
  plt.figure()
  plotPath = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                          "plots", "accuracy_during_sensorimotor_inference.pdf")

  # Plot each curve
  legendList = []
  colorList = ['r', 'b', 'g', 'm', 'c', 'k', 'y']

  for i in range(len(featureRange)):
    f = featureRange[i]
    legendList.append('Sequence layer, feature pool size: {}'.format(f))
    plt.errorbar(objectRange, meanAccuracy[objectRange, f],
                 yerr=stdev[objectRange, f],
                 color=colorList[i])

  plt.errorbar(objectRange, meanL2Accuracy[objectRange],
               yerr=stdevL2[objectRange],
               color=colorList[len(featureRange)])
  legendList.append('Sensorimotor layer')

  # format
  plt.legend(legendList, bbox_to_anchor=(0., 0.6, 1., .102), loc="right", prop={'size':10})
  plt.xlabel("Number of objects")
  plt.ylim(-10.0, 110.0)
  plt.ylabel(yaxis)
  plt.title(title)

    # save
  plt.savefig(plotPath)
  plt.close()
1316401
private void estimateFar() {

		// do nothing if there are objects at infinity
		farInlierCount = 0;
		if (farAngles.size == 0)
			return;

		farAnglesCopy.reset();
		farAnglesCopy.addAll(farAngles);

		// find angle which maximizes inlier set
		farAngle = maximizeCountInSpread(farAnglesCopy.data, farAngles.size, 2 * thresholdFarAngleError);

		// mark and count inliers
		for (int i = 0; i < tracksFar.size(); i++) {
			PointTrack t = tracksFar.get(i);
			VoTrack p = t.getCookie();

			if (UtilAngle.dist(farAngles.get(i), farAngle) <= thresholdFarAngleError) {
				p.lastInlier = tick;
				farInlierCount++;
			}
		}
	}
791060
def is_single_trajectory(nc, variable):
    '''
    
    '''
    # x(t), y(t), z(t), t(t)
    # X(t)
    dims = nc.variables[variable].dimensions
    cmatrix = coordinate_dimension_matrix(nc)

    for req in ('x', 'y', 't'):
        if req not in cmatrix:
            return False
    t = get_time_variable(nc)
    if cmatrix['x'] != (t,):
        return False
    if cmatrix['x'] != cmatrix['y']:
        return False
    if cmatrix['x'] != cmatrix['t']:
        return False
    if 'z' in cmatrix and cmatrix['x'] != cmatrix['z']:
        return False
    if dims == cmatrix['x']:
        return True
    return False
854728
def numberOfConnectedProximalSynapses(self, cells=None):
    
    if cells is None:
      cells = xrange(self.numberOfCells())

    return _countWhereGreaterEqualInRows(self.proximalPermanences, cells,
                                         self.connectedPermanenceProximal)
789385
def visualize_qual_stats_dict_single(D, dest, title):
    

    # first find out how many cycles were there. it is going to be about 101 for
    # hiseq runs, and 251 in miseq runs, but these values may change from run to
    # run. although all lanes are expected to have the identical number of cycles
    # the following code makes sure that the number_of_cycles variable holds the
    # longest one if there is a variation between the number of cycles between
    # lanes
    number_of_cycles = 0
    for pair in ['1', '2']:
        if pair not in D:
            continue
        for tile in D[pair]:
            if len(D[pair][tile]['mean']) > number_of_cycles:
                number_of_cycles = len(D[pair][tile]['mean'])


    fig = plt.figure(figsize = (12, 8))

    plt.rcParams.update({'axes.linewidth' : 0.9})
    plt.rc('grid', color='0.50', linestyle='-', linewidth=0.1)

    all_tiles = {'1': {'mean': [0] * number_of_cycles, 'count': [0] * number_of_cycles},
                 '2': {'mean': [0] * number_of_cycles, 'count': [0] * number_of_cycles}
                }

    for i in range(0, number_of_cycles):
        means_p1 = []
        counts_p1 = []
        means_p2 = []
        counts_p2 = []
        for tile_id in D['1']:
            tile = D['1'][tile_id]
            means_p1.append(tile['mean'][i])
            counts_p1.append(tile['count'][i])
            if '2' in D and D['2']:
                tile = D['2'][tile_id]
                means_p2.append(tile['mean'][i])
                counts_p2.append(tile['count'][i])

        all_tiles['1']['mean'][i] = numpy.mean(means_p1)
        all_tiles['1']['count'][i] = sum(counts_p1)

        if '2' in D and D['2']:
            all_tiles['2']['mean'][i] = numpy.mean(means_p2)
            all_tiles['2']['count'][i] = sum(counts_p2)

    colors = cm.get_cmap('RdYlGn', lut=256)

    plt.grid(True)

    plt.subplots_adjust(left=0.02, bottom = 0.03, top = 0.95, right = 0.98)

    plt.xticks(list(range(number_of_cycles / 10, number_of_cycles, number_of_cycles / 10)), rotation=90, size='xx-small')
    plt.ylim(ymin = 0, ymax = 42)
    plt.xlim(xmin = 0, xmax = number_of_cycles - 1)
    plt.yticks(list(range(5, 41, 5)), size='xx-small')

    plt.fill_between(list(range(0, number_of_cycles)), [42 for _ in range(0, number_of_cycles)], y2 = 0, color = colors(0), alpha = 0.2)
    plt.plot(all_tiles['1']['mean'], color = 'orange', lw = 6)

    read_number_percent_dropdown = [42 * (x / all_tiles['1']['count'][0]) for x in all_tiles['1']['count']]
    if not len(set(read_number_percent_dropdown)) <= 1:
        plt.fill_between(list(range(0, number_of_cycles)), read_number_percent_dropdown, y2 = 0, color = 'black', alpha = 0.08)

        plt.text(5, 2.5, '%s' % big_number_pretty_print(all_tiles['1']['count'][0]), alpha=0.5)
    else:
        plt.text(5, 2.5, '%s' % big_number_pretty_print(all_tiles['1']['count'][0]), alpha=0.5)

    if '2' in all_tiles and all_tiles['2']:
        plt.plot(all_tiles['2']['mean'], color = 'purple', lw = 6)

    plt.figtext(0.5, 0.97, '%s' % (title), weight = 'black', size = 'xx-large', ha = 'center')

    try:
        plt.savefig(dest + '.tiff')
    except:
        plt.savefig(dest + '.png')

    return (all_tiles['1']['mean'], all_tiles['2']['mean'])
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),
        }
541951
def define_trajectory(self, trajectory_id, offset, n_pieces):
        
        self._send_packet(struct.pack('<BBBBIB',
                                      self.COMMAND_DEFINE_TRAJECTORY,
                                      trajectory_id,
                                      self.TRAJECTORY_LOCATION_MEM,
                                      self.TRAJECTORY_TYPE_POLY4D,
                                      offset,
                                      n_pieces))
947035
def _synDelayParams(self):
        '''
        
        '''
        delays = {}
        #mean delays
        loc = np.zeros((len(self.y), len(self.X)))
        loc[:, 0] = self.delays[0]
        loc[:, 1::2] = self.delays[0]
        loc[:, 2::2] = self.delays[1]
        #standard deviations
        scale = loc * self.delay_rel_sd
        
        #prepare output
        delay_loc = {}
        for i, y in enumerate(self.y):
            delay_loc.update({y : loc[i]})
        
        delay_scale = {}
        for i, y in enumerate(self.y):
            delay_scale.update({y : scale[i]})
                
        return delay_loc, delay_scale
722251
def getSomaPos(self):
        ''' '''
        n3dsoma = 0
        r3dsoma = np.zeros(3)
        for sec in [sec for secName, sec in self.secs.items() if 'soma' in secName]:
            sec['hObj'].push()
            n3d = int(h.n3d())  # get number of n3d points in each section
            r3d = np.zeros((3, n3d))  # to hold locations of 3D morphology for the current section
            n3dsoma += n3d

            for i in range(n3d):
                r3dsoma[0] += h.x3d(i)
                r3dsoma[1] += h.y3d(i)
                r3dsoma[2] += h.z3d(i)

            h.pop_section() 
        
        r3dsoma /= n3dsoma

        return r3dsoma
787680
def check_trajectory_id(self, dataset):
        '''
        
        '''
        results = []
        exists_ctx = TestCtx(BaseCheck.MEDIUM, 'Variable defining "trajectory_id" exists')
        trajectory_ids = dataset.get_variables_by_attributes(cf_role='trajectory_id')
        # No need to check
        exists_ctx.assert_true(trajectory_ids, 'variable defining cf_role="trajectory_id" exists')
        if not trajectory_ids:
            return exists_ctx.to_result()
        results.append(exists_ctx.to_result())
        test_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended attributes for the {} variable'.format(trajectory_ids[0].name))
        test_ctx.assert_true(
            getattr(trajectory_ids[0], 'long_name', '') != "",
            "long_name attribute should exist and not be empty"
        )
        results.append(test_ctx.to_result())
        return results
907196
def directed_graph(trajectories, k=5, verbose=False, pruning_thresh=0,
                   return_coords=False):
  '''
  '''
  X = np.vstack(trajectories)
  G = neighbor_graph(X, k=k)
  if pruning_thresh > 0:
    traj_len = map(len, trajectories)
    G = _prune_edges(G, X, traj_len, pruning_thresh, verbose=verbose)
  if return_coords:
    return G, X
  return G