def merge_fasta(fasta_file, output_dir):
<EOL>def chunk_lexicographic_order(chunk):<EOL><INDENT>"""<STR_LIT>"""<EOL>chunk_fields = chunk.split("<STR_LIT:_>")<EOL>chunk_name = chunk_fields[:-<NUM_LIT:1>]<EOL>chunk_id = chunk_fields[-<NUM_LIT:1>]<EOL>return (chunk_name, int(chunk_id))<EOL><DEDENT>def are_consecutive(chunk1, chunk2):<EOL><INDENT>if None in {chunk1, chunk2}:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>ord1 = chunk_lexicographic_order(chunk1)<EOL>ord2 = chunk_lexicographic_order(chunk2)<EOL>return (ord1[<NUM_LIT:0>] == ord2[<NUM_LIT:0>]) and (ord1[<NUM_LIT:1>] == ord2[<NUM_LIT:1>] + <NUM_LIT:1>)<EOL><DEDENT><DEDENT>def consecutiveness(key_chunk_pair):<EOL><INDENT>"""<STR_LIT>"""<EOL>key, chunk = key_chunk_pair<EOL>chunk_name, chunk_id = chunk_lexicographic_order(chunk)<EOL>return (chunk_name, chunk_id - key)<EOL><DEDENT>genome = {<EOL>record.id: record.seq for record in SeqIO.parse(fasta_file, "<STR_LIT>")<EOL>}<EOL>sorted_ids = sorted(genome, key=chunk_lexicographic_order)<EOL>new_genome = dict()<EOL>for _, g in itertools.groupby(enumerate(sorted_ids), consecutiveness):<EOL><INDENT>chunk_range = map(operator.itemgetter(<NUM_LIT:1>), g)<EOL>first_chunk = next(chunk_range)<EOL>my_sequence = genome[first_chunk]<EOL>my_chunk = None<EOL>while "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>my_chunk = next(chunk_range)<EOL>my_sequence += genome[my_chunk]<EOL><DEDENT>except StopIteration:<EOL><INDENT>break<EOL><DEDENT><DEDENT>try:<EOL><INDENT>last_chunk_id = my_chunk.split("<STR_LIT:_>")[-<NUM_LIT:1>]<EOL><DEDENT>except AttributeError:<EOL><INDENT>last_chunk_id = "<STR_LIT>"<EOL><DEDENT>if last_chunk_id:<EOL><INDENT>new_chunk_id = "<STR_LIT>".format(first_chunk, last_chunk_id)<EOL><DEDENT>else:<EOL><INDENT>new_chunk_id = first_chunk<EOL><DEDENT>new_genome[new_chunk_id] = my_sequence<EOL><DEDENT>base_name = "<STR_LIT:.>".join(os.path.basename(fasta_file).split("<STR_LIT:.>")[:-<NUM_LIT:1>])<EOL>output_name = "<STR_LIT>".format(base_name)<EOL>merged_core_file = os.path.join(output_dir, output_name)<EOL>with open(merged_core_file, "<STR_LIT:w>") as output_handle:<EOL><INDENT>for my_id in sorted(new_genome, key=chunk_lexicographic_order):<EOL><INDENT>output_handle.write("<STR_LIT>".format(my_id))<EOL>output_handle.write("<STR_LIT>".format(new_genome[my_id]))<EOL><DEDENT><DEDENT>
Merge chunks into complete FASTA bins

    Merge bin chunks by appending consecutive chunks to one another.

    Parameters
    ----------
    fasta_file : file, str or pathlib.Path
        The FASTA file containing the chunks to merge.
    output_dir : str or pathlib.Path
        The output directory to write the merged FASTA bin into.