def write_metadata_grid(data_worksheet, schema_dict):
    """

    :type data_worksheet: xlsxbasics.MetadataWorksheet
    """

    _write_sample_id_col(data_worksheet)

    unlocked = xlsxbasics.make_format(data_worksheet.workbook, is_locked=False)
    # format as text to prevent autoformatting!
    unlocked_text = xlsxbasics.make_format(data_worksheet.workbook,
                                           {'num_format': '@'},
                                           is_locked=False)

    sorted_keys = xlsxbasics.sort_keys(schema_dict)
    for field_index, field_name in enumerate(sorted_keys):
        field_specs_dict = schema_dict[field_name]
        curr_col_index = field_index + 1  # add one bc sample id is in first col

        xlsxbasics.write_header(data_worksheet, field_name, field_index + 1)
        curr_format = unlocked_text if _determine_if_format_should_be_text(
            field_specs_dict) else unlocked
        data_worksheet.worksheet.set_column(curr_col_index, curr_col_index,
                                            None, curr_format)

        col_range = xlsxbasics.format_range(curr_col_index, None)
        starting_cell_name = xlsxbasics.format_range(
            curr_col_index, data_worksheet.first_data_row_index)
        whole_col_range = xlsxbasics.format_range(
            curr_col_index,
            data_worksheet.first_data_row_index,
            last_row_index=data_worksheet.last_allowable_row_for_sample_index)

        validation_dict = _get_validation_dict(field_name, field_specs_dict,
                                               data_worksheet.regex_handler)
        value_key = "value"
        if validation_dict is not None:
            if value_key in validation_dict:
                unformatted_validation_formula = validation_dict[value_key]
                formatted_validation_formula = unformatted_validation_formula.format(
                    cell=starting_cell_name, col_range=col_range)
                validation_dict[value_key] = formatted_validation_formula

            validation_return_code = data_worksheet.worksheet.data_validation(
                whole_col_range, validation_dict)
            # NB: xlsxwriter's data_validation docstring *claims* it returns 0 if it succeeds, but in fact if it
            # succeeds it doesn't return an error code at all, hence the then None check ...
            if validation_return_code is not None and validation_return_code < 0:
                raise ValueError(
                    "Worksheet validation failed with return code '{0}'; check user warnings."
                    .format(validation_return_code))

        _add_default_if_any(data_worksheet, field_specs_dict, curr_col_index)

        max_samples_msg = "No more than {0} samples can be entered in this worksheet.  If you need to submit metadata" \
                          " for >{0} samples, please contact CMI directly.".format(data_worksheet.num_allowable_samples)
        xlsxbasics.write_header(
            data_worksheet, max_samples_msg,
            data_worksheet.first_data_col_index,
            data_worksheet.last_allowable_row_for_sample_index + 1)
