Create frequency categories
321769
function determineFreqCategories() {
    if (mean - sd < 0) {
      var lowrange = 0 + mean / 3;
    } else {
      var lowrange = mean - sd;
    }
    var midrange = [mean + sd, lowrange];
    var highrange = mean + sd;

    var i = 0;
    for (; i < potentialexamples.length; i++) {
      var word = potentialexamples[i][0];

      if ('undefined' != typeof wordfreq[word.simplified]) {
        pushFrequency(word);
      }
    }

    function pushFrequency(word) {
      if (wordfreq[word.simplified] < lowrange) {
        lowfreq.push(word);
      }
      if (
        wordfreq[word.simplified] >= midrange[1] &&
        wordfreq[word.simplified] < midrange[0]
      ) {
        midfreq.push(word);
      }
      if (wordfreq[word.simplified] >= highrange) {
        highfreq.push(word);
      }
    }
  }
1305665
def timefreq(x,fs=200):
    
    from numpy import size, shape, arange, append
    
    maxfreq=float(fs)/2.0 # Maximum frequency
    minfreq=float(fs)/float(size(x,0)) # Minimum and delta frequency -- simply the inverse of the length of the recording in seconds
    F=arange(minfreq,maxfreq+minfreq,minfreq) # Create frequencies evenly spaced from 0:minfreq:maxfreq
    F=append(0,F) # Add zero-frequency component
    
    return F
1275239
private void addTermFrequencies(Map<String, Int> termFreqMap, TermFreqVector vector)
   {
      String[] terms = vector.getTerms();
      int[] freqs = vector.getTermFrequencies();
      for (int j = 0; j < terms.length; j++)
      {
         String term = terms[j];

         if (isNoiseWord(term))
         {
            continue;
         }
         // increment frequency
         Int cnt = termFreqMap.get(term);
         if (cnt == null)
         {
            cnt = new Int();
            termFreqMap.put(term, cnt);
            cnt.x = freqs[j];
         }
         else
         {
            cnt.x += freqs[j];
         }
      }
   }
461101
function () {
  var cats = getCategories();
  for (var i in cats) {
    log.debug('\n\nTEST CATEGORY: ' + cats[i]);
    testCategory(cats[i]);
  }
}
1129411
def f_rollup(items, times, freq):
    
    rollup = [np.sum(item for __, item in ts)
              for _, ts in groupby_freq(items, times, freq)]
    return np.array(rollup)
989923
def _make_tagdict(self, sentences):
        ''''''
        counts = defaultdict(lambda: defaultdict(int))
        for words, tags in sentences:
            for word, tag in zip(words, tags):
                counts[word][tag] += 1
                self.classes.add(tag)
        freq_thresh = 20
        ambiguity_thresh = 0.97
        for word, tag_freqs in counts.items():
            tag, mode = max(tag_freqs.items(), key=lambda item: item[1])
            n = sum(tag_freqs.values())
            # Don't add rare words to the tag dictionary
            # Only add quite unambiguous words
            if n >= freq_thresh and (float(mode) / n) >= ambiguity_thresh:
                self.tagdict[word] = tag
514570
def use_custom_term_frequencies(self, custom_term_frequencies):
		'''
		
		'''
		self.priors += custom_term_frequencies.reindex(self.priors.index).fillna(0)
		return self
817341
def ensure_frequencies(self, frequencies):
        """"""
        if not frequencies:
            return {}
        if not isinstance(frequencies, dict):
            raise ValueError("frequencies should be dict")
        frequencies = {
            host: Frequency.ensure_frequency(frequencies[host]) for host in frequencies
        }
        return frequencies
