idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
11,500
def get_rotation_parameters ( phases , magnitudes ) : z_thetas = [ ] y_thetas = [ ] new_phases = [ ] new_magnitudes = [ ] for i in range ( 0 , len ( phases ) , 2 ) : phi = phases [ i ] psi = phases [ i + 1 ] z_thetas . append ( phi - psi ) kappa = ( phi + psi ) / 2. new_phases . append ( kappa ) a = magnitudes [ i ] b ...
Simulates one step of rotations .
11,501
def get_reversed_unification_program ( angles , control_indices , target , controls , mode ) : if mode == 'phase' : gate = RZ elif mode == 'magnitude' : gate = RY else : raise ValueError ( "mode must be \'phase\' or \'magnitude\'" ) reversed_gates = [ ] for j in range ( len ( angles ) ) : if angles [ j ] != 0 : reverse...
Gets the Program representing the reversed circuit for the decomposition of the uniformly controlled rotations in a unification step .
11,502
def get_ancestors ( self ) : node = self ancestor_list = [ ] while node . parent is not None : ancestor_list . append ( node . parent ) node = node . parent return ancestor_list
Returns a list of ancestors of the node . Ordered from the earliest .
11,503
def bitwise_dot_product ( bs0 : str , bs1 : str ) -> str : if len ( bs0 ) != len ( bs1 ) : raise ValueError ( "Bit strings are not of equal length" ) return str ( sum ( [ int ( bs0 [ i ] ) * int ( bs1 [ i ] ) for i in range ( len ( bs0 ) ) ] ) % 2 )
A helper to calculate the bitwise dot - product between two string representing bit - vectors
11,504
def notebook_mode ( m ) : global NOTEBOOK_MODE global TRANGE NOTEBOOK_MODE = m if NOTEBOOK_MODE : TRANGE = tqdm . tnrange else : TRANGE = tqdm . trange
Configure whether this module should assume that it is being run from a jupyter notebook . This sets some global variables related to how progress for long measurement sequences is indicated .
11,505
def sample_outcomes ( probs , n ) : dist = np . cumsum ( probs ) rs = np . random . rand ( n ) return np . array ( [ ( np . where ( r < dist ) [ 0 ] [ 0 ] ) for r in rs ] )
For a discrete probability distribution probs with outcomes 0 1 ... k - 1 draw n random samples .
11,506
def sample_bad_readout ( program , num_samples , assignment_probs , cxn ) : wf = cxn . wavefunction ( program ) return sample_outcomes ( assignment_probs . dot ( abs ( wf . amplitudes . ravel ( ) ) ** 2 ) , num_samples )
Generate n samples of measuring all outcomes of a Quil program assuming the assignment probabilities assignment_probs by simulating the wave function on a qvm QVMConnection cxn
11,507
def plot_pauli_transfer_matrix ( ptransfermatrix , ax , labels , title ) : 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" ...
Visualize the Pauli Transfer Matrix of a process .
11,508
def state_histogram ( rho , ax = None , title = "" , threshold = 0.001 ) : 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 = mp...
Visualize a density matrix as a 3d bar plot with complex phase encoded as the bar color .
11,509
def bitlist_to_int ( bitlist ) : ret = 0 for b in bitlist : ret = ( ret << 1 ) | ( int ( b ) & 1 ) return ret
Convert a binary bitstring into the corresponding unsigned integer .
11,510
def sample_assignment_probs ( qubits , nsamples , cxn ) : 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 , qub...
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 .
11,511
def run_in_parallel ( programs , nsamples , cxn , shuffle = True ) : 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 ( permutati...
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 .
11,512
def remove_imaginary_terms ( pauli_sums : PauliSum ) -> PauliSum : 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
Remove the imaginary component of each term in a Pauli sum .
11,513
def get_rotation_program ( pauli_term : PauliTerm ) -> Program : 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 Val...
Generate a rotation program so that the pauli term is diagonal .
11,514
def controlled ( m : np . ndarray ) -> np . ndarray : 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
Make a one - qubit - controlled version of a matrix .
11,515
def phase_estimation ( U : np . ndarray , accuracy : int , reg_offset : int = 0 ) -> Program : 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 ...
Generate a circuit for quantum phase estimation .
11,516
def binary_float_to_decimal_float ( number : Union [ float , str ] ) -> float : 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 ( '.' )...
Convert binary floating point to decimal floating point .
11,517
def measurements_to_bf ( measurements : np . ndarray ) -> float : 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 ] [ ...
Convert measurements into gradient binary fraction .
11,518
def amplification_circuit ( algorithm : Program , oracle : Program , qubits : List [ int ] , num_iter : int , decompose_diffusion : bool = False ) -> Program : program = Program ( ) uniform_superimposer = Program ( ) . inst ( [ H ( qubit ) for qubit in qubits ] ) program += uniform_superimposer if decompose_diffusion :...
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 .
11,519
def _operator_generator ( index , conj ) : 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 , scala...
Internal method to generate the appropriate operator
11,520
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 ) : if not isinstance ( graph , nx . Graph ) and isinstance ( graph , list ) : maxcut_graph = nx . Graph ( ) for edge in graph : maxcut_g...
Max cut set up method
11,521
def default_rotations ( * qubits ) : 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
Generates the Quil programs for the tomographic pre - and post - rotations of any number of qubits .
11,522
def default_channel_ops ( nqubits ) : for gates in cartesian_product ( TOMOGRAPHY_GATES . values ( ) , repeat = nqubits ) : yield qt . tensor ( * gates )
Generate the tomographic pre - and post - rotations of any number of qubits as qutip operators .
11,523
def is_functional ( cls ) : 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 , test_problem_dimension ) prob ...
Checks lazily whether a convex solver is installed that handles positivity constraints .
11,524
def measure_wf_coefficients ( prep_program , coeff_list , reference_state , quantum_resource , variance_bound = 1.0E-6 ) : num_qubits = len ( prep_program . get_qubits ( ) ) normalizer_ops = projector_generator ( reference_state , reference_state ) c0_coeff , _ , _ = estimate_locally_commuting_operator ( prep_program ,...
Measure a set of coefficients with a phase relative to the reference_state
11,525
def measure_pure_state ( prep_program , reference_state , quantum_resource , variance_bound = 1.0E-6 ) : 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_r...
Measure the coefficients of the pure state
11,526
def build ( self ) : self . defined_gates = set ( STANDARD_GATE_NAMES ) prog = self . _recursive_builder ( self . operation , self . gate_name , self . control_qubits , self . target_qubit ) return prog
Builds this controlled gate .
11,527
def _defgate ( self , program , gate_name , gate_matrix ) : 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
Defines a gate named gate_name with matrix gate_matrix in program . In addition updates self . defined_gates to track what has been defined .
11,528
def parity_even_p ( state , marked_qubits ) : 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
Calculates the parity of elements at indexes in marked_qubits
11,529
def vqe_run ( self , variational_state_evolve , hamiltonian , initial_params , gate_noise = None , measurement_noise = None , jacobian = None , qc = None , disp = None , samples = None , return_all = False ) : self . _disp_fun = disp if disp is not None else lambda x : None iteration_params = [ ] expectation_vals = [ ]...
functional minimization loop .
11,530
def _get_path_from_parent ( self , parent ) : if hasattr ( self , 'get_path_from_parent' ) : return self . get_path_from_parent ( parent ) if self . model is parent : return [ ] model = self . concrete_model chain = model . _meta . get_base_chain ( parent ) or [ ] chain . reverse ( ) chain . append ( model ) path = [ ]...
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 .
11,531
def patience_sort ( xs ) : pile_tops = list ( ) for x in xs : pile = bisect . bisect_left ( pile_tops , x ) if pile == len ( pile_tops ) : pile_tops . append ( x ) else : pile_tops [ pile ] = x yield x , pile
Patience sort an iterable xs .
11,532
def longest_monotonic_subseq_length ( xs ) : li = longest_increasing_subseq_length ( xs ) ld = longest_decreasing_subseq_length ( xs ) return max ( li , ld ) , li - ld
Return the length of the longest monotonic subsequence of xs second return value is the difference between increasing and decreasing lengths .
11,533
def longest_increasing_subsequence ( xs ) : piles = [ [ ] ] for x , p in patience_sort ( xs ) : if p + 1 == len ( piles ) : piles . append ( [ ] ) piles [ p + 1 ] . append ( ( x , len ( piles [ p ] ) - 1 ) ) npiles = len ( piles ) - 1 prev = 0 lis = list ( ) for pile in range ( npiles , 0 , - 1 ) : x , prev = piles [ p...
Return a longest increasing subsequence of xs .
11,534
def backtracking ( a , L , bestsofar ) : w , j = max ( L . items ( ) ) while j != - 1 : yield j w , j = bestsofar [ j ]
Start with the heaviest weight and emit index
11,535
def mappability ( args ) : 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 ( "." ...
%prog mappability reference . fasta
11,536
def freq ( args ) : 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 (...
%prog freq fastafile bamfile
11,537
def frommaf ( args ) : 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...
%prog frommaf maffile
11,538
def libs ( args ) : 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...
%prog libs libfile
11,539
def pull ( args ) : 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 . e...
%prog pull libfile
11,540
def read_record ( fp , first_line = None ) : 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 =...
Read a record from a file of AMOS messages
11,541
def filter ( args ) : 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}...
%prog filter frgfile idsfile
11,542
def frg ( args ) : 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 . ty...
%prog frg frgfile
11,543
def asm ( args ) : 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 (...
%prog asm asmfile
11,544
def count ( args ) : 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 . ite...
%prog count frgfile
11,545
def prepare ( args ) : 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 ) cou...
%prog prepare countfolder families
11,546
def outlier_cutoff ( a , threshold = 3.5 ) : 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
Iglewicz and Hoaglin s robust returns the cutoff values - lower bound and upper bound .
11,547
def bed ( args ) : 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 =...
%prog bed genes . ids
11,548
def bed ( args ) : 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 , ...
%prog bed binfile fastafile
11,549
def query ( args ) : 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 = offse...
%prog query binfile fastafile ctgID baseID
11,550
def count ( args ) : 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. Remo...
%prog count t . coveragePerBase fastafile
11,551
def edges_to_path ( edges ) : if not edges : return None G = edges_to_graph ( edges ) path = nx . topological_sort ( G ) return path
Connect edges and return a path .
11,552
def max_sum ( a ) : 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 , current_start_index , current_en...
For an input array a output the range that gives the largest sum
11,553
def silicosoma ( args ) : 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 i...
%prog silicosoma in . silico > out . soma
11,554
def condense ( args ) : 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 ....
%prog condense OM . bed
11,555
def chimera ( args ) : 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 ) chimerabed = "chimera.bed" fw = open ( chimerabed , "w" ) for...
%prog chimera bedfile
11,556
def select_bed ( bed ) : 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
Return non - overlapping set of ranges choosing high scoring blocks over low scoring alignments when there are conflicts .
11,557
def fasta ( args ) : 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 ] ...
%prog fasta bedfile scf . fasta pseudomolecules . fasta
11,558
def bed ( args ) : 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 = "...
%prog bed xmlfile
11,559
def bam ( args ) : 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 ...
%prog snp input . gsnap ref . fasta
11,560
def index ( args ) : 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 ( dbfi...
%prog index database . fasta Wrapper for gmap_build . Same interface .
11,561
def gmap ( args ) : 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 chimera" " detected, e...
%prog gmap database . fasta fastafile
11,562
def align ( args ) : 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 GSN...
%prog align database . fasta read1 . fq read2 . fq
11,563
def get_1D_overlap ( eclusters , depth = 1 ) : overlap_set = set ( ) active = set ( ) ends = [ ] for i , ( chr , left , right ) in enumerate ( eclusters ) : ends . append ( ( chr , left , 0 , i ) ) ends . append ( ( chr , right , 1 , i ) ) ends . sort ( ) chr_last = "" for chr , pos , left_right , i in ends : if chr !=...
Find blocks that are 1D overlapping returns cliques of block ids that are in conflict
11,564
def make_range ( clusters , extend = 0 ) : 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 ) xmax += extend ymax += extend if xmax < xmin : xmin ,...
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
11,565
def get_constraints ( clusters , quota = ( 1 , 1 ) , Nmax = 0 ) : qa , qb = quota eclusters = make_range ( clusters , extend = - Nmax ) nodes = [ ( i + 1 , c [ - 1 ] ) for i , c in enumerate ( eclusters ) ] eclusters_x , eclusters_y , scores = zip ( * eclusters ) constraints_x = get_1D_overlap ( eclusters_x , qa ) cons...
Check pairwise cluster comparison if they overlap then mark edge as conflict
11,566
def format_lp ( nodes , constraints_x , qa , constraints_y , qb ) : lp_handle = cStringIO . StringIO ( ) lp_handle . write ( "Maximize\n " ) records = 0 for i , score in nodes : lp_handle . write ( "+ %d x%d " % ( score , i ) ) records += 1 if records % 10 == 0 : lp_handle . write ( "\n" ) lp_handle . write ( "\n" ) nu...
Maximize 4 x1 + 2 x2 + 3 x3 + x4 Subject To x1 + x2 < = 1 End
11,567
def solve_lp ( clusters , quota , work_dir = "work" , Nmax = 0 , self_match = False , solver = "SCIP" , verbose = False ) : qb , qa = quota nodes , constraints_x , constraints_y = get_constraints ( clusters , ( qa , qb ) , Nmax = Nmax ) if self_match : constraints_x = constraints_y = constraints_x | constraints_y lp_da...
Solve the formatted LP instance
11,568
def print_maps_by_type ( map_type , number = None ) : 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} ...
Print all available maps of a given type .
11,569
def get_map ( name , map_type , number , reverse = False ) : number = str ( number ) 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 ) map_names = dict ( ( k . lower ( ) , k ) for k in COLOR_MAPS [ map...
Return a BrewerMap representation of the specified color map .
11,570
def _load_maps_by_type ( map_type ) : 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 ) loaded_maps [ m...
Load all maps of a given type into a dictionary .
11,571
def mpl_colors ( self ) : mc = [ ] for color in self . colors : mc . append ( tuple ( [ x / 255. for x in color ] ) ) return mc
Colors expressed on the range 0 - 1 as used by matplotlib .
11,572
def get_mpl_colormap ( self , ** kwargs ) : if not HAVE_MPL : raise RuntimeError ( 'matplotlib not available.' ) cmap = LinearSegmentedColormap . from_list ( self . name , self . mpl_colors , ** kwargs ) return cmap
A color map that can be used in matplotlib plots . Requires matplotlib to be importable . Keyword arguments are passed to matplotlib . colors . LinearSegmentedColormap . from_list .
11,573
def show_as_blocks ( self , block_size = 100 ) : from ipythonblocks import BlockGrid grid = BlockGrid ( self . number , 1 , block_size = block_size ) for block , color in zip ( grid , self . colors ) : block . rgb = color grid . show ( )
Show colors in the IPython Notebook using ipythonblocks .
11,574
def colorbrewer2_url ( self ) : url = 'http://colorbrewer2.org/index.html?type={0}&scheme={1}&n={2}' return url . format ( self . type . lower ( ) , self . name , self . number )
URL that can be used to view the color map at colorbrewer2 . org .
11,575
def summary ( args ) : from jcvi . formats . fasta import summary as fsummary from jcvi . utils . cbook import percentage , human_size p = OptionParser ( summary . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) chainfile , oldfasta , newfasta = args chain = ...
%prog summary old . new . chain old . fasta new . fasta
11,576
def fromagp ( args ) : from jcvi . formats . agp import AGP from jcvi . formats . sizes import Sizes p = OptionParser ( fromagp . __doc__ ) p . add_option ( "--novalidate" , default = False , action = "store_true" , help = "Do not validate AGP" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit (...
%prog fromagp agpfile componentfasta objectfasta
11,577
def blat ( args ) : p = OptionParser ( blat . __doc__ ) p . add_option ( "--minscore" , default = 100 , type = "int" , help = "Matches minus mismatches gap penalty [default: %default]" ) p . add_option ( "--minid" , default = 98 , type = "int" , help = "Minimum sequence identity [default: %default]" ) p . set_cpus ( ) ...
%prog blat old . fasta new . fasta
11,578
def frompsl ( args ) : from jcvi . formats . sizes import Sizes p = OptionParser ( frompsl . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) pslfile , oldfasta , newfasta = args pf = oldfasta . split ( "." ) [ 0 ] chainfile = pf + ".chain" twobitfiles = [ ] f...
%prog frompsl old . new . psl old . fasta new . fasta
11,579
def lastz_to_blast ( row ) : atoms = row . strip ( ) . split ( "\t" ) name1 , name2 , coverage , identity , nmismatch , ngap , start1 , end1 , strand1 , start2 , end2 , strand2 , score = atoms identity = identity . replace ( "%" , "" ) hitlen = coverage . split ( "/" ) [ 1 ] score = float ( score ) same_strand = ( stra...
Convert the lastz tabular to the blast tabular see headers above Obsolete after LASTZ version 1 . 02 . 40
11,580
def lastz_2bit ( t ) : bfasta_fn , afasta_fn , outfile , lastz_bin , extra , mask , format = t ref_tags = [ Darkspace ] qry_tags = [ Darkspace ] ref_tags , qry_tags = add_mask ( ref_tags , qry_tags , mask = mask ) lastz_cmd = Lastz_template . format ( lastz_bin , bfasta_fn , ref_tags , afasta_fn , qry_tags ) if extra :...
Used for formats other than BLAST i . e . lav maf etc . which requires the database file to contain a single FASTA record .
11,581
def augustus ( args ) : p = OptionParser ( augustus . __doc__ ) p . add_option ( "--species" , default = "maize" , help = "Use species model for prediction" ) p . add_option ( "--hintsfile" , help = "Hint-guided AUGUSTUS" ) p . add_option ( "--nogff3" , default = False , action = "store_true" , help = "Turn --gff3=off"...
%prog augustus fastafile
11,582
def star ( args ) : p = OptionParser ( star . __doc__ ) p . add_option ( "--single" , default = False , action = "store_true" , help = "Single end mapping" ) p . set_fastq_names ( ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) folder , reference = a...
%prog star folder reference
11,583
def cufflinks ( args ) : p = OptionParser ( cufflinks . __doc__ ) p . add_option ( "--gtf" , help = "Reference annotation [default: %default]" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) folder , reference = args cpus = opts . cpus gtf = opts . g...
%prog cufflinks folder reference
11,584
def tophat ( args ) : from jcvi . apps . bowtie import check_index from jcvi . formats . fastq import guessoffset p = OptionParser ( tophat . __doc__ ) p . add_option ( "--gtf" , help = "Reference annotation [default: %default]" ) p . add_option ( "--single" , default = False , action = "store_true" , help = "Single en...
%prog tophat folder reference
11,585
def hmean_int ( a , a_min = 5778 , a_max = 1149851 ) : from scipy . stats import hmean return int ( round ( hmean ( np . clip ( a , a_min , a_max ) ) ) )
Harmonic mean of an array returns the closest int
11,586
def golden_array ( a , phi = 1.61803398875 , lb = LB , ub = UB ) : counts = np . zeros ( BB , dtype = int ) for x in a : c = int ( round ( math . log ( x , phi ) ) ) if c < lb : c = lb if c > ub : c = ub counts [ c - lb ] += 1 return counts
Given list of ints we aggregate similar values so that it becomes an array of multiples of phi where phi is the golden ratio .
11,587
def heatmap ( args ) : p = OptionParser ( heatmap . __doc__ ) p . add_option ( "--resolution" , default = 500000 , type = "int" , help = "Resolution when counting the links" ) p . add_option ( "--chr" , help = "Plot this contig/chr only" ) p . add_option ( "--nobreaks" , default = False , action = "store_true" , help =...
%prog heatmap input . npy genome . json
11,588
def get_seqstarts ( bamfile , N ) : import pysam bamfile = pysam . AlignmentFile ( bamfile , "rb" ) seqsize = { } for kv in bamfile . header [ "SQ" ] : if kv [ "LN" ] < 10 * N : continue seqsize [ kv [ "SN" ] ] = kv [ "LN" ] / N + 1 allseqs = natsorted ( seqsize . keys ( ) ) allseqsizes = np . array ( [ seqsize [ x ] f...
Go through the SQ headers and pull out all sequences with size greater than the resolution settings i . e . contains at least a few cells
11,589
def get_distbins ( start = 100 , bins = 2500 , ratio = 1.01 ) : b = np . ones ( bins , dtype = "float64" ) b [ 0 ] = 100 for i in range ( 1 , bins ) : b [ i ] = b [ i - 1 ] * ratio bins = np . around ( b ) . astype ( dtype = "int" ) binsizes = np . diff ( bins ) return bins , binsizes
Get exponentially sized
11,590
def simulate ( args ) : p = OptionParser ( simulate . __doc__ ) p . add_option ( "--genomesize" , default = 10000000 , type = "int" , help = "Genome size" ) p . add_option ( "--genes" , default = 1000 , type = "int" , help = "Number of genes" ) p . add_option ( "--contigs" , default = 100 , type = "int" , help = "Numbe...
%prog simulate test
11,591
def write_last_and_beds ( pf , GenePositions , ContigStarts ) : qbedfile = pf + "tigs.bed" sbedfile = pf + "chr.bed" lastfile = "{}tigs.{}chr.last" . format ( pf , pf ) qbedfw = open ( qbedfile , "w" ) sbedfw = open ( sbedfile , "w" ) lastfw = open ( lastfile , "w" ) GeneContigs = np . searchsorted ( ContigStarts , Gen...
Write LAST file query and subject BED files .
11,592
def write_clm ( pf , ICLinkStartContigs , ICLinkEndContigs , ICLinkStarts , ICLinkEnds , ContigStarts , ContigSizes ) : clm = defaultdict ( list ) for start , end , linkstart , linkend in zip ( ICLinkStartContigs , ICLinkEndContigs , ICLinkStarts , ICLinkEnds ) : start_a = ContigStarts [ start ] start_b = start_a + Con...
Write CLM file from simulated data .
11,593
def density ( args ) : p = OptionParser ( density . __doc__ ) p . add_option ( "--save" , default = False , action = "store_true" , help = "Write log densitites of contigs to file" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) clmfile , = args clm ...
%prog density test . clm
11,594
def optimize ( args ) : p = OptionParser ( optimize . __doc__ ) p . add_option ( "--skiprecover" , default = False , action = "store_true" , help = "Do not import 'recover' contigs" ) p . add_option ( "--startover" , default = False , action = "store_true" , help = "Do not resume from existing tour file" ) p . add_opti...
%prog optimize test . clm
11,595
def optimize_orientations ( fwtour , clm , phase , cpus ) : tour_contigs = clm . active_contigs tour = clm . tour oo = clm . oo print_tour ( fwtour , tour , "FLIPALL{}" . format ( phase ) , tour_contigs , oo , signs = clm . signs ) tag1 = clm . flip_whole ( tour ) print_tour ( fwtour , tour , "FLIPWHOLE{}" . format ( p...
Optimize the orientations of contigs by using heuristic flipping .
11,596
def iter_last_tour ( tourfile , clm ) : row = open ( tourfile ) . readlines ( ) [ - 1 ] _tour , _tour_o = separate_tour_and_o ( row ) tour = [ ] tour_o = [ ] for tc , to in zip ( _tour , _tour_o ) : if tc not in clm . contigs : logging . debug ( "Contig `{}` in file `{}` not found in `{}`" . format ( tc , tourfile , cl...
Extract last tour from tourfile . The clm instance is also passed in to see if any contig is covered in the clm .
11,597
def iter_tours ( tourfile , frames = 1 ) : fp = open ( tourfile ) i = 0 for row in fp : if row [ 0 ] == '>' : label = row [ 1 : ] . strip ( ) if label . startswith ( "GA" ) : pf , j , score = label . split ( "-" , 2 ) j = int ( j ) else : j = 0 i += 1 else : if j % frames != 0 : continue tour , tour_o = separate_tour_a...
Extract tours from tourfile . Tourfile contains a set of contig configurations generated at each iteration of the genetic algorithm . Each configuration has two rows first row contains iteration id and score second row contains list of contigs separated by comma .
11,598
def movie ( args ) : p = OptionParser ( movie . __doc__ ) p . add_option ( "--frames" , default = 500 , type = "int" , help = "Only plot every N frames" ) p . add_option ( "--engine" , default = "ffmpeg" , choices = ( "ffmpeg" , "gifsicle" ) , help = "Movie engine, output MP4 or GIF" ) p . set_beds ( ) opts , args , io...
%prog movie test . tour test . clm ref . contigs . last
11,599
def prepare_ec ( oo , sizes , M ) : tour = range ( len ( oo ) ) tour_sizes = np . array ( [ sizes . sizes [ x ] for x in oo ] ) tour_M = M [ oo , : ] [ : , oo ] return tour , tour_sizes , tour_M
This prepares EC and converts from contig_id to an index .