Add percent combined to general stats table
323422
def stats_table(self, data):
        """"""
        headers = OrderedDict()
        headers['combopairs'] = {
            'title': 'Combined pairs',
            'description': 'Num read pairs combined',
            'shared_key': 'read_count',
            'hidden': True,
            'scale': False
        }
        headers['perccombo'] = {
            'title': '% Combined',
            'description': '% read pairs combined',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'PiYG'
        }
        self.general_stats_addcols(data, headers)
464462
function(numSt, numCov, numBranch, numCovBr, moduleName) {

        var totalPercent = percentage(numCov, numSt);
        var statusClass = totalPercent < successRate ? "bl-error" : "bl-success";
        var rowTitle = ( moduleName ? "Total for module: " + moduleName : "Global total" );
        var totalsOutput = grandTotalTemplate.replace("{{rowTitle}}", rowTitle)
            .replace("{{percentage}}", totalPercent)
            .replace("{{numberCovered}}", numCov)
            .replace("{{totalSmts}}", numSt)
            .replace("{{passedBranches}}", numCovBr)
            .replace("{{totalBranches}}", numBranch)
            .replace("{{statusclass}}", statusClass);

        bodyContent += totalsOutput;
    }
740217
function generateTableDataInsideScores(table){
	// Save to allow in function referencte
	table = table || this;
	var columns = table.columns*1;

	/*
		Create data table
	*/
	var scores = table.scores;

	// Just warn (DEBUG mode...)
	if(!scores)
		console.log('Table is empty!');

	// Get evaluation method ('min', 'max', custom...)
	var evalMethod = getMethodFor(table.evaluateMethod);

	// List of all the keys to sort
	var keysToSort = ['final'];

	// Go through all scores, creating a unique row
	_(scores).forEach(function(score){
		/*
			Notice score structure:

			{
				tableId: [this table id]
				teamId: xxx,
				scores: {
					  0: {value: xxx, data: {}},
					'1': {value: xxx, data: {}},
					  2: {value: xxx, data: {}}
					  [...],
				}
			}
		*/

		// This will be the object inserted in the table's data array
		// var scoreData = {};

		// Add simple attributes
		// scoreData['id'] = score.id || null;
		// scoreData['teamId'] = score.teamId || null;
		// scoreData['tableId'] = score.tableId || null;
		// scoreData['team'] = score.teamId || null;
		// scoreData.team: score.team.name
		// scoreData.country: score.team.country

		// Add scores data
		var scoreValues = [];
		for(var i = 0; i < columns; i++){

			// Get value and add to scoreValues
			var value = null;
			if(score.scores[i])
				value = score.scores[i].value;

			scoreValues.push(value);

			// Generate field key and saves
			// var field = 'score.'+(i+1);
			// score[field] = score.scores.value || null;
		}

		// Compute final score and adds to scoreData
		var finalScores = '?';

		// If evalMethod is set, let's compute the score. 
		if(evalMethod) {
			finalScores = evalMethod(scoreValues) || 0;
		}

		var showScore = finalScores;

		if(_.isArray(finalScores)){
			showScore = finalScores[0];

			for(var i = 1; i < finalScores.length; i++){
				var fieldKey = 'final'+(i+1); // Like: final2, final3, ...
				score[fieldKey] = finalScores[i];

				if(keysToSort.length <= i)
					keysToSort.push(fieldKey);
			}
		}

		score['final'] = showScore;

		// Add to table data
		// tableRows.push(score)
	});

	// Sort by 'final' field and reverse if needed
	var finalData = _.sortBy(scores, keysToSort);

	if(table.sort == 'desc')
		finalData = finalData.reverse();

	// Rank Table
	var pos = 0;
	var lastRow = null;

	_.forEach(finalData, function(row){
		pos++;

		var sameRanking = (lastRow ? true : false);
		for(var k in keysToSort){
			var key = keysToSort[k];
			if(lastRow && lastRow[key] != row[key]){
				sameRanking = false;
				break;
			}
		}

		if(sameRanking){
			// Keeps the same ranking if scores are the same
			return row.rank = lastRow.rank;
		}else{
			// Set rank as current position
			row.rank = pos;

		}
		// Save current row as last one
		lastRow = row;
	});

	// Self assign the table
	this.scores = finalData;

	// Return the table
	return this.scores;
}
321651
def methylqa_general_stats_table(self):
        

        headers = OrderedDict()
        headers['coverage'] = {
            'title': 'Fold Coverage',
            'min': 0,
            'suffix': 'X',
            'scale': 'YlGn'
        }
        self.general_stats_addcols(self.methylqa_data, headers)