def write_workbook(study_name, schema_dict, form_dict, metadata_wizard_settings):
    num_allowable_samples = 1000
    # TODO: someday: either expand code to use num_samples and add real code to get in from interface, or take out unused hook
    num_samples = 0
    num_columns = len(schema_dict.keys())
    a_regex_handler = metadata_wizard_settings.regex_handler

    # create workbook
    file_base_name = slugify(study_name)
    file_name = '{0}.xlsx'.format(file_base_name)
    output_path = metadata_wizard_settings.get_output_path(file_name)
    workbook = xlsxwriter.Workbook(output_path, {'strings_to_numbers': False,
                                               'strings_to_formulas': True,
                                               'strings_to_urls': True})

    # write metadata worksheet
    phi_renamed_schema_dict = metadata_wizard.schema_builder.rewrite_field_names_with_phi_if_relevant(schema_dict)
    metadata_worksheet = xlsxbasics.MetadataWorksheet(workbook, num_columns, num_samples, a_regex_handler,
                                                       num_allowable_samples=num_allowable_samples)
    metadata_wizard.xlsx_metadata_grid_builder.write_metadata_grid(metadata_worksheet, phi_renamed_schema_dict)

    # write validation worksheet
    validation_worksheet = metadata_wizard.xlsx_static_grid_builder.ValidationWorksheet(workbook, num_columns, num_samples,
                                                                                        a_regex_handler)
    index_and_range_str_tuple_by_header_dict = metadata_wizard.xlsx_static_grid_builder.write_static_validation_grid_and_helpers(
        validation_worksheet, phi_renamed_schema_dict)
    metadata_wizard.xlsx_dynamic_grid_builder.write_dynamic_validation_grid(
        validation_worksheet, index_and_range_str_tuple_by_header_dict)

    # write descriptions worksheet
    descriptions_worksheet = DescriptionWorksheet(workbook, num_columns, num_samples, a_regex_handler)
    xlsxbasics.write_header(descriptions_worksheet, "field name", 0)
    xlsxbasics.write_header(descriptions_worksheet, "field description", 1)
    sorted_keys = xlsxbasics.sort_keys(phi_renamed_schema_dict)
    for field_index, field_name in enumerate(sorted_keys):
        row_num = field_index + 1 + 1  # plus 1 to move past name row, and plus 1 again because row nums are 1-based
        field_specs_dict = phi_renamed_schema_dict[field_name]
        message = metadata_wizard.xlsx_validation_builder.get_field_constraint_description(field_specs_dict, a_regex_handler)
        descriptions_worksheet.worksheet.write("A{0}".format(row_num), field_name, metadata_worksheet.bold_format)
        descriptions_worksheet.worksheet.write("B{0}".format(row_num), message)

    # write schema worksheet--note, don't use the phi_renamed_schema_dict but the original schema_dict
    schema_worksheet = xlsxbasics.create_worksheet(workbook, "metadata_schema")
    schema_worksheet.write_string("A1", yaml.dump(schema_dict, default_flow_style=False))

    # write form worksheet
    form_worksheet = xlsxbasics.create_worksheet(workbook, "metadata_form")
    form_worksheet.write_string("A1", yaml.dump(form_dict, default_flow_style=False))

    # write readme worksheet
    readme_format = workbook.add_format({'align': 'left', 'valign': 'top'})
    readme_format.set_text_wrap()
    form_worksheet = xlsxbasics.create_worksheet(workbook, "readme")
    form_worksheet.set_column(0, 0, 100)  # Width of column A set to 100.
    form_worksheet.merge_range('A1:A100', metadata_wizard_settings.make_readme_text(), readme_format)

    # close workbook
    workbook.close()
    return file_name
Ejemplo n.º 3
0
def _write_dynamic_header_cell(val_sheet, curr_col_index, col_rank):
    # e.g., =IF(B2=" ", " ", INDEX($AS$1:$BY$1, 1, MATCH(COLUMNS($AS$1005:AS1005),$AS$1005:$BY$1005,0)))

    first_data_cell_in_col = xlsxbasics.format_range(
        curr_col_index, val_sheet.first_data_row_index)
    static_grid_header_row = xlsxbasics.format_single_static_grid_row_range(
        val_sheet,
        val_sheet.name_row_index,
        first_col_fixed=True,
        first_row_fixed=True,
        last_col_fixed=True,
        last_row_fixed=True)

    # if ALL samples are valid in this column, then all the data cells for this column will have a space
    # in them.  Conversely, if ANY sample is invalid in this column, the data cells will either be *empty* (have
    # not even a space) if a particular sample is valid in that column or will have the word "Fix".  I check just
    # the FIRST data cell in this column to see if it holds a space; if it does, the whole column is valid and
    # should be hidden, so the "header" will also just be a space.
    header_formula = "=IF({first_data_cell_in_col}=\" \", \" \", INDEX({static_grid_header_row}, 1, {col_rank}))" \
        .format(first_data_cell_in_col=first_data_cell_in_col, static_grid_header_row=static_grid_header_row,
                col_rank=col_rank)
    xlsxbasics.write_header(val_sheet, header_formula, curr_col_index)