509832
def create_gp(self):
        """"""

        categories_order = [
            ("{U}", "#ee82ee", 'Unmapped correctly'),
            ("{u}", "#ff0000", 'Unmapped incorrectly'),
            ("{T}", "#00ff00", 'Thresholded correctly'),
            ("{t}", "#008800", 'Thresholded incorrectly'),
            ("{P}", "#ffff00", 'Multimapped'),
            ("{w}+{x}", "#7f7f7f", 'Mapped, should be unmapped'),
            ("{m}", "#000000", 'Mapped to wrong position'),
            ("{M}", "#0000ff", 'Mapped correctly'),
        ]

        plot_lines = [
            '"{roc_fn}" using (( ({x}) )):({y}) lt rgb "{color}" with filledcurve x1 title "{title}", \\'.format(
                roc_fn=self._roc_fn,
                x=rnftools.lavender._format_xxx(self.default_x_axis),
                y=rnftools.lavender._format_xxx(
                    '({sum})*100/{{all}}'.format(sum="+".join([c[0] for c in categories_order[i:]]))
                ),
                color=categories_order[i][1],
                title=categories_order[i][2],
            ) for i in range(len(categories_order))
        ]

        plot = os.linesep.join((["plot \\"] + plot_lines + [""]))

        with open(self._gp_fn, "w+") as gp:
            gp_content = """
					set title "{{/:Bold=16 {title}}}"
	
					set x2lab "{x_lab}"
					set log x
					set log x2
	
					set format x "10^{{%L}}"
					set format x2 "10^{{%L}}"
					set xran  [{xran}]
					set x2ran [{xran}]
					set x2tics
					unset xtics
	
					set ylab "Part of all reads (%)"
	
					set format y "%g %%"
					set yran [{yran}]
					set y2ran [{yran}]
	
					set pointsize 1.5
	
					set grid ytics lc rgb "#777777" lw 1 lt 0 front
					set grid x2tics lc rgb "#777777" lw 1 lt 0 front
	
					set datafile separator "\\t"
					set palette negative
	
					set termin svg size {svg_size} enhanced
					set out "{svg_fn}"
					set key spacing 0.8 opaque width -5
				""".format(
                svg_fn=self._svg_fn,
                xran="{:.10f}:{:.10f}".format(self.report.default_x_run[0], self.report.default_x_run[1]),
                yran="{:.10f}:{:.10f}".format(self.report.default_y_run[0], self.report.default_y_run[1]),
                svg_size="{},{}".format(self.report.default_svg_size_px[0], self.report.default_svg_size_px[1]),
                title=os.path.basename(self._bam_fn)[:-4],
                x_lab=self.default_x_label,
            )
            gp_content = textwrap.dedent(gp_content) + "\n" + plot
            # gp_lines=gp_content.split("\n")
            # gp_lines=[x.strip() for x in gp_lines]
            # gp_content=gp_lines.join("\n")
            gp.write(gp_content)
623001
def frequency(self):
        
        freqOptions = ("YEARLY", "MONTHLY", "WEEKLY", "DAILY")
        if self.rule._freq < len(freqOptions):
            return freqOptions[self.rule._freq]
        else:
            return "unsupported_frequency_{}".format(self.rule._freq)
319742
def use_general_term_frequencies(self):
		'''
		
		'''
		tdf = self._get_relevant_term_freq()
		bg_df = self.term_doc_mat.get_term_and_background_counts()[['background']]
		bg_df = pd.merge(tdf,
		                 bg_df,
		                 left_index=True,
		                 right_index=True,
		                 how='left').fillna(0.)
		self._store_priors_from_background_dataframe(bg_df)
		return self
936235
function createCategories() {
    $cnt = count( $this->categories );
    if( 0 >= $cnt )
      return;
    $output = null;
    foreach( $this->categories as $category ) {
      $attributes = $this->_createParams( $category['params'], array( 'LANGUAGE' ));
      if( is_array( $category['value'] )) {
        foreach( $category['value'] as $cix => $categoryPart )
          $category['value'][$cix] = $this->_strrep( $categoryPart );
        $content  = implode( ',', $category['value'] );
      }
      else
        $content  = $this->_strrep( $category['value'] );
      $output    .= $this->_createElement( 'CATEGORIES', $attributes, $content );
    }
    return $output;
  }
