def move_files():
    if not g.has_native_client:
        return jsonify(status="failure", reason="method not allowed")
    destination = request.values.get("destination")
    if destination is None:
        return jsonify(status="failure", reason="no destination specified")
    if not os.path.exists(destination):
        return jsonify(status="failure", reason="destination does not exist")

    filenames = request.values.getlist("filenames[]")
    good_names = []
    for name in filenames:
        path = resolve_file_name(name)
        if os.path.exists(path):
            good_names.append(path)
        else:
            g.add_message("Could not locate file %r" % (str(name), ))

    for file_path in good_names:
        file_dest = (os.path.join(destination, os.path.basename(file_path)))
        if os.path.exists(file_dest):
            shutil.rmtree(file_dest, True)
        try:
            shutil.move((file_path), file_dest)
        except shutil.Error as err:
            jsonify(status='failure', reason=str(err))
    return jsonify(status="success", reason=None)
def export_glycan_composition_hypothesis_as_text(uuid):
    hypothesis = get_glycan_hypothesis(uuid)
    entity_iterable = hypothesis.glycans
    g.add_message(Message("Building Export", "update"))
    file_name = "%s-glycan-compositions.txt" % (hypothesis.name)
    path = safepath(g.manager.get_temp_path(file_name))
    with open(path, 'wb') as handle:
        ImportableGlycanHypothesisCSVSerializer(handle, entity_iterable).start()
    file_names = [(file_name)]
    return jsonify(status='success', filenames=file_names)
def _export_csv(sample_run_uuid):
    view = get_view(sample_run_uuid)
    with view:
        g.add_message(Message("Building Chromatogram CSV Export", "update"))

        file_name = "%s-chromatograms.csv" % (view.record.name)
        path = safepath(g.manager.get_temp_path(file_name))

        SimpleChromatogramCSVSerializer(open(path, 'wb'),
                                        view.chromatograms).start()
    return [file_name]
Beispiel #4
0
def _export_csv(analysis_uuid):
    view = get_view(analysis_uuid)
    with view:
        g.add_message(Message("Building CSV Export", "update"))
        snapshot = view.get_items_for_display()
        with snapshot.bind(view.session):
            file_name = "%s-glycan-chromatograms.csv" % (view.analysis.name)
            path = g.manager.get_temp_path(file_name)
            GlycanLCMSAnalysisCSVSerializer(open(path, 'wb'), (
                c.convert()
                for c in (list(snapshot.glycan_chromatograms) +
                          list(snapshot.unidentified_chromatograms)))).start()
    return [file_name]
Beispiel #5
0
def add_modification():
    name = request.values.get("new-modification-name")
    formula = request.values.get("new-modification-formula")
    target = request.values.get("new-modification-target")
    if name is None or name == "":
        g.add_message("Modification Name Cannot Be Empty")
        return abort(400)
    try:
        composition = Composition(str(formula))
    except ChemicalCompositionError:
        g.add_message("Invalid Formula")
        return abort(400)
    try:
        target = extract_targets_from_string(target)
    except Exception:
        g.add_message("Invalid Target Specification")
        return abort(400)
    rule = ModificationRule(target, name, None, composition.mass, composition)
    try:
        add_user_peptide_modification_rule(rule)
    except Exception:
        g.add_message("Failed to save modification rule")
        return abort(400)
    return jsonify(name=rule.name,
                   formula=formula,
                   mass=rule.mass,
                   specificities=list(rule.as_spec_strings()))
def _export_hypothesis(analysis_uuid):
    view = get_view(analysis_uuid)
    with view:
        g.add_message(Message("Building CSV Export", "update"))
        snapshot = view.get_items_for_display()
        with snapshot.bind(view.session):
            file_name = "%s-glycan-compositions.txt" % (view.analysis.name)
            path = safepath(g.manager.get_temp_path(file_name))
            composition_keys = {c.composition.id: c.composition for c in snapshot.glycan_chromatograms}
            compositions = [
                view.session.query(GlycanComposition).get(key) for key in composition_keys
            ]
            with open(path, 'wb') as handle:
                ImportableGlycanHypothesisCSVSerializer(handle, compositions).start()
    return [file_name]
Beispiel #7
0
def download_multiple_files():
    filenames = request.values.getlist("filenames[]")
    good_names = []
    for name in filenames:
        path = resolve_file_name(name)
        if os.path.exists(path):
            good_names.append(path)
        else:
            g.add_message("Could not locate file %r" % (str(name), ))
    archive_name = request.values.get("download_name", None)
    if archive_name is None:
        archive_name = form_cleaners.get_random_string()
    archive_name += ".zip"
    archive_path = resolve_file_name(archive_name)
    with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED,
                         True) as zip_handle:
        for path in good_names:
            zip_handle.write(path, os.path.basename(path))
    return jsonify(filename=archive_name)
def download_multiple_files():
    filenames = request.values.getlist("filenames[]")
    good_names = []
    for name in filenames:
        path = resolve_file_name(name)
        if os.path.exists(path):
            good_names.append(path)
        else:
            g.add_message("Could not locate file %r" % (str(name), ))
    archive_name = request.values.get("download_name", None)
    if archive_name is None:
        archive_name = form_cleaners.get_random_string()
    archive_name += ".zip"
    archive_path = resolve_file_name(archive_name)
    with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED,
                         True) as zip_handle:
        for path in good_names:
            if os.path.isfile(path):
                zip_handle.write((path), os.path.basename(path))
            elif os.path.isdir(path):
                base = os.path.basename(path)
                zip_handle.write(path, base)
                for dirpath, dirnames, filenames in os.walk(path):
                    for name in sorted(dirnames):
                        zip_handle.write((os.path.join(dirpath, name)),
                                         os.path.join(base, dirpath, name))
                    for name in filenames:
                        try:
                            zip_handle.write((os.path.join(dirpath, name)),
                                             os.path.join(base, dirpath, name))
                        except (IOError, OSError):
                            zip_handle.write(
                                safepath(os.path.join(dirpath, name)),
                                os.path.join(base, dirpath, name))
            else:
                print("Unknown name type", path)
    return jsonify(filename=archive_name)