794645
def add_stats(self, args):
        """"""
        bg_name, stats = args
        logger.debug("Stats: %s %s", bg_name, stats)
        
        for motif_id in stats.keys():
            if motif_id not in self.stats:
                self.stats[motif_id] = {}
        
            self.stats[motif_id][bg_name] = stats[motif_id]
402391
def add_stats_plot(self):
        """"""

        keys = OrderedDict()
        keys['species_a'] = {'color': '#437bb1', 'name': 'Species a'}
        keys['species_b'] = {'color': '#b1084c', 'name': 'Species b'}
        keys['ambiguous'] = {'color': '#333333', 'name': 'Ambiguous'}

        plot_config = {
            'id': "disambiguated_alignments",
            'title': "Disambiguate: Alignment Counts",
            'cpswitch_counts_label': "# Reads",
            'ylab': "# Reads"
        }

        self.add_section(
            plot=bargraph.plot(self.data, keys, plot_config)
        )
285845
function combine(statsObjects) {
  let result = create();
  L.each(statsObjects, function(stats) {
    L.each(stats._latencies, function(latency) {
      result._latencies.push(latency);
    });
    result._generatedScenarios += stats._generatedScenarios;
    L.each(stats._scenarioCounter, function(count, name) {
      if(result._scenarioCounter[name]) {
        result._scenarioCounter[name] += count;
      } else {
        result._scenarioCounter[name] = count;
      }
    });
    result._completedScenarios += stats._completedScenarios;
    result._scenariosAvoided += stats._scenariosAvoided;
    L.each(stats._codes, function(count, code) {
      if(result._codes[code]) {
        result._codes[code] += count;
      } else {
        result._codes[code] = count;
      }
    });
    L.each(stats._errors, function(count, error) {
      if(result._errors[error]) {
        result._errors[error] += count;
      } else {
        result._errors[error] = count;
      }
    });
    L.each(stats._requestTimestamps, function(timestamp) {
      result._requestTimestamps.push(timestamp);
    });
    result._completedRequests += stats._completedRequests;
    L.each(stats._scenarioLatencies, function(latency) {
      result._scenarioLatencies.push(latency);
    });
    result._matches += stats._matches;

    L.each(stats._counters, function(value, name) {
      if (!result._counters[name]) {
        result._counters[name] = 0;
      }
      result._counters[name] += value;
    });
    L.each(stats._customStats, function(values, name) {
      if (!result._customStats[name]) {
        result._customStats[name] = [];
      }

      L.each(values, function(v) {
        result._customStats[name].push(v);
      });
    });

    result._concurrency += stats._concurrency || 0;
    result._pendingRequests += stats._pendingRequests;
  });

  return result;
}
77183
def run_stats_df(self):
        """"""

        run_stats_df = []
        for x in self.run_stats:
            search_results = {**x["search_params"]}
            search_results["score"] = x["score"]
            run_stats_df.append(search_results)
        return pd.DataFrame(run_stats_df)
36417
def fastp_general_stats_table(self):
        

        headers = OrderedDict()
        headers['pct_duplication'] = {
            'title': '% Duplication',
            'description': 'Duplication rate in filtered reads',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'RdYlGn-rev'
        }
        headers['after_filtering_q30_rate'] = {
            'title': '% > Q30',
            'description': 'Percentage of reads > Q30 after filtering',
            'min': 0,
            'max': 100,
            'modify': lambda x: x * 100.0,
            'scale': 'GnBu',
            'suffix': '%',
            'hidden': True
        }
        headers['after_filtering_q30_bases'] = {
            'title': '{} Q30 bases'.format(config.base_count_prefix),
            'description': 'Bases > Q30 after filtering ({})'.format(config.base_count_desc),
            'min': 0,
            'modify': lambda x: x * config.base_count_multiplier,
            'scale': 'GnBu',
            'shared_key': 'base_count',
            'hidden': True
        }
        headers['after_filtering_gc_content'] = {
            'title': 'GC content',
            'description': 'GC content after filtering',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'Blues',
            'modify': lambda x: x * 100.0
        }
        headers['pct_surviving'] = {
            'title': '% PF',
            'description': 'Percent reads passing filter',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'BuGn',
        }
        headers['pct_adapter'] = {
            'title': '% Adapter',
            'description': 'Percentage adapter-trimmed reads',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'RdYlGn-rev',
        }

        self.general_stats_addcols(self.fastp_data, headers)