898762
def _GenerateStaticsTable(self, title='Current Statistics'):
        """"""
        if len(self.__categories.keys()) < 1:
            return ''
        d = self.__categories
        keys = sorted(d.keys())
        cats = ', '.join(['"%s"' % k for k in keys])
        vals = ', '.join(['%d' % d[k] for k in keys])

        return r'''

%s
%s

.. csv-table::
   :header: %s

   %s

''' % (title, '-'*len(title), cats, vals)
314752
def build_multi_mfd(mfd):
    
    node = Node("multiMFD", dict(kind=mfd.kind, size=mfd.size))
    for name in sorted(mfd.kwargs):
        values = mfd.kwargs[name]
        if name in ('magnitudes', 'occurRates'):
            if len(values[0]) > 1:  # tested in multipoint_test.py
                values = list(numpy.concatenate(values))
            else:
                values = sum(values, [])
        node.append(Node(name, text=values))
    if 'occurRates' in mfd.kwargs:
        lengths = [len(rates) for rates in mfd.kwargs['occurRates']]
        node.append(Node('lengths', text=lengths))
    return node
893184
def stem_frequencies(self):
        """"""
        stemfreq = self.array.sum(axis=1).astype(np.float)
        stemfreq /= stemfreq.sum()
        return stemfreq
412218
def makeFrequencyPanel(allFreqs, patientName):
    
    titles = sorted(
        iter(allFreqs.keys()),
        key=lambda title: (allFreqs[title]['bitScoreMax'], title))

    origMaxY = 0
    cols = 6
    rows = len(allFreqs)
    figure, ax = plt.subplots(rows, cols, squeeze=False)
    substitutions = ['C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G']
    colors = ['blue', 'black', 'red', 'yellow', 'green', 'orange']

    for i, title in enumerate(titles):
        for index in range(6):
            for subst in allFreqs[str(title)]:
                substitution = substitutions[index]
                print(i, index, title, 'substitution', substitutions[index])
                if substitution[0] == 'C':
                    pattern = 'cPattern'
                else:
                    pattern = 'tPattern'
                maxY = makeFrequencyGraph(allFreqs, title, substitution,
                                          pattern, color=colors[index],
                                          createFigure=False, showFigure=False,
                                          readsAx=ax[i][index])
                if maxY > origMaxY:
                    origMaxY = maxY

            # add title for individual plot.
            # if used for other viruses, this will have to be adapted.
            if index == 0:
                gi = title.split('|')[1]
                titles = title.split(' ')
                try:
                    typeIndex = titles.index('type')
                except ValueError:
                    typeNumber = 'gi: %s' % gi
                else:
                    typeNumber = titles[typeIndex + 1]

                ax[i][index].set_ylabel(('Type %s \n maxBitScore: %s' % (
                    typeNumber, allFreqs[title]['bitScoreMax'])), fontsize=10)
            # add xAxis tick labels
            if i == 0:
                ax[i][index].set_title(substitution, fontsize=13)
            if i == len(allFreqs) - 1 or i == (len(allFreqs) - 1) / 2:
                if index < 3:
                    pat = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG',
                           'CCT', 'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC',
                           'TCG', 'TCT']
                else:
                    pat = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG',
                           'CTT', 'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC',
                           'TTG', 'TTT']
                ax[i][index].set_xticklabels(pat, rotation=45, fontsize=8)

    # make Y-axis equal
    for i, title in enumerate(allFreqs):
        for index in range(6):
            a = ax[i][index]
            a.set_ylim([0, origMaxY])
    # add title of whole panel
    figure.suptitle('Mutation Signatures in %s' % patientName, fontsize=20)
    figure.set_size_inches(5 * cols, 3 * rows, forward=True)
    figure.show()

    return allFreqs
970984
def frequencies_for(words)
      word_frequencies = {}
      words.each { |word| word_frequencies[word] = words.count(word) }
      word_frequencies
    end