def _write_sample_id_col(data_sheet):
    """

    :type data_sheet: xlsxbasics.MetadataWorksheet
    """

    data_sheet.worksheet.set_column(data_sheet.sample_id_col_index,
                                    data_sheet.sample_id_col_index, None, None,
                                    data_sheet.hidden_cell_setting)
    xlsxbasics.write_header(data_sheet, "sample_id",
                            data_sheet.sample_id_col_index)

    # +1 bc range is exclusive of last number
    for row_index in range(data_sheet.first_data_row_index,
                           data_sheet.last_allowable_row_for_sample_index + 1):
        curr_cell = xlsxbasics.format_range(data_sheet.sample_id_col_index,
                                            row_index)
        id_num = row_index - data_sheet.first_data_row_index + 1
        data_row_range = xlsxbasics.format_single_data_grid_row_range(
            data_sheet, row_index)

        completed_formula = "=IF(COUNTBLANK({data_row_range})<>COLUMNS({data_row_range}),{id_num},\"\")".format(
            data_row_range=data_row_range, id_num=id_num)
        data_sheet.worksheet.write_formula(curr_cell, completed_formula)
Ejemplo n.º 5
0
def _write_dynamic_name_link_col(val_sheet,
                                 index_and_range_str_tuple_by_header_dict):
    """

    :type val_sheet: xlsx_static_grid_builder.ValidationWorksheet
    """

    # e.g., =IF(B2=" "," ",HYPERLINK(CONCATENATE("#metadata!", ADDRESS(INDEX($AL$2:$AL$11,MATCH(ROWS($AJ$2:AJ2),
    # $AJ$2:$AJ$11,0),0),$AQ$14)),INDEX($AO$2:$AO$11,MATCH(ROWS($AJ$2:AJ2),$AJ$2:$AJ$11,0),0)))

    # Create the standard blue, underlined url link format.
    url_format = xlsxbasics.make_format(val_sheet.workbook, {
        'font_color': 'blue',
        'underline': 1
    })

    xlsxbasics.write_header(val_sheet, val_sheet.SAMPLE_NAME_HEADER,
                            val_sheet.name_link_col_index)

    # NB: grid goes as far as last allowable row for samples, not just to number of expected samples, in case user
    # adds some extra ones :)
    for curr_row_index in range(
            val_sheet.first_data_row_index,
            val_sheet.last_allowable_row_for_sample_index + 1):
        row_rank_num = _format_dynamic_rank_formula_str(
            val_sheet,
            curr_row_index,
            index_and_range_str_tuple_by_header_dict,
            for_row=True)

        row_in_metadata_fixed_range_str = index_and_range_str_tuple_by_header_dict[
            val_sheet.ROW_IN_METADATA_HEADER][1]
        metadata_row_index_str = "INDEX({row_in_metadata_fixed_range_str},{row_rank_num},0)".format(
            row_in_metadata_fixed_range_str=row_in_metadata_fixed_range_str,
            row_rank_num=row_rank_num)

        link_address = "CONCATENATE(\"#metadata!\",ADDRESS({metadata_row_index},{metadata_name_col_index}))".format(
            metadata_row_index=metadata_row_index_str,
            metadata_name_col_index=val_sheet.name_col_index)

        helper_name_fixed_range_str = index_and_range_str_tuple_by_header_dict[
            val_sheet.SAMPLE_NAME_HEADER][1]
        # this index formula will get the value of the name for this sample from the helper col next to the static grid
        helper_name_val = "INDEX({conditional_name_fixed_range_str},{row_num},0)".format(
            conditional_name_fixed_range_str=helper_name_fixed_range_str,
            row_num=row_rank_num)

        curr_cell = xlsxbasics.format_range(val_sheet.name_link_col_index,
                                            curr_row_index)

        # If this sample is entirely valid as shown by the fact that the first data cell in the dynamic grid for this
        # row is just an empty string, write a space into the dynamic name cell.  Otherwise, write a link to the
        # name column for this sample in the metadata sheet.  NB: it does NOT work to look at
        # the value in the is_valid helper column for this sample (either True or False) because the samples
        # change order based on validation status ...
        first_data_cell_in_first_data_col = xlsxbasics.format_range(
            val_sheet.name_link_col_index + 1, curr_row_index)
        full_formula = "=IF({first_validation_cell}=\" \",\" \",HYPERLINK({link_address},{helper_name_val}))".format(
            first_validation_cell=first_data_cell_in_first_data_col,
            link_address=link_address,
            helper_name_val=helper_name_val)
        val_sheet.worksheet.write_formula(curr_cell, full_formula, url_format)