code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
p = np.array(bitstring_prep_histograms, dtype=float).T p /= p.sum(axis=0)[np.newaxis, :] return p
def estimate_assignment_probs(bitstring_prep_histograms)
Compute the estimated assignment probability matrix for a sequence of single shot histograms obtained by running the programs generated by `basis_state_preps()`. bitstring_prep_histograms[i,j] = #number of measured outcomes j when running program i The assignment probability is obtained by transposing...
3.111325
3.731136
0.833881
im = ax.imshow(ptransfermatrix, interpolation="nearest", cmap=rigetti_3_color_cm, vmin=-1, vmax=1) dim = len(labels) plt.colorbar(im, ax=ax) ax.set_xticks(range(dim)) ax.set_xlabel("Input Pauli Operator", fontsize=20) ax.set_yticks(range(dim)) ax.set_ylabel("Output Pa...
def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title)
Visualize the Pauli Transfer Matrix of a process. :param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix :param ax: The matplotlib axes. :param labels: The labels for the operator basis states. :param title: The title for the plot :return: The modified axis object. :rtype: AxesSubplot
2.497169
2.552888
0.978174
rho_amps = rho.data.toarray().ravel() nqc = int(round(np.log2(rho.shape[0]))) if ax is None: fig = plt.figure(figsize=(10, 6)) ax = Axes3D(fig, azim=-35, elev=35) cmap = rigetti_4_color_cm norm = mpl.colors.Normalize(-np.pi, np.pi) colors = cmap(norm(np.angle(rho_amps))) ...
def state_histogram(rho, ax=None, title="", threshold=0.001)
Visualize a density matrix as a 3d bar plot with complex phase encoded as the bar color. This code is a modified version of `an equivalent function in qutip <http://qutip.org/docs/3.1.0/apidoc/functions.html#qutip.visualization.matrix_histogram_complex>`_ which is released under the (New) BSD license. ...
2.304015
2.244376
1.026573
ret = 0 for b in bitlist: ret = (ret << 1) | (int(b) & 1) return ret
def bitlist_to_int(bitlist)
Convert a binary bitstring into the corresponding unsigned integer. :param list bitlist: A list of ones of zeros. :return: The corresponding integer. :rtype: int
2.960408
3.19097
0.927745
num_qubits = len(qubits) dimension = 2 ** num_qubits hists = [] preps = basis_state_preps(*qubits) jobs = [] _log.info('Submitting jobs...') for jj, p in izip(TRANGE(dimension), preps): jobs.append(cxn.run_and_measure_async(p, qubits, nsamples)) _log.info('Waiting for resu...
def sample_assignment_probs(qubits, nsamples, cxn)
Sample the assignment probabilities of qubits using nsamples per measurement, and then compute the estimated assignment probability matrix. See the docstring for estimate_assignment_probs for more information. :param list qubits: Qubits to sample the assignment probabilities for. :param int nsamples: T...
4.485295
4.506832
0.995221
if shuffle: n_groups = len(programs) n_progs_per_group = len(programs[0]) permutations = np.outer(np.ones(n_groups, dtype=int), np.arange(n_progs_per_group, dtype=int)) inverse_permutations = np.zeros_like(permutations) for jj in range(n...
def run_in_parallel(programs, nsamples, cxn, shuffle=True)
Take sequences of Protoquil programs on disjoint qubits and execute a single sequence of programs that executes the input programs in parallel. Optionally randomize within each qubit-specific sequence. The programs are passed as a 2d array of Quil programs, where the (first) outer axis iterates over di...
2.404378
2.447537
0.982367
n_groups = len(programs) n_progs_per_group = len(programs[0]) for progs in programs[1:]: if not len(progs) == n_progs_per_group: raise ValueError("Non-rectangular grid of programs specified: {}".format(programs)) # identify qubit groups, ensure disjointedness qubit_groups ...
def _run_in_parallel(programs, nsamples, cxn)
See docs for ``run_in_parallel()``. :param Union[np.ndarray,List[List[Program]]] programs: A rectangular list of lists, or a 2d array of Quil Programs. The outer list iterates over disjoint qubit groups as targets, the inner list over programs to run on those qubits, e.g., tomographic sequences. ...
3.032603
2.888785
1.049785
if not isinstance(pauli_sums, PauliSum): raise TypeError("not a pauli sum. please give me one") new_term = sI(0) * 0.0 for term in pauli_sums: new_term += term_with_coeff(term, term.coefficient.real) return new_term
def remove_imaginary_terms(pauli_sums: PauliSum) -> PauliSum
Remove the imaginary component of each term in a Pauli sum. :param pauli_sums: The Pauli sum to process. :return: a purely Hermitian Pauli sum.
5.366851
5.645974
0.950563
meas_basis_change = Program() for index, gate in pauli_term: if gate == 'X': meas_basis_change.inst(RY(-np.pi / 2, index)) elif gate == 'Y': meas_basis_change.inst(RX(np.pi / 2, index)) elif gate == 'Z': pass else: raise ValueE...
def get_rotation_program(pauli_term: PauliTerm) -> Program
Generate a rotation program so that the pauli term is diagonal. :param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations. :return: The rotation program.
2.502192
2.548092
0.981987
rows, cols = m.shape assert rows == cols n = rows I = np.eye(n) Z = np.zeros((n, n)) controlled_m = np.bmat([[I, Z], [Z, m]]) return controlled_m
def controlled(m: np.ndarray) -> np.ndarray
Make a one-qubit-controlled version of a matrix. :param m: A matrix. :return: A controlled version of that matrix.
3.798263
3.416131
1.111861
assert isinstance(accuracy, int) rows, cols = U.shape m = int(log2(rows)) output_qubits = range(0, accuracy) U_qubits = range(accuracy, accuracy + m) p = Program() ro = p.declare('ro', 'BIT', len(output_qubits)) # Hadamard initialization for i in output_qubits: p.inst(H...
def phase_estimation(U: np.ndarray, accuracy: int, reg_offset: int = 0) -> Program
Generate a circuit for quantum phase estimation. :param U: A unitary matrix. :param accuracy: Number of bits of accuracy desired. :param reg_offset: Where to start writing measurements (default 0). :return: A Quil program to perform phase estimation.
3.911328
3.883209
1.007241
if isinstance(number, str): if number[0] == '-': n_sign = -1 else: n_sign = 1 elif isinstance(number, float): n_sign = np.sign(number) number = str(number) deci = 0 for ndx, val in enumerate(number.split('.')[-1]): deci += float(val) ...
def binary_float_to_decimal_float(number: Union[float, str]) -> float
Convert binary floating point to decimal floating point. :param number: Binary floating point. :return: Decimal floating point representation of binary floating point.
3.019392
3.129408
0.964845
try: measurements.sum(axis=0) except AttributeError: measurements = np.asarray(measurements) finally: stats = measurements.sum(axis=0) / len(measurements) stats_str = [str(int(i)) for i in np.round(stats[::-1][1:])] bf_str = '0.' + ''.join(stats_str) bf = float(bf_s...
def measurements_to_bf(measurements: np.ndarray) -> float
Convert measurements into gradient binary fraction. :param measurements: Output measurements of gradient program. :return: Binary fraction representation of gradient estimate.
3.965471
3.814071
1.039695
program = Program() uniform_superimposer = Program().inst([H(qubit) for qubit in qubits]) program += uniform_superimposer if decompose_diffusion: diffusion = decomposed_diffusion_program(qubits) else: diffusion = diffusion_program(qubits) # To avoid redefining gates, we col...
def amplification_circuit(algorithm: Program, oracle: Program, qubits: List[int], num_iter: int, decompose_diffusion: bool = False) -> Program
Returns a program that does ``num_iter`` rounds of amplification, given a measurement-less algorithm, an oracle, and a list of qubits to operate on. :param algorithm: A program representing a measurement-less algorithm run on qubits. :param oracle: An oracle maps any basis vector ``|psi>`` to either ``+|ps...
3.862964
3.960703
0.975323
program = Program() if len(qubits) == 1: program.inst(Z(qubits[0])) else: program.inst([X(q) for q in qubits]) program.inst(H(qubits[-1])) program.inst(RZ(-np.pi, qubits[0])) program += (ControlledProgramBuilder() .with_controls(qubi...
def decomposed_diffusion_program(qubits: List[int]) -> Program
Constructs the diffusion operator used in Grover's Algorithm, acted on both sides by an a Hadamard gate on each qubit. Note that this means that the matrix representation of this operator is diag(1, -1, ..., -1). In particular, this decomposes the diffusion operator, which is a :math:`2**{len(qubits)}\times...
2.461009
2.705452
0.909648
pterm = PauliTerm('I', 0, 1.0) for conj, index in zip(conjugate, indices): pterm = pterm * self._operator_generator(index, conj) pterm = pterm.simplify() return pterm
def product_ops(self, indices, conjugate)
Convert a list of site indices and coefficients to a Pauli Operators list with the Jordan-Wigner (JW) transformation :param List indices: list of ints specifying the site the fermionic operator acts on, e.g. [0,2,4,6] :param List conjugate: List of -1, 1 specifying ...
4.997725
5.206631
0.959877
pterm = PauliTerm('I', 0, 1.0) Zstring = PauliTerm('I', 0, 1.0) for j in range(index): Zstring = Zstring*PauliTerm('Z', j, 1.0) pterm1 = Zstring*PauliTerm('X', index, 0.5) scalar = 0.5 * conj * 1.0j pterm2 = Zstring*PauliTerm('Y', index, scalar) ...
def _operator_generator(index, conj)
Internal method to generate the appropriate operator
3.275784
3.23945
1.011216
n_bits = len(mask) form_string = "{0:0" + str(n_bits) + "b}" bit_map_dct = {} for idx in range(2**n_bits): bit_string = form_string.format(idx) bit_map_dct[bit_string] = utils.bitwise_xor(bit_string, mask) return bit_map_dct
def create_1to1_bitmap(mask: str) -> Dict[str, str]
Create a bit map function (as a dictionary) for a given mask. e.g., for a mask :math:`m = 10` the return is a dictionary: >>> create_1to1_bitmap('10') ... { ... '00': '10', ... '01': '11', ... '10': '00', ... '11': '01' ... } :param mask: A binary mask as a str...
2.728001
2.709969
1.006654
if not isinstance(graph, nx.Graph) and isinstance(graph, list): maxcut_graph = nx.Graph() for edge in graph: maxcut_graph.add_edge(*edge) graph = maxcut_graph.copy() cost_operators = [] driver_operators = [] for i, j in graph.edges(): cost_operators.appe...
def maxcut_qaoa(graph, steps=1, rand_seed=None, connection=None, samples=None, initial_beta=None, initial_gamma=None, minimizer_kwargs=None, vqe_option=None)
Max cut set up method :param graph: Graph definition. Either networkx or list of tuples :param steps: (Optional. Default=1) Trotterization order for the QAOA algorithm. :param rand_seed: (Optional. Default=None) random seed when beta and gamma angles are not provided. :param connection: (Option...
2.572996
2.284247
1.126409
for gates in cartesian_product(TOMOGRAPHY_GATES.keys(), repeat=len(qubits)): tomography_program = Program() for qubit, gate in izip(qubits, gates): tomography_program.inst(gate(qubit)) yield tomography_program
def default_rotations(*qubits)
Generates the Quil programs for the tomographic pre- and post-rotations of any number of qubits. :param list qubits: A list of qubits to perform tomography on.
3.441456
2.85165
1.20683
for gates in cartesian_product(TOMOGRAPHY_GATES.values(), repeat=nqubits): yield qt.tensor(*gates)
def default_channel_ops(nqubits)
Generate the tomographic pre- and post-rotations of any number of qubits as qutip operators. :param int nqubits: The number of qubits to perform tomography on. :return: Qutip object corresponding to the tomographic rotation. :rtype: Qobj
9.955977
7.792881
1.277573
if not cls._tested: cls._tested = True np.random.seed(SEED) test_problem_dimension = 10 mat = np.random.randn(test_problem_dimension, test_problem_dimension) posmat = mat.dot(mat.T) posvar = cvxpy.Variable(test_problem_dimension, t...
def is_functional(cls)
Checks lazily whether a convex solver is installed that handles positivity constraints. :return: True if a solver supporting positivity constraints is installed. :rtype: bool
4.265232
3.840594
1.110566
if not isinstance(ket_op, int): raise TypeError("ket_op needs to be an integer") if not isinstance(bra_op, int): raise TypeError("ket_op needs to be an integer") if ket_op not in [0, 1] or bra_op not in [0, 1]: raise ValueError("bra and ket op needs to be either 0 or 1") if...
def _single_projector_generator(ket_op, bra_op, index)
Generate the pauli sum terms corresponding to |ket_op><brak_op| :param ket_op: single qubit computational basis state :param bra_op: single qubit computational basis state :param index: qubit index to assign to the projector :return: pauli sum of single qubit projection operator :rtype: PauliSum
1.687763
1.701154
0.992129
projectors = [] for index, (ket_one_qubit, bra_one_qubit) in enumerate(zip(ket[::-1], bra[::-1])): projectors.append(_single_projector_generator(ket_one_qubit, bra_one_qubit, index)) return reduce(lambda x, y: x * y, projectors)
def projector_generator(ket, bra)
Generate a Pauli Sum that corresponds to the projection operator |ket><bra| note: ket and bra are numerically ordered such that ket = [msd, ..., lsd] where msd == most significant digit and lsd = least significant digit. :param List ket: string of zeros and ones corresponding to a computational ...
2.691397
2.84889
0.944718
num_qubits = len(prep_program.get_qubits()) normalizer_ops = projector_generator(reference_state, reference_state) c0_coeff, _, _ = estimate_locally_commuting_operator( prep_program, normalizer_ops, variance_bound=variance_bound, quantum_resource=quantum_resource) c0_coeff = np.sqrt...
def measure_wf_coefficients(prep_program, coeff_list, reference_state, quantum_resource, variance_bound=1.0E-6)
Measure a set of coefficients with a phase relative to the reference_state :param prep_program: pyQuil program to prepare the state :param coeff_list: list of integers labeling amplitudes to measure :param reference_state: Integer of the computational basis state to use as a ref...
2.810386
2.898232
0.96969
num_qubits = len(prep_program.get_qubits()) amplitudes_to_measure = list(range(2 ** num_qubits)) amplitudes = measure_wf_coefficients(prep_program, amplitudes_to_measure, reference_state, quantum_resource, ...
def measure_pure_state(prep_program, reference_state, quantum_resource, variance_bound=1.0E-6)
Measure the coefficients of the pure state :param prep_program: pyQuil program to prepare the state :param reference_state: Integer of the computational basis state to use as a reference :param quantum_resource: An instance of a quantum abstract machine :param variance_bound...
3.230632
3.394687
0.951673
if conj != -1 and conj != +1: raise ValueError("Improper conjugate coefficient") if index >= self.n_qubits or index < 0: raise IndexError("Operator index outside number of qubits for " "current Bravyi-Kitaev transform.") # parity set...
def _operator_generator(self, index, conj)
Internal method to generate the appropriate ladder operator at fermion orbital at 'index' If conj == -1 --> creation conj == +1 --> annihilation :param int index: fermion orbital to generate ladder operator at :param int conj: -1 for creation, +1 for annihilation
4.412524
4.334743
1.017944
self.defined_gates = set(STANDARD_GATE_NAMES) prog = self._recursive_builder(self.operation, self.gate_name, self.control_qubits, self.target_qubit) return prog
def build(self)
Builds this controlled gate. :return: The controlled gate, defined by this object. :rtype: Program
8.652682
7.95202
1.088111
new_program = pq.Program() new_program += program if gate_name not in self.defined_gates: new_program.defgate(gate_name, gate_matrix) self.defined_gates.add(gate_name) return new_program
def _defgate(self, program, gate_name, gate_matrix)
Defines a gate named gate_name with matrix gate_matrix in program. In addition, updates self.defined_gates to track what has been defined. :param Program program: Pyquil Program to add the defgate and gate to. :param str gate_name: The name of the gate to add to program. :param numpy.n...
2.29258
2.406461
0.952677
control_true = np.kron(ONE_PROJECTION, operation) control_false = np.kron(ZERO_PROJECTION, np.eye(2, 2)) control_root_true = np.kron(ONE_PROJECTION, sqrtm(operation, disp=True)) controlled_gate = control_true + control_false controlled_root_gate = control_root_true + con...
def _recursive_builder(self, operation, gate_name, control_qubits, target_qubit)
Helper function used to define the controlled gate recursively. It uses the algorithm in the reference above. Namely it recursively constructs a controlled gate by applying a controlled square root of the gate, followed by a toffoli gate with len(control_qubits) - 1 controls, applying the con...
3.213745
3.013792
1.066346
assert isinstance(state, int), \ f"{state} is not an integer. Must call parity_even_p with an integer state." mask = 0 for q in marked_qubits: mask |= 1 << q return bin(mask & state).count("1") % 2 == 0
def parity_even_p(state, marked_qubits)
Calculates the parity of elements at indexes in marked_qubits Parity is relative to the binary representation of the integer state. :param state: The wavefunction index that corresponds to this state. :param marked_qubits: The indexes to be considered in the parity sum. :returns: A boolean correspondi...
3.585081
3.63889
0.985213
program = Program() ro = program.declare('ro', 'BIT', max(marked_qubits) + 1) program += pyquil_program program += [MEASURE(qubit, r) for qubit, r in zip(list(range(max(marked_qubits) + 1)), ro)] program.wrap_in_numshots_loop(samples) executable = qc.compile(program) bitstring_samples =...
def expectation_from_sampling(pyquil_program: Program, marked_qubits: List[int], qc: QuantumComputer, samples: int) -> float
Calculation of Z_{i} at marked_qubits Given a wavefunctions, this calculates the expectation value of the Zi operator where i ranges over all the qubits given in marked_qubits. :param pyquil_program: pyQuil program generating some state :param marked_qubits: The qubits within the support of the Z paul...
2.979279
2.999828
0.99315
if isinstance(pauli_sum, np.ndarray): # debug mode by passing an array wf = WavefunctionSimulator().wavefunction(pyquil_prog) wf = np.reshape(wf.amplitudes, (-1, 1)) average_exp = np.conj(wf).T.dot(pauli_sum.dot(wf)).real return average_exp ...
def expectation(pyquil_prog: Program, pauli_sum: Union[PauliSum, PauliTerm, np.ndarray], samples: int, qc: QuantumComputer) -> float
Compute the expectation value of pauli_sum over the distribution generated from pyquil_prog. :param pyquil_prog: The state preparation Program to calculate the expectation value of. :param pauli_sum: PauliSum representing the operator of which to calculate the expectation value or a numpy m...
2.970314
2.96905
1.000426
if hasattr(self, 'get_path_from_parent'): return self.get_path_from_parent(parent) if self.model is parent: return [] model = self.concrete_model # Get a reversed base chain including both the current and parent # models. chain = model._meta.get_base_chain(parent) or [] ...
def _get_path_from_parent(self, parent)
Return a list of PathInfos containing the path from the parent model to the current model, or an empty list if parent is not a parent of the current model.
4.340638
3.749124
1.157774
return cls.maybe_optimize(info, cls._meta.model.objects, id)
def get_node(cls, info, id)
Bear in mind that if you are overriding this method get_node(info, pk), you should always call maybe_optimize(info, qs, pk) and never directly call get_optimized_node(info, qs, pk) as it would result to the node being attempted to be optimized when it is not supposed to actually get opti...
15.165039
7.298691
2.077775
'''Patience sort an iterable, xs. This function generates a series of pairs (x, pile), where "pile" is the 0-based index of the pile "x" should be placed on top of. Elements of "xs" must be less-than comparable. ''' pile_tops = list() for x in xs: pile = bisect.bisect_left(pile_tops...
def patience_sort(xs)
Patience sort an iterable, xs. This function generates a series of pairs (x, pile), where "pile" is the 0-based index of the pile "x" should be placed on top of. Elements of "xs" must be less-than comparable.
4.222832
1.765229
2.392229
'''Return the length of the longest monotonic subsequence of xs, second return value is the difference between increasing and decreasing lengths. >>> longest_monotonic_subseq_length((4, 5, 1, 2, 3)) (3, 1) >>> longest_monotonic_subseq_length((1, 2, 3, 5, 4)) (4, 2) >>> longest_monotonic_sub...
def longest_monotonic_subseq_length(xs)
Return the length of the longest monotonic subsequence of xs, second return value is the difference between increasing and decreasing lengths. >>> longest_monotonic_subseq_length((4, 5, 1, 2, 3)) (3, 1) >>> longest_monotonic_subseq_length((1, 2, 3, 5, 4)) (4, 2) >>> longest_monotonic_subseq_len...
2.460661
1.439353
1.709561
'''Return a longest increasing subsequence of xs. (Note that there may be more than one such subsequence.) >>> longest_increasing_subsequence(range(3)) [0, 1, 2] >>> longest_increasing_subsequence([3, 1, 2, 0]) [1, 2] ''' # Patience sort xs, stacking (x, prev_ix) pairs on the piles. ...
def longest_increasing_subsequence(xs)
Return a longest increasing subsequence of xs. (Note that there may be more than one such subsequence.) >>> longest_increasing_subsequence(range(3)) [0, 1, 2] >>> longest_increasing_subsequence([3, 1, 2, 0]) [1, 2]
3.775366
3.178162
1.187909
w, j = max(L.items()) while j != -1: yield j w, j = bestsofar[j]
def backtracking(a, L, bestsofar)
Start with the heaviest weight and emit index
8.294218
5.571355
1.488726
# Stores the smallest idx of last element of a subsequence of weight w L = {0: -1} bestsofar = [(0, -1)] * len(a) # (best weight, from_idx) for i, (key, weight) in enumerate(a): for w, j in L.items(): if j != -1 and a[j][0] >= key: continue new_wei...
def heaviest_increasing_subsequence(a, debug=False)
Returns the heaviest increasing subsequence for array a. Elements are (key, weight) pairs. >>> heaviest_increasing_subsequence([(3, 3), (2, 2), (1, 1), (0, 5)]) ([(0, 5)], 5)
4.83117
4.702701
1.027318
p = OptionParser(mappability.__doc__) p.add_option("--mer", default=50, type="int", help="User mer size") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) ref, = args K = opts.mer pf = ref.rsplit(".", 1)[0] mm = MakeManager()...
def mappability(args)
%prog mappability reference.fasta Generate 50mer mappability for reference genome. Commands are based on gem mapper. See instructions: <https://github.com/xuefzhao/Reference.Mappability>
3.2913
3.139376
1.048393
p = OptionParser(somatic.__doc__) opts, args = p.parse_args(args) if len(args) < 3: sys.exit(not p.print_help()) ref, bams = args[0], args[1:] tcmd = "~/export/speedseq/bin/speedseq somatic" tcmd += " -t 32 -F .2 -C 3 -q 30" cmds = [] for b in bams: pf = b.split("....
def somatic(args)
%prog somatic ref.fasta *.bam > somatic.sh Useful to identify somatic mutations in each sample compared to all other samples. Script using SPEEDSEQ-somatic will be written to stdout.
3.567096
3.079238
1.158435
p = OptionParser(rmdup.__doc__) p.add_option("-S", default=False, action="store_true", help="Treat PE reads as SE in rmdup") opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) bams = args cmd = "samtools rmdup" if opts.S: cm...
def rmdup(args)
%prog rmdup *.bam > rmdup.cmds Remove PCR duplicates from BAM files, generate a list of commands.
2.742859
2.510469
1.092568
p = OptionParser(mpileup.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) prefix, ref = args[0:2] bams = args[2:] cmd = "samtools mpileup -P ILLUMINA -E -ugD -r {0}" cmd += " -f {0} {1}".format(ref, " ".join(bams)) fmd = "bcftools vie...
def mpileup(args)
%prog mpileup prefix ref.fa *.bam Call SNPs using samtools mpileup.
4.275011
3.84585
1.111591
p = OptionParser(freebayes.__doc__) p.add_option("--mindepth", default=3, type="int", help="Minimum depth [default: %default]") p.add_option("--minqual", default=20, type="int", help="Minimum quality [default: %default]") opts, args = p.parse_args(args) if len...
def freebayes(args)
%prog freebayes prefix ref.fa *.bam Call SNPs using freebayes.
3.265408
3.050368
1.070496
p = OptionParser(freq.__doc__) p.add_option("--mindepth", default=3, type="int", help="Minimum depth [default: %default]") p.add_option("--minqual", default=20, type="int", help="Minimum quality [default: %default]") p.set_outfile() opts, args = p.parse_args(ar...
def freq(args)
%prog freq fastafile bamfile Call SNP frequencies and generate GFF file.
3.219139
3.016384
1.067218
p = OptionParser(frommaf.__doc__) p.add_option("--validate", help="Validate coordinates against FASTA [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) maf, = args snpfile = maf.rsplit(".", 1)[0] + ".vcf" fp ...
def frommaf(args)
%prog frommaf maffile Convert to four-column tabular format from MAF.
2.642374
2.680731
0.985692
if connector == 'Sybase': shost, suser, spass = None, None, None _ = lambda x: x.split("=")[-1].translate(None, "\"'").strip() sqshrc = op.expanduser(sqshrc) if op.exists(sqshrc): for row in open(sqshrc): row = row.strip() if not row.s...
def get_profile(sqshrc="~/.sqshrc", connector='Sybase', hostname=None, username=None, password=None)
get database, username, password from .sqshrc file e.g. \set username="user"
3.013036
3.00549
1.002511
p = OptionParser(libs.__doc__) p.set_db_opts(dbname="track", credentials=None) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) libfile, = args sqlcmd = "select library.lib_id, library.name, bac.gb# from library join bac on " + \ "libra...
def libs(args)
%prog libs libfile Get list of lib_ids to be run by pull(). The SQL commands: select library.lib_id, library.name from library join bac on library.bac_id=bac.id where bac.lib_name="Medicago"; select seq_name from sequence where seq_name like 'MBE%' and trash is null;
4.289815
3.318115
1.292847
p = OptionParser(pull.__doc__) p.set_db_opts(dbname="mtg2", credentials=None) p.add_option("--frag", default=False, action="store_true", help="The command to pull sequences from db [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print...
def pull(args)
%prog pull libfile Pull the sequences using the first column in the libfile.
3.750903
3.553818
1.055457
p = OptionParser(query.__doc__) p.set_db_opts() p.add_option("--dryrun", default=False, action="store_true", help="Don't commit to database. Just print queries [default: %default]") p.set_sep(help="Specify output field separator") p.set_verbose(help="Print out all the queries")...
def query(args)
%prog query "SELECT feat_name FROM asm_feature WHERE feat_type = \\"{0}\\" AND end5 <= \\"{1}\\" AND end3 >= \\"{2}\\"" ::: datafile1 .... Script takes the data from tab-delimited datafile(s) and replaces the placeholders in the query which is then executed. Depending upon the type of query, results are ei...
2.90603
2.871189
1.012135
if first_line is None: first_line = fp.readline() if not first_line: raise EOFError() match = _START.match(first_line) if not match: raise Exception('Bad start of message', first_line) type = match.group(1) message = Message(type) while True: row = f...
def read_record(fp, first_line=None)
Read a record from a file of AMOS messages On success returns a Message object On end of file raises EOFError
2.612393
2.511296
1.040257
p = OptionParser(filter.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) frgfile, idsfile = args assert frgfile.endswith(".frg") fp = open(idsfile) allowed = set(x.strip() for x in fp) logging.debug("A total of {0} allowed ids loade...
def filter(args)
%prog filter frgfile idsfile Removes the reads from frgfile that are indicated as duplicates in the clstrfile (generated by CD-HIT-454). `idsfile` includes a set of names to include in the filtered frgfile. See apps.cdhit.ids().
2.566199
2.357161
1.088682
p = OptionParser(frg.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) frgfile, = args fastafile = frgfile.rsplit(".", 1)[0] + ".fasta" fp = open(frgfile) fw = open(fastafile, "w") for rec in iter_records(fp): if rec.type != "FRG...
def frg(args)
%prog frg frgfile Extract FASTA sequences from frg reads.
2.435509
2.2723
1.071826
p = OptionParser(asm.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) asmfile, = args prefix = asmfile.rsplit(".", 1)[0] ctgfastafile = prefix + ".ctg.fasta" scffastafile = prefix + ".scf.fasta" fp = open(asmfile) ctgfw = open(ctgfas...
def asm(args)
%prog asm asmfile Extract FASTA sequences from asm reads.
2.786187
2.716962
1.025479
p = OptionParser(count.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) frgfile, = args fp = open(frgfile) counts = defaultdict(int) for rec in iter_records(fp): counts[rec.type] += 1 for type, cnt in sorted(counts.items()): ...
def count(args)
%prog count frgfile Count each type of messages
2.719016
2.32918
1.167371
from itertools import groupby from jcvi.formats.base import FileShredder p = OptionParser(mergeclean.__doc__) p.set_sep(sep="_", help="Separator to group per prefix") opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) files = sorted(args) sep =...
def mergeclean(args)
%prog mergeclean [*.bam|*.count] Clean redundant merged bam/count files. This usually happens after running formats.sam.merge() several times.
2.768024
2.743779
1.008836
p = OptionParser(prepare.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) counts, families = args countfiles = glob(op.join(counts, "*.count")) countsdb = defaultdict(list) for c in countfiles: rs = RiceSample(c) countsdb...
def prepare(args)
%prog prepare countfolder families Parse list of count files and group per family into families folder.
3.020622
2.835912
1.065132
print("Insert-size\tOverlap", file=sys.stderr) for i in range(0, 3 * readlen, step): p = gaussian_prob_le(i, i / 5, 2 * readlen) if p < cutoff or p > 1 - cutoff: continue print("{0}bp\t{1}%".format(i, int(round(100 * p))), file=sys.stderr)
def choose_insertsize(readlen=150, step=20, cutoff=.01)
Calculate ratio of overlap for a range of insert sizes. Idea borrowed from ALLPATHS code (`allpaths_cache/CacheToAllPathsInputs.pl`).
4.473078
4.631996
0.965691
from scipy import stats if not x or not y: return 0 corr, pvalue = stats.spearmanr(x, y) return corr
def spearmanr(x, y)
Michiel de Hoon's library (available in BioPython or standalone as PyCluster) returns Spearman rsb which does include a tie correction. >>> x = [5.05, 6.75, 3.21, 2.66] >>> y = [1.65, 26.5, -5.93, 7.96] >>> z = [1.65, 2.64, 2.64, 6.95] >>> round(spearmanr(x, y), 4) 0.4 >>> round(spearmanr(x...
3.050457
4.4314
0.688373
if len(a) < 3: return np.zeros(len(a), dtype=bool) A = np.array(a, dtype=float) lb, ub = outlier_cutoff(A, threshold=threshold) return np.logical_or(A > ub, A < lb)
def reject_outliers(a, threshold=3.5)
Iglewicz and Hoaglin's robust test for multiple outliers (two sided test). <http://www.itl.nist.gov/div898/handbook/eda/section3/eda35h.htm> See also: <http://contchart.com/outliers.aspx> >>> a = [0, 1, 2, 4, 12, 58, 188, 189] >>> list(reject_outliers(a)) [False, False, False, False, False, Tr...
3.251223
3.766159
0.863273
A = np.array(a, dtype=float) M = np.median(A) D = np.absolute(A - M) MAD = np.median(D) C = threshold / .67449 * MAD return M - C, M + C
def outlier_cutoff(a, threshold=3.5)
Iglewicz and Hoaglin's robust, returns the cutoff values - lower bound and upper bound.
3.519298
3.447173
1.020923
assert method in ("kosambi", "haldane") d = cM / 100. if method == "kosambi": e4d = exp(4 * d) return (e4d - 1) / (e4d + 1) / 2 elif method == "haldane": return (1 - exp(-2 * d)) / 2
def recomb_probability(cM, method="kosambi")
<http://statgen.ncsu.edu/qtlcart/manual/node46.html> >>> recomb_probability(1) 0.009998666879965463 >>> recomb_probability(100) 0.48201379003790845 >>> recomb_probability(10000) 0.5
3.517024
4.232502
0.830956
assert 0 <= p < .75 rD = 1 - 4. / 3 * p D = -.75 * log(rD) varD = p * (1 - p) / (rD ** 2 * L) return D, varD
def jukesCantorD(p, L=100)
>>> jukesCantorD(.1) (0.10732563273050497, 0.001198224852071006) >>> jukesCantorD(.7) (2.0310376508266565, 0.47249999999999864)
7.174315
8.883476
0.807602
ram = -109635 + 18977 * readsize + 86326 * genomesize + \ 233353 * numreads - 51092 * K print("ReadSize: {0}".format(readsize), file=sys.stderr) print("GenomeSize: {0}Mb".format(genomesize), file=sys.stderr) print("NumReads: {0}M".format(numreads), file=sys.stderr) print("K: {0}".fo...
def velvet(readsize, genomesize, numreads, K)
Calculate velvet memory requirement. <http://seqanswers.com/forums/showthread.php?t=2101> Ram required for velvetg = -109635 + 18977*ReadSize + 86326*GenomeSize + 233353*NumReads - 51092*K Read size is in bases. Genome size is in millions of bases (Mb) Number of reads is in millions K is t...
3.94279
2.40964
1.636257
genelist = ",".join(genelist) dataset = get_phytozome_dataset() filters = dict(gene_name_filter=genelist) attributes = "chr_name1,gene_chrom_start,gene_chrom_end,gene_name1".split(",") data = dataset.query(filters=filters, attributes=attributes) return data
def get_bed_from_phytozome(genelist)
>>> data = get_bed_from_phytozome(["AT5G54690", "AT1G01010"]) >>> print data.read() #doctest: +NORMALIZE_WHITESPACE Chr1 3631 5899 AT1G01010 Chr5 22219224 22221840 AT5G54690 <BLANKLINE>
5.013156
5.4758
0.915511
p = OptionParser(bed.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) idsfile, = args ids = set(x.strip() for x in open(idsfile)) data = get_bed_from_phytozome(list(ids)) pf = idsfile.rsplit(".", 1)[0] bedfile = pf + ".bed" fw =...
def bed(args)
%prog bed genes.ids Get gene bed from phytozome. `genes.ids` contains the list of gene you want to pull from Phytozome. Write output to .bed file.
2.912387
2.54689
1.143507
p = OptionParser(bed.__doc__) p.add_option("-o", dest="output", default="stdout", help="Output file name [default: %default]") p.add_option("--cutoff", dest="cutoff", default=10, type="int", help="Minimum read depth to report intervals [default: %default]") opts, args = p.pa...
def bed(args)
%prog bed binfile fastafile Write bed files where the bases have at least certain depth.
3.208673
3.068756
1.045594
p = OptionParser(merge.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) binfiles = args[:-1] mergedbin = args[-1] if op.exists(mergedbin): logging.error("`{0}` file exists. Remove before proceed."\ .format(mergedbin)) ...
def merge(args)
%prog merge *.bin merged.bin Merge several count arrays into one. Overflows will be capped at uint8_max (255).
3.159402
2.883598
1.095646
p = OptionParser(query.__doc__) opts, args = p.parse_args(args) if len(args) != 4: sys.exit(not p.print_help()) binfile, fastafile, ctgID, baseID = args b = BinFile(binfile, fastafile) ar = b.mmarray fastasize, sizes, offsets = get_offsets(fastafile) oi = offsets[ctgID] +...
def query(args)
%prog query binfile fastafile ctgID baseID Get the depth at a particular base.
4.700685
3.223071
1.458449
p = OptionParser(count.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) coveragefile, fastafile = args countsfile = coveragefile.split(".")[0] + ".bin" if op.exists(countsfile): logging.error("`{0}` file exists. Remove before procee...
def count(args)
%prog count t.coveragePerBase fastafile Serialize the genomeCoverage results. The coordinate system of the count array will be based on the fastafile.
3.426536
3.204495
1.069291
if not edges: return None G = edges_to_graph(edges) path = nx.topological_sort(G) return path
def edges_to_path(edges)
Connect edges and return a path.
4.260436
3.587854
1.187461
edges = populate_edge_weights(edges) incident, nodes = node_to_edge(edges, directed=False) if not directed: # Make graph symmetric dual_edges = edges[:] for a, b, w in edges: dual_edges.append((b, a, w)) edges = dual_edges DUMMY = "DUMMY" dummy_edges = edge...
def hamiltonian(edges, directed=False, constraint_generation=True)
Calculates shortest path that traverses each node exactly once. Convert Hamiltonian path problem to TSP by adding one dummy point that has a distance of zero to all your other points. Solve the TSP and get rid of the dummy point - what remains is the Hamiltonian Path. >>> g = [(1,2), (2,3), (3,4), (4,2...
4.215369
4.756359
0.88626
from gurobipy import Model, GRB, quicksum edges = populate_edge_weights(edges) incoming, outgoing, nodes = node_to_edge(edges) idx = dict((n, i) for i, n in enumerate(nodes)) nedges = len(edges) n = len(nodes) m = Model() def step(x): return "u_{0}".format(x) # Create variabl...
def tsp_gurobi(edges)
Modeled using GUROBI python example.
2.809856
2.80192
1.002833
edges = populate_edge_weights(edges) incoming, outgoing, nodes = node_to_edge(edges) nedges, nnodes = len(edges), len(nodes) L = LPInstance() L.add_objective(edges, objective=MINIMIZE) balance = [] # For each node, select exactly 1 incoming and 1 outgoing edge for v in nodes: ...
def tsp(edges, constraint_generation=False)
Calculates shortest cycle that traverses each node exactly once. Also known as the Traveling Salesman Problem (TSP).
4.147531
4.186896
0.990598
outgoing, incoming, nodes = node_to_edge(edges) nedges = len(edges) L = LPInstance() assert flavor in ("longest", "shortest") objective = MAXIMIZE if flavor == "longest" else MINIMIZE L.add_objective(edges, objective=objective) # Balancing constraint, incoming edges equal to outgoin...
def path(edges, source, sink, flavor="longest")
Calculates shortest/longest path from list of edges in a graph >>> g = [(1,2,1),(2,3,9),(2,4,3),(2,5,2),(3,6,8),(4,6,10),(4,7,4)] >>> g += [(6,8,7),(7,9,5),(8,9,6),(9,10,11)] >>> path(g, 1, 8, flavor="shortest") ([1, 2, 4, 6, 8], 21) >>> path(g, 1, 8, flavor="longest") ([1, 2, 3, 6, 8], 25)
4.017703
4.367337
0.919943
G = nx.DiGraph() edge_to_index = {} for i, (a, b, w) in enumerate(edges): G.add_edge(a, b) edge_to_index[a, b] = i nedges = len(edges) L = LPInstance() L.add_objective(edges, objective=MINIMIZE) constraints = [] ncycles = 0 for c in nx.simple_cycles(G): ...
def min_feedback_arc_set(edges, remove=False, maxcycles=20000)
A directed graph may contain directed cycles, when such cycles are undesirable, we wish to eliminate them and obtain a directed acyclic graph (DAG). A feedback arc set has the property that it has at least one edge of every cycle in the graph. A minimum feedback arc set is the set that minimizes the tot...
3.299301
3.370556
0.97886
max_sum, max_start_index, max_end_index = -Infinity, 0, 0 current_max_sum = 0 current_start_index = 0 for current_end_index, x in enumerate(a): current_max_sum += x if current_max_sum > max_sum: max_sum, max_start_index, max_end_index = current_max_sum, \ ...
def max_sum(a)
For an input array a, output the range that gives the largest sum >>> max_sum([4, 4, 9, -5, -6, -1, 5, -6, -8, 9]) (17, 0, 2) >>> max_sum([8, -10, 10, -9, -6, 9, -7, -4, -10, -8]) (10, 2, 2) >>> max_sum([10, 1, -10, -8, 6, 10, -10, 6, -3, 10]) (19, 4, 9)
1.79848
1.976982
0.90971
p = OptionParser(silicosoma.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) silicofile, = args fp = must_open(silicofile) fw = must_open(opts.outfile, "w") next(fp) positions = [int(x) for x in fp.next().split()]...
def silicosoma(args)
%prog silicosoma in.silico > out.soma Convert .silico to .soma file. Format of .silico A text file containing in-silico digested contigs. This file contains pairs of lines. The first line in each pair constains an identifier, this contig length in bp, and the number of restriction sites, separ...
3.224824
3.055316
1.05548
from itertools import groupby from jcvi.assembly.patch import merge_ranges p = OptionParser(condense.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args bed = Bed(bedfile, sorted=False) key = lambda x: (x.seqid, x.start...
def condense(args)
%prog condense OM.bed Merge split alignments in OM bed.
3.190137
2.995006
1.065152
p = OptionParser(chimera.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args bed = Bed(bedfile) selected = select_bed(bed) mapped = defaultdict(set) # scaffold => chr chimerabed = "chimera.bed" fw = open(chimerabed,...
def chimera(args)
%prog chimera bedfile Scan the bed file to break scaffolds that multi-maps.
2.761213
2.62126
1.053391
ranges = [Range(x.seqid, x.start, x.end, float(x.score), i) for i, x in enumerate(bed)] selected, score = range_chain(ranges) selected = [bed[x.id] for x in selected] return selected
def select_bed(bed)
Return non-overlapping set of ranges, choosing high scoring blocks over low scoring alignments when there are conflicts.
5.375878
4.776206
1.125554
from jcvi.formats.sizes import Sizes from jcvi.formats.agp import OO, build p = OptionParser(fasta.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) bedfile, scffasta, pmolfasta = args pf = bedfile.rsplit(".", 1)[0] bed = Bed(bedfile...
def fasta(args)
%prog fasta bedfile scf.fasta pseudomolecules.fasta Use OM bed to scaffold and create pseudomolecules. bedfile can be generated by running jcvi.assembly.opticalmap bed --blockonly
4.281721
3.902131
1.097278
from jcvi.formats.bed import sort p = OptionParser(bed.__doc__) p.add_option("--blockonly", default=False, action="store_true", help="Only print out large blocks, not fragments [default: %default]") p.add_option("--point", default=False, action="store_true", help=...
def bed(args)
%prog bed xmlfile Print summary of optical map alignment in BED format.
3.046853
2.752326
1.10701
from jcvi.formats.sizes import Sizes from jcvi.formats.sam import index p = OptionParser(bam.__doc__) p.set_home("eddyyeh") p.set_cpus() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) gsnapfile, fastafile = args EYHOME = opts.eddyyeh_h...
def bam(args)
%prog snp input.gsnap ref.fasta Convert GSNAP output to BAM.
4.102281
3.908465
1.049589
p = OptionParser(index.__doc__) p.add_option("--supercat", default=False, action="store_true", help="Concatenate reference to speed up alignment") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) dbfile, = args check_index(dbfile, su...
def index(args)
%prog index database.fasta ` Wrapper for `gmap_build`. Same interface.
3.437486
3.155945
1.08921
p = OptionParser(gmap.__doc__) p.add_option("--cross", default=False, action="store_true", help="Cross-species alignment") p.add_option("--npaths", default=0, type="int", help="Maximum number of paths to show." " If set to 0, prints two paths if chimer...
def gmap(args)
%prog gmap database.fasta fastafile Wrapper for `gmap`.
3.38347
3.189818
1.060709
from jcvi.formats.fastq import guessoffset p = OptionParser(align.__doc__) p.add_option("--rnaseq", default=False, action="store_true", help="Input is RNA-seq reads, turn splicing on") p.add_option("--native", default=False, action="store_true", help="Convert GSNA...
def align(args)
%prog align database.fasta read1.fq read2.fq Wrapper for `gsnap` single-end or paired-end, depending on the number of args.
3.593532
3.404952
1.055384
overlap_set = set() active = set() ends = [] for i, (chr, left, right) in enumerate(eclusters): ends.append((chr, left, 0, i)) # 0/1 for left/right-ness ends.append((chr, right, 1, i)) ends.sort() chr_last = "" for chr, pos, left_right, i in ends: if chr != ch...
def get_1D_overlap(eclusters, depth=1)
Find blocks that are 1D overlapping, returns cliques of block ids that are in conflict
3.081103
3.044353
1.012071
mergeables = Grouper() active = set() x_ends = [] for i, (range_x, range_y, score) in enumerate(eclusters): chr, left, right = range_x x_ends.append((chr, left, 0, i)) # 0/1 for left/right-ness x_ends.append((chr, right, 1, i)) x_ends.sort() chr_last = "" for ...
def get_2D_overlap(chain, eclusters)
Implements a sweep line algorithm, that has better running time than naive O(n^2): assume block has x_ends, and y_ends for the bounds 1. sort x_ends, and take a sweep line to scan the x_ends 2. if left end, test y-axis intersection of current block with `active` set; also put this block in the `acti...
4.074193
3.767814
1.081315
eclusters = [] for cluster in clusters: xlist, ylist, scores = zip(*cluster) score = _score(cluster) xchr, xmin = min(xlist) xchr, xmax = max(xlist) ychr, ymin = min(ylist) ychr, ymax = max(ylist) # allow fuzziness to the boundary xmax += ex...
def make_range(clusters, extend=0)
Convert to interval ends from a list of anchors extend modifies the xmax, ymax boundary of the box, which can be positive or negative very useful when we want to make the range as fuzzy as we specify
3.821817
3.736899
1.022724
qa, qb = quota eclusters = make_range(clusters, extend=-Nmax) # (1-based index, cluster score) nodes = [(i+1, c[-1]) for i, c in enumerate(eclusters)] eclusters_x, eclusters_y, scores = zip(*eclusters) # represents the contraints over x-axis and y-axis constraints_x = get_1D_overlap(e...
def get_constraints(clusters, quota=(1, 1), Nmax=0)
Check pairwise cluster comparison, if they overlap then mark edge as conflict
5.67973
5.588982
1.016237
lp_handle = cStringIO.StringIO() lp_handle.write("Maximize\n ") records = 0 for i, score in nodes: lp_handle.write("+ %d x%d " % (score, i)) # SCIP does not like really long string per row records += 1 if records % 10 == 0: lp_handle.write("\n") lp_h...
def format_lp(nodes, constraints_x, qa, constraints_y, qb)
Maximize 4 x1 + 2 x2 + 3 x3 + x4 Subject To x1 + x2 <= 1 End
2.539375
2.62387
0.967797
qb, qa = quota # flip it nodes, constraints_x, constraints_y = get_constraints( clusters, (qa, qb), Nmax=Nmax) if self_match: constraints_x = constraints_y = constraints_x | constraints_y lp_data = format_lp(nodes, constraints_x, qa, constraints_y, qb) if solver == "SCIP": ...
def solve_lp(clusters, quota, work_dir="work", Nmax=0, self_match=False, solver="SCIP", verbose=False)
Solve the formatted LP instance
2.875002
2.857194
1.006233
if not map_type and not number: print_all_maps() elif map_type: print_maps_by_type(map_type, number) else: s = ('Invalid parameter combination. ' 'number without map_type is not supported.') raise ValueError(s)
def print_maps(map_type=None, number=None)
Print maps by type and/or number of defined colors. Parameters ---------- map_type : {'Sequential', 'Diverging', 'Qualitative'}, optional Filter output by map type. By default all maps are printed. number : int, optional Filter output by number of defined colors. By default there is ...
4.074062
4.769933
0.854113
map_type = map_type.lower().capitalize() if map_type not in MAP_TYPES: s = 'Invalid map type, must be one of {0}'.format(MAP_TYPES) raise ValueError(s) print(map_type) map_keys = sorted(COLOR_MAPS[map_type].keys()) format_str = '{0:8} : {1}' for mk in map_keys: ...
def print_maps_by_type(map_type, number=None)
Print all available maps of a given type. Parameters ---------- map_type : {'Sequential', 'Diverging', 'Qualitative'} Select map type to print. number : int, optional Filter output by number of defined colors. By default there is no numeric filtering.
2.902419
3.095158
0.937729
number = str(number) map_type = map_type.lower().capitalize() # check for valid type if map_type not in MAP_TYPES: s = 'Invalid map type, must be one of {0}'.format(MAP_TYPES) raise ValueError(s) # make a dict of lower case map name to map name so this can be # insensitive...
def get_map(name, map_type, number, reverse=False)
Return a `BrewerMap` representation of the specified color map. Parameters ---------- name : str Name of color map. Use `print_maps` to see available color maps. map_type : {'Sequential', 'Diverging', 'Qualitative'} Select color map type. number : int Number of defined color...
2.622341
2.598634
1.009123
seq_maps = COLOR_MAPS[map_type] loaded_maps = {} for map_name in seq_maps: loaded_maps[map_name] = {} for num in seq_maps[map_name]: inum = int(num) colors = seq_maps[map_name][num]['Colors'] bmap = BrewerMap(map_name, map_type, colors) ...
def _load_maps_by_type(map_type)
Load all maps of a given type into a dictionary. Color maps are loaded as BrewerMap objects. Dictionary is keyed by map name and then integer numbers of defined colors. There is an additional 'max' key that points to the color map with the largest number of defined colors. Parameters ---------...
3.060318
2.74498
1.114878
hc = [] for color in self.colors: h = '#' + ''.join('{0:>02}'.format(hex(c)[2:].upper()) for c in color) hc.append(h) return hc
def hex_colors(self)
Colors as a tuple of hex strings. (e.g. '#A912F4')
4.544262
4.13151
1.099904
mc = [] for color in self.colors: mc.append(tuple([x / 255. for x in color])) return mc
def mpl_colors(self)
Colors expressed on the range 0-1 as used by matplotlib.
4.647808
4.435851
1.047783