def main(args, lims, epp_logger):
    p = Process(lims, id=args.pid)
    lines = []
    cs = []
    if args.container_id:
        cs = p.output_containers()
        for c in cs:
            logging.info('Constructing barcode for container {0}.'.format(
                c.id))
            lines += makeContainerBarcode(c.id, copies=1)
    if args.container_name:
        cs = p.output_containers()
        for c in cs:
            logging.info('Constructing name label for container {0}.'.format(
                c.id))
            lines += makeContainerNameBarcode(c.name, copies=1)
    if args.operator_and_date:
        op = p.technician.name
        date = str(datetime.date.today())
        if cs:  # list of containers
            copies = len(cs)
        else:
            copies = args.copies
        lines += makeOperatorAndDateBarcode(op, date, copies=copies)
    if args.process_name:
        pn = p.type.name
        if cs:  # list of containers
            copies = len(cs)
        else:
            copies = args.copies
        lines += makeProcessNameBarcode(pn, copies=copies)
    if not (args.container_id or args.container_name or args.operator_and_date
            or args.process_name):
        logging.info('No recognized label type given, exiting.')
        sys.exit(-1)
    if not args.use_printer:
        logging.info('Writing to stdout.')
        epp_logger.saved_stdout.write('\n'.join(lines) + '\n')
    elif lines:  # Avoid printing empty files
        lp_args = ["lp"]
        if args.hostname:
            #remove that when all the calls to this script have been updated
            if args.hostname == 'homer.scilifelab.se:631':
                args.hostname = 'homer2.scilifelab.se:631'
            lp_args += ["-h", args.hostname]
        if args.destination:
            lp_args += ["-d", args.destination]
        lp_args.append("-")  # lp accepts stdin if '-' is given as filename
        logging.info('Ready to call lp for printing.')
        sp = subprocess.Popen(lp_args,
                              stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
        sp.stdin.write(str('\n'.join(lines)))
        logging.info('lp command is called for printing.')
        stdout, stderr = sp.communicate()  # Will wait for sp to finish
        logging.info('lp stdout: {0}'.format(stdout))
        logging.info('lp stderr: {0}'.format(stderr))
        logging.info('lp command finished')
        sp.stdin.close()
def main(args,lims,epp_logger):
    p = Process(lims,id=args.pid)
    lines = []
    cs = []
    if args.container_id:
        cs = p.output_containers()
        for c in cs:
            logging.info('Constructing barcode for container {0}.'.format(c.id))
            lines += makeContainerBarcode(c.id, copies=1)
    if args.container_name:
        cs = p.output_containers()
        for c in cs:
            logging.info('Constructing name label for container {0}.'.format(c.id))
            lines += makeContainerNameBarcode(c.name,copies=1)
    if args.operator_and_date:
        op = p.technician.name
        date = str(datetime.date.today())
        if cs: # list of containers
            copies = len(cs)
        else:
            copies = args.copies
        lines += makeOperatorAndDateBarcode(op,date,copies=copies)
    if args.process_name:
        pn = p.type.name
        if cs: # list of containers
            copies = len(cs)
        else:
            copies = args.copies
        lines += makeProcessNameBarcode(pn,copies=copies)
    if not (args.container_id or args.container_name or 
            args.operator_and_date or args.process_name):
        logging.info('No recognized label type given, exiting.')
        sys.exit(-1)
    if not args.use_printer:
        logging.info('Writing to stdout.')
        epp_logger.saved_stdout.write('\n'.join(lines)+'\n')
    elif lines: # Avoid printing empty files
        lp_args = ["lp"]
        if args.hostname:
            #remove that when all the calls to this script have been updated
            if args.hostname == 'homer.scilifelab.se:631':
                args.hostname='homer2.scilifelab.se:631'
            lp_args += ["-h",args.hostname]
        if args.destination:
            lp_args += ["-d",args.destination]
        lp_args.append("-") # lp accepts stdin if '-' is given as filename
        logging.info('Ready to call lp for printing.')
        sp = subprocess.Popen(lp_args, 
                              stdin=subprocess.PIPE, 
                              stdout=subprocess.PIPE, 
                              stderr=subprocess.PIPE)
        sp.stdin.write(str('\n'.join(lines)))
        logging.info('lp command is called for printing.')
        stdout,stderr = sp.communicate() # Will wait for sp to finish
        logging.info('lp stdout: {0}'.format(stdout))
        logging.info('lp stderr: {0}'.format(stderr))
        logging.info('lp command finished')
        sp.stdin.close()
Example #3
0
def samplesheet(lims, process_id, output_file):
    """Create Tapestation samplesheet."""
    process = Process(lims, id=process_id)
    well_plate = {}

    for placement, artifact in process.output_containers(
    )[0].placements.iteritems():
        placement = ''.join(placement.split(':'))
        well_plate[placement] = artifact.name.split('_')[0]

    for well in clarity_epp.export.utils.sort_96_well_plate(well_plate.keys()):
        output_file.write('{sample}\n'.format(sample=well_plate[well]))
Example #4
0
def container_sample(lims, process_id, output_file, description=''):
    """Generate container & artifact name label file."""
    process = Process(lims, id=process_id)
    for container in process.output_containers():
        for artifact in container.placements.values():
            if description:
                output_file.write(
                    '{description}\t{sample}\t{container}\r\n'.format(
                        description=description,
                        container=container.name,
                        sample=artifact.name))
            else:
                output_file.write('{sample}\t{container}\r\n'.format(
                    container=container.name, sample=artifact.name))
Example #5
0
def samplesheet_filling_out(lims, process_id, output_file):
    """Create Hamilton samplesheet for filling out 96 well plate."""
    output_file.write('SourceTubeID\tPositionID\n')
    process = Process(lims, id=process_id)
    well_plate = {}

    for placement, artifact in process.output_containers(
    )[0].placements.iteritems():
        placement = ''.join(placement.split(':'))
        well_plate[placement] = artifact.samples[0].udf['Dx Fractienummer']

    for well in clarity_epp.export.utils.sort_96_well_plate(well_plate.keys()):
        output_file.write('{source_tube}\t{well}\n'.format(
            source_tube=well_plate[well], well=well))
Example #6
0
def samplesheet(lims, process_id, output_file):
    """Create Magnis samplesheet."""
    process = Process(lims, id=process_id)
    well_strip = {}

    for placement, artifact in process.output_containers()[0].placements.items():
        placement = ''.join(placement.split(':'))
        well_strip[placement] = artifact.name

    # Write Header
    output_file.write('sample_id\n')

    # Write samples
    for well in clarity_epp.export.utils.sort_96_well_plate(well_strip.keys()):
        output_file.write('{sample}{instrument_name}\n'.format(
            sample=well_strip[well],
            instrument_name=process.udf['Instrument naam'].capitalize()
        ))
Example #7
0
def container(lims, process_id, output_file, description=''):
    """Generate container label file."""
    process = Process(lims, id=process_id)
    for index, container in enumerate(
            sorted(process.output_containers(),
                   key=lambda container: container.id,
                   reverse=True)):
        if description:
            if ',' in description:
                output_file.write('{description}\t{container}\r\n'.format(
                    description=description.split(',')[index],
                    container=container.name))
            else:
                output_file.write('{description}\t{container}\r\n'.format(
                    description=description, container=container.name))
        else:
            output_file.write(
                '{container}\r\n'.format(container=container.name))
Example #8
0
def samplesheet(lims, process_id, output_file):
    """Create Tecan samplesheet."""
    output_file.write('Position\tSample\n')
    process = Process(lims, id=process_id)
    well_plate = {}

    for placement, artifact in process.output_containers()[0].placements.items(
    ):
        placement = ''.join(placement.split(':'))
        if len(
                artifact.samples
        ) == 1:  # Remove 'meet_id' from artifact name if artifact is not a pool
            well_plate[placement] = artifact.name.split('_')[0]
        else:
            well_plate[placement] = artifact.name

    for well in clarity_epp.export.utils.sort_96_well_plate(well_plate.keys()):
        output_file.write('{well}\t{sample}\n'.format(well=well,
                                                      sample=well_plate[well]))
Example #9
0
def samplesheet(lims, process_id, output_file):
    """Create Bioanalyzer samplesheet."""
    process = Process(lims, id=process_id)

    # Default plate layout
    plate = {
        'A1': {'name': 'sample 1', 'comment': ''}, 'A2': {'name': 'sample 2', 'comment': ''}, 'A3': {'name': 'sample 3', 'comment': ''},
        'B1': {'name': 'sample 4', 'comment': ''}, 'B2': {'name': 'sample 5', 'comment': ''}, 'B3': {'name': 'sample 6', 'comment': ''},
        'C1': {'name': 'sample 7', 'comment': ''}, 'C2': {'name': 'sample 8', 'comment': ''}, 'C3': {'name': 'sample 9', 'comment': ''},
        'D1': {'name': 'sample 10', 'comment': ''}, 'D2': {'name': 'sample 11', 'comment': ''}
    }

    # Get sample placement
    for placement, artifact in process.output_containers()[0].placements.iteritems():
        placement = ''.join(placement.split(':'))
        plate[placement]['name'] = artifact.name
        plate[placement]['comment'] = ''

    # Create samplesheet
    output_file.write('"Sample Name","Sample Comment","Rest. Digest","Status","Observation","Result Label","Result Color"\n')
    for well in sorted(plate.keys()):
        output_file.write('{sample},{sample_comment},FALSE,1,,,\n'.format(
            sample=plate[well]['name'],
            sample_comment=plate[well]['comment']
        ))
    output_file.write('Ladder,,FALSE,1,,,\n\n')

    output_file.write('"Chip Lot #","Reagent Kit Lot #"\n')
    output_file.write('{chip_lot},{reagent_lot}\n\n'.format(
        chip_lot=process.udf['lot # chip'],
        reagent_lot=process.udf['lot # Reagentia kit']
    ))

    output_file.write('"QC1 Min [%]","QC1 Max [%]","QC2 Min [%]","QC2 Max [%]"\n')
    output_file.write(',,,\n\n')

    output_file.write('"Chip Comment"\n\n\n')

    output_file.write('"Study Name","Experimenter","Laboratory","Company","Department"\n')
    output_file.write(',,,,\n\n')

    output_file.write('"Study Comment"\n\n')
Example #10
0
def samplesheet_purify(lims, process_id, output_file):
    """Create Hamilton samplesheet for purifying 96 well plate."""
    output_file.write(
        'SampleID\tSample Rack barcode\tSample rack positionID\tSample Start volume\n'
    )
    process = Process(lims, id=process_id)
    parent_process_barcode = process.parent_processes()[0].output_containers(
    )[0].name
    well_plate = {}

    for placement, artifact in process.output_containers(
    )[0].placements.iteritems():
        placement = ''.join(placement.split(':'))
        well_plate[placement] = artifact.samples[0].udf['Dx Fractienummer']

    for well in clarity_epp.export.utils.sort_96_well_plate(well_plate.keys()):
        output_file.write(
            '{sample}\t{sample_rack_barcode}\t{sample_rack_position}\t{sample_start_volume}\n'
            .format(sample=well_plate[well],
                    sample_rack_barcode=parent_process_barcode,
                    sample_rack_position=well,
                    sample_start_volume='50'))
Example #11
0
def samplesheet_purify(lims, process_id, output_file):
    """Create manual pipetting samplesheet for purifying samples."""
    output_file.write(
        'Fractienummer\tConcentration(ng/ul)\taantal ng te isoleren\tul gDNA\tul Water\n'
    )
    process = Process(lims, id=process_id)

    for container in process.output_containers():
        artifact = container.placements['1:1']  # asume tubes
        input_artifact = artifact.input_artifact_list()[
            0]  # asume one input artifact
        sample = artifact.samples[0]  # asume one sample per tube

        if 'Dx Fractienummer' in sample.udf:
            fractienummer = sample.udf['Dx Fractienummer']
        else:  # giab
            fractienummer = sample.name

        if 'Dx Concentratie fluorescentie (ng/ul)' in input_artifact.udf:
            concentration = float(
                input_artifact.udf['Dx Concentratie fluorescentie (ng/ul)'])
        elif 'Dx Concentratie OD (ng/ul)' in input_artifact.udf:
            concentration = float(
                input_artifact.udf['Dx Concentratie OD (ng/ul)'])
        elif 'Dx Concentratie (ng/ul)' in sample.udf:
            concentration = float(sample.udf['Dx Concentratie (ng/ul)'])

        input_gdna_ng = float(artifact.udf['Dx input hoeveelheid (ng)'])
        ul_gdna = input_gdna_ng / concentration
        ul_water = 200 - ul_gdna

        output_file.write(
            '{fractienummer}\t{concentration}\t{input_gdna_ng}\t{ul_gdna:.1f}\t{ul_water:.1f}\n'
            .format(fractienummer=fractienummer,
                    concentration=concentration,
                    input_gdna_ng=input_gdna_ng,
                    ul_gdna=ul_gdna,
                    ul_water=ul_water))
Example #12
0
def samplesheet_normalise(lims, process_id, output_file):
    """Create Caliper samplesheet for normalising 96 well plate."""
    output_file.write(
        'Monsternummer\tPlate_Id_input\tWell\tPlate_Id_output\tPipetteervolume DNA (ul)\tPipetteervolume H2O (ul)\n'
    )
    process = Process(lims, id=process_id)
    process_samples = [artifact.name for artifact in process.analytes()[0]]
    parent_processes = []
    parent_process_barcode_manual = 'None'
    parent_process_barcode_hamilton = 'None'

    for p in process.parent_processes():
        if p.type.name.startswith('Dx manueel gezuiverd placement'):
            for pp in p.parent_processes():
                parent_processes.append(pp)
            parent_process_barcode_manual = p.output_containers()[0].name
        elif p.type.name.startswith('Dx Hamilton'):
            parent_processes.append(p)
            parent_process_barcode_hamilton = p.output_containers()[0].name
        elif p.type.name.startswith('Dx Zuiveren gDNA manueel'):
            parent_processes.append(p)

    if parent_process_barcode_hamilton != 'None':
        parent_process_barcode = parent_process_barcode_hamilton
    else:
        parent_process_barcode = parent_process_barcode_manual

    # Get all Qubit and Tecan Spark QC types
    qc_process_types = clarity_epp.export.utils.get_process_types(
        lims, ['Dx Qubit QC', 'Dx Tecan Spark 10M QC'])

    # Get all unique input artifact ids
    parent_processes = list(set(parent_processes))
    input_artifact_ids = []
    for p in parent_processes:
        for analyte in p.all_outputs():
            input_artifact_ids.append(analyte.id)
    input_artifact_ids = list(set(input_artifact_ids))

    # Get unique QC processes for input artifacts
    qc_processes = list(
        set(
            lims.get_processes(type=qc_process_types,
                               inputartifactlimsid=input_artifact_ids)))

    samples_measurements_qubit = {}
    sample_concentration = {}
    samples_measurements_tecan = {}
    filled_wells = []
    order = [
        'A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'A2', 'B2', 'C2', 'D2',
        'E2', 'F2', 'G2', 'H2', 'A3', 'B3', 'C3', 'D3', 'E3', 'F3', 'G3', 'H3',
        'A4', 'B4', 'C4', 'D4', 'E4', 'F4', 'G4', 'H4', 'A5', 'B5', 'C5', 'D5',
        'E5', 'F5', 'G5', 'H5', 'A6', 'B6', 'C6', 'D6', 'E6', 'F6', 'G6', 'H6',
        'A7', 'B7', 'C7', 'D7', 'E7', 'F7', 'G7', 'H7', 'A8', 'B8', 'C8', 'D8',
        'E8', 'F8', 'G8', 'H8', 'A9', 'B9', 'C9', 'D9', 'E9', 'F9', 'G9', 'H9',
        'A10', 'B10', 'C10', 'D10', 'E10', 'F10', 'G10', 'H10', 'A11', 'B11',
        'C11', 'D11', 'E11', 'F11', 'G11', 'H11', 'A12', 'B12', 'C12', 'D12',
        'E12', 'F12', 'G12', 'H12'
    ]
    order = dict(zip(order, range(len(order))))
    last_filled_well = 0
    monsternummer = {}
    volume_DNA = {}
    volume_H2O = {}
    conc_measured = {}
    output_ng = float(process.udf['Output genormaliseerd gDNA'])
    conc = {}
    output_ul = process.udf['Eindvolume (ul) genormaliseerd gDNA']
    output_plate_barcode = process.output_containers()[0].name

    for qc_process in qc_processes:
        if 'Dx Qubit QC' in qc_process.type.name:
            for artifact in qc_process.all_outputs():
                sample = artifact.samples[0].name
                if sample in process_samples and not any(
                        keyword in artifact.name
                        for keyword in ['Tecan', 'check', 'Label']):
                    if 'Dx Conc. goedgekeurde meting (ng/ul)' in artifact.udf:
                        measurement = artifact.udf[
                            'Dx Conc. goedgekeurde meting (ng/ul)']
                        if sample not in samples_measurements_qubit:
                            samples_measurements_qubit[sample] = []
                        samples_measurements_qubit[sample].append(measurement)
                    elif sample not in sample_concentration:
                        sample_concentration[sample] = 'geen'

        elif 'Dx Tecan Spark 10M QC' in qc_process.type.name:
            for artifact in qc_process.all_outputs():
                sample = artifact.samples[0].name
                if sample in process_samples and not any(
                        keyword in artifact.name
                        for keyword in ['Tecan', 'check', 'Label']):
                    if 'Dx Conc. goedgekeurde meting (ng/ul)' in artifact.udf:
                        measurement = artifact.udf[
                            'Dx Conc. goedgekeurde meting (ng/ul)']
                        if sample not in samples_measurements_tecan:
                            samples_measurements_tecan[sample] = []
                        samples_measurements_tecan[sample].append(measurement)
                    elif sample not in sample_concentration:
                        sample_concentration[sample] = 'geen'

    for qc_process in qc_processes:
        for artifact in qc_process.all_outputs():
            sample = artifact.samples[0].name
            if not any(keyword in artifact.name
                       for keyword in ['Tecan', 'check', 'Label']):
                if 'Dx Tecan Spark 10M QC' in qc_process.type.name and 'Dx Conc. goedgekeurde meting (ng/ul)' in artifact.udf:
                    machine = 'Tecan'
                elif 'Dx Qubit QC' in qc_process.type.name and 'Dx Conc. goedgekeurde meting (ng/ul)' in artifact.udf:
                    machine = 'Qubit'

                if sample not in sample_concentration or machine == 'Qubit':
                    if sample in samples_measurements_tecan or sample in samples_measurements_qubit:
                        if machine == 'Tecan':
                            sample_measurements = samples_measurements_tecan[
                                sample]
                        elif machine == 'Qubit':
                            sample_measurements = samples_measurements_qubit[
                                sample]
                        sample_measurements_average = sum(
                            sample_measurements) / float(
                                len(sample_measurements))
                        sample_concentration[
                            sample] = sample_measurements_average

    for placement, artifact in process.output_containers()[0].placements.items(
    ):
        placement = ''.join(placement.split(':'))
        filled_wells.append(placement)
        if order[placement] > last_filled_well:
            last_filled_well = order[placement]

    for x in range(0, last_filled_well):
        for well, number in order.items():
            if number == x:
                placement = well
        monsternummer[placement] = 'Leeg'
        volume_DNA[placement] = 0
        volume_H2O[placement] = 0

    for placement, artifact in process.output_containers()[0].placements.items(
    ):
        sample = artifact.samples[0].name
        if sample in process_samples:
            placement = ''.join(placement.split(':'))
            monsternummer[placement] = sample
            conc_measured[placement] = sample_concentration[sample]
            if conc_measured[placement] != 'geen':
                if output_ng / conc_measured[placement] > 100:
                    conc[placement] = output_ng / 100
                else:
                    conc[placement] = conc_measured[placement]
                volume_DNA[placement] = int(round(output_ng / conc[placement]))
                volume_H2O[placement] = output_ul - int(
                    round(output_ng / conc[placement]))

    for well in clarity_epp.export.utils.sort_96_well_plate(
            monsternummer.keys()):
        output_file.write(
            '{monsternummer}\t{plate_id_input}\t{position}\t{plate_id_output}\t{volume_DNA}\t{volume_H2O}\n'
            .format(monsternummer=monsternummer[well],
                    plate_id_input=parent_process_barcode,
                    position=well,
                    plate_id_output=output_plate_barcode,
                    volume_DNA=volume_DNA[well],
                    volume_H2O=volume_H2O[well]))