93901
def _merge_results(self, results):
        """"""
        self.results['tests'] += results['tests']

        for key, value in results['summary'].items():
            self.results['summary'][key] += value
957139
def afterqc_general_stats_table(self):
        

        headers = OrderedDict()
        headers['pct_good_bases'] = {
            'title': '% Good Bases',
            'description': 'Percent Good Bases',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'BuGn',
        }
        headers['good_reads'] = {
            'title': '{} Good Reads'.format(config.read_count_prefix),
            'description': 'Good Reads ({})'.format(config.read_count_desc),
            'min': 0,
            'modify': lambda x: x * config.read_count_multiplier,
            'scale': 'GnBu',
            'shared_key': 'read_count'
        }
        headers['total_reads'] = {
            'title': '{} Total Reads'.format(config.read_count_prefix),
            'description': 'Total Reads ({})'.format(config.read_count_desc),
            'min': 0,
            'modify': lambda x: x * config.read_count_multiplier,
            'scale': 'Blues',
            'shared_key': 'read_count'
        }
        headers['readlen'] = {
            'title': 'Read Length',
            'description': 'Read Length',
            'min': 0,
            'suffix': ' bp',
            'format': '{:,.0f}',
            'scale': 'YlGn'
        }
        self.general_stats_addcols(self.afterqc_data, headers)
1088665
def tophat_general_stats_table(self):
        

        headers = OrderedDict()
        headers['overall_aligned_percent'] = {
            'title': '% Aligned',
            'description': 'overall read mapping rate',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'YlGn'
        }
        headers['aligned_not_multimapped_discordant'] = {
            'title': '{} Aligned'.format(config.read_count_prefix),
            'description': 'Aligned reads, not multimapped or discordant ({})'.format(config.read_count_desc),
            'min': 0,
            'scale': 'PuRd',
            'modify': lambda x: x * config.read_count_multiplier,
            'shared_key': 'read_count'
        }
        self.general_stats_addcols(self.tophat_data, headers)
1133672
def table_qALL(self):
        

        self.add_section (
            name = 'Stats: All reads',
            anchor = 'minionqc-stats-qAll',
            description = 'MinIONQC statistics for all reads',
            plot = table.plot(
                self.minionqc_data,
                self.headers_to_use(),
                {
                    'namespace': 'MinIONQC',
                    'id': 'minionqc-stats-qAll-table',
                    'table_title': 'MinIONQC Stats: All reads'
                }
            )
        )
501533
def ratio_and_percentage(current, total, time_remaining):
    """"""
    return "{} / {} ({}% completed)".format(current, total, int(current / total * 100))
1051108
def addTable(D):
    

    _swap = {
        "1": "measurement",
        "2": "summary",
        "3": "ensemble",
        "4": "distribution"
    }


    print("What type of table would you like to add?\n"
          "1: measurement\n"
          "2: summary\n"
          "3: ensemble (under development)\n"
          "4: distribution (under development)\n"
          "\n Note: if you want to add a whole model, use the addModel() function")
    _ans = input(">")

    if _ans in ["3", "4"]:
        print("I don't know how to do that yet.")
    # if this is a summary or measurement, split the csv into each column
    elif _ans in ["1", "2"]:
        # read in a csv file. have the user point to it
        print("Locate the CSV file with the values for this table: ")
        _path, _files = browse_dialog_file()

        _path = _confirm_file_path(_files)
        _values = read_csv_from_file(_path)
        _table = _build_table(_values)
        _placement = _prompt_placement(D, _swap[_ans])
        D = _put_table(D, _placement, _table)

    else:
        print("That's not a valid option")

    return D
700363
def stats_enabled(self, value):
        """"""
        if value:
            self.statistics.enable()
        else:
            self.statistics.disable()