Beispiel #9
0
def build_glycan_search_space_process():
    data = request.values
    custom_reduction_type = data.get("custom-reduction-type")
    custom_derivatization_type = data.get("custom-derivatization-type")

    has_custom_reduction = custom_reduction_type != ""
    has_custom_derivatization = custom_derivatization_type != ""

    reduction_type = data.get("reduction-type")
    derivatization_type = data.get("derivatization-type")

    hypothesis_name = data.get("hypothesis-name")
    hypothesis_name = g.manager.make_unique_hypothesis_name(hypothesis_name)

    secure_name = secure_filename(hypothesis_name if hypothesis_name is not None else "glycan_database")
    storage_path = g.manager.get_hypothesis_path(re.sub(r"[\s\(\)]", "_", secure_name)) + '_glycan_%s.database'
    storage_path = make_unique_name(storage_path)
    touch_file(storage_path)

    if reduction_type in ("", "native"):
        reduction_type = None
    if derivatization_type in ("", "native"):
        derivatization_type = None

    try:
        reduction_type = validate_reduction(None, reduction_type)
    except Exception:
        g.manager.add_message(Message("Could not validate reduction type %r" % reduction_type, 'update'))
        return Response("Task Not Scheduled")
    try:
        derivatization_type = validate_derivatization(None, derivatization_type)
    except Exception:
        g.manager.add_message(Message("Could not validate derivatization type %r" % derivatization_type, 'update'))
        return Response("Task Not Scheduled")

    selected_method = data.get("selected-method", 'combinatorial')

    # Construct the argument set for a BuildCombinatorialGlycanHypothesis Task.
    # This involves building a StringIO object buffer which contains the user's
    # specified rules.
    if selected_method == "combinatorial":
        comb_monosaccharide_name = data.getlist('monosaccharide_name')[:-1]
        comb_lower_bound = map(intify, data.getlist('monosaccharide_lower_bound')[:-1])
        comb_upper_bound = map(intify, data.getlist('monosaccharide_upper_bound')[:-1])

        comb_monosaccharide_name, comb_lower_bound, comb_upper_bound = remove_empty_rows(
            comb_monosaccharide_name, comb_lower_bound, comb_upper_bound)

        constraint_lhs = data.getlist("left_hand_side")[:-1]
        constraint_op = data.getlist("operator")[:-1]
        constraint_rhs = data.getlist("right_hand_side")[:-1]

        constraints = zip(*remove_empty_rows(constraint_lhs, constraint_op, constraint_rhs))
        rules = zip(comb_monosaccharide_name, comb_lower_bound, comb_upper_bound)
        # File-like object to pass to the task in place of a path to a rules file
        rules_buffer = _serialize_rules_to_buffer(rules, constraints, "generated")

        task = BuildCombinatorialGlycanHypothesis(
            rules_buffer, storage_path,
            reduction=custom_reduction_type if has_custom_reduction else reduction_type,
            derivatization=custom_derivatization_type if has_custom_derivatization else derivatization_type,
            name=hypothesis_name,
            callback=lambda: 0, user=g.user
        )
        g.add_task(task)
    # Construct the argument set for a BuildTextFileGlycanHypothesis Task.
    elif selected_method == "text-file":
        glycan_list_file = request.files["glycan-list-file"]
        secure_glycan_list_file = g.manager.get_temp_path(secure_filename(glycan_list_file.filename))
        glycan_list_file.save(secure_glycan_list_file)
        task = BuildTextFileGlycanHypothesis(
            secure_glycan_list_file,
            storage_path,
            reduction=custom_reduction_type if has_custom_reduction else reduction_type,
            derivatization=custom_derivatization_type if has_custom_derivatization else derivatization_type,
            name=hypothesis_name,
            callback=lambda: 0, user=g.user)
        g.add_task(task)
    elif selected_method == "pregenerated":
        # include_human_n_glycan = data.get("glycomedb-human-n-glycan")
        # include_human_o_glycan = data.get("glycomedb-human-o-glycan")
        # include_mammalian_n_glycan = data.get("glycomedb-mammlian-n-glycan")
        # include_mammalian_o_glycan = data.get("glycomedb-mammlian-o-glycan")

        g.manager.add_message(Message("This method is not enabled at this time", 'update'))
        return Response("Task Not Scheduled")
    # Not yet implemented
    elif selected_method == "merge-hypotheses":
        id_1 = data.get("merged-hypothesis-1", 0)
        id_2 = data.get("merged-hypothesis-2", 0)

        if id_1 == 0 or id_2 == 0 or id_1 == id_2:
            g.add_message(Message("Two different hypotheses must be selected to merge."))
            return Response("Task Not Scheduled")

        rec_1 = g.manager.hypothesis_manager.get(id_1)
        rec_2 = g.manager.hypothesis_manager.get(id_2)

        # g.add_message(Message("Not yet implemented."))
        # return Response("Task Not Scheduled")
        task = MergeGlycanHypotheses(
            g.manager.connection_bridge, [(rec_1.path, rec_1.id), (rec_2.path, rec_2.id)], name=hypothesis_name,
            callback=lambda: 0, user=g.user)
        g.add_task(task)
    else:
        g.add_message(Message("This method is not recognized: \"%s\"" % (selected_method,), 'update'))
        return Response("Task Not Scheduled")

    return Response("Task Scheduled")