441427
function buildTableColumns(item, tableStructuresAndCombinations) {
  if (!defined(tableStructuresAndCombinations)) {
    // Invalid selection, eg. missing a selected code for a concept.
    return []; // Remove current columns.
  }
  var tableStructures = tableStructuresAndCombinations.tableStructures;
  var activeCombinations = tableStructuresAndCombinations.activeCombinations;
  if (tableStructures.length <= 1) {
    throwLoadError(item, "GetGenericData");
  }
  // The last element of the tableStructures is the total population.
  var totalPopulationTableStructure = tableStructures.pop();

  var firstTableStructure = tableStructures[0];
  var timeColumn = firstTableStructure.columns[0];
  var regionColumn = firstTableStructure.columns[2];
  var isTimeVarying =
    defined(timeColumn) && timeColumn.minimumValue !== timeColumn.maximumValue;
  // If there is time variation, for now, let's turn off the displayPercent option.
  // (since we don't have time-varying population data yet)
  if (isTimeVarying) {
    item.canDisplayPercent = false;
    item.displayPercent = false;
  } else {
    item.canDisplayPercent = true; // Assume we can unless proven otherwise.
  }

  var newColumns = buildValueColumns(item, tableStructures, activeCombinations);
  var totalSelectedColumn = new TableColumn(
    "Total selected",
    TableColumn.sumValues(newColumns),
    {
      active: !item.displayPercent
    }
  );
  // If there's more than one combination selected, add the total selected.
  if (newColumns.length > 1) {
    newColumns.push(totalSelectedColumn);
  } else if (!item.displayPercent) {
    // If there's only one value column, activate it.
    newColumns[0].isActive = true;
  }

  // Only add the total population columns if there is no time variation
  // (for now, since we don't have time-varying population data)
  if (!isTimeVarying) {
    var totalPopColumns = totalPopulationTableStructure.columns;
    // Check that the regions correspond in the two tables.  Assume total popn table has regions as first column.
    if (
      !arraysAreEqual(
        totalPopColumns[0].values.slice(0, regionColumn.values.length),
        regionColumn.values
      )
    ) {
      console.error(
        "Region ordering is different between total population data file and ABS data set."
      );
      // Activate the last value column, turn off percentDisplay and don't add the total population columns.
      item.canDisplayPercent = false;
      item.displayPercent = false;
      newColumns[newColumns.length - 1].isActive = true;
    } else {
      var totalPopColumn = new TableColumn(
        "Total population",
        totalPopColumns[totalPopColumns.length - 1].values.slice(
          0,
          regionColumn.values.length
        )
      );
      newColumns.push(totalPopColumn);
      var percentValues = TableColumn.divideValues(
        totalSelectedColumn,
        totalPopColumn,
        0
      ).map(function(fraction) {
        return fraction < 0.01
          ? Math.round(fraction * 1000) / 10
          : Math.round(fraction * 10000) / 100;
      });
      newColumns.push(
        new TableColumn("Total selected percent", percentValues, {
          active: item.displayPercent
        })
      );
    }
  }
  // Rename the region column to conform to csv-geo-au.
  // Since only one regiontype code can be selected, all combinations have the same regiontype.
  // (Don't use getActiveRegionTypeCode() because the UI might no longer reflect which regiontype was loaded.)
  // Just use the first time from the time column; we assume these are all the same (eg. 2011).
  var loadedRegionCode = activeCombinations[0].filter(function(absCode) {
    return absCode.concept.id === item.regionTypeConcept;
  })[0];
  var regionColumnName = regionTypeToCsvGeo(loadedRegionCode.code, timeColumn);

  // Make sure the Time and REGION columns match across columns (apart from the totalPopulationTableStructure).
  // Don't worry about Description - it is a description of the region, which we get from the region mapping anyway.
  if (!isTimeVarying) {
    timeColumn.options.type = VarType.SCALAR; // Otherwise we can get a spurious clock.
  }
  timeColumn = new TableColumn("Year", timeColumn.values, timeColumn.options);
  regionColumn = new TableColumn(
    regionColumnName,
    regionColumn.values,
    regionColumn.options
  );
  tableStructures.slice(1).forEach(function(tableStructure) {
    if (
      !arraysAreEqual(tableStructure.columns[0], timeColumn) ||
      !arraysAreEqual(tableStructure.columns[2], regionColumn)
    ) {
      throwDataMergeError(item);
    }
  });

  // Put these columns to the front of the value columns.
  newColumns.unshift(timeColumn);
  newColumns.unshift(regionColumn);

  return newColumns;
}