Mercurial > repos > bimib > marea_2_0
changeset 255:9d85c019db24 draft
Uploaded
author | luca_milaz |
---|---|
date | Mon, 08 Jul 2024 15:42:14 +0000 |
parents | 12b5f2e957c8 |
children | 883d5966a092 |
files | marea_2_0/flux_sampling.py marea_2_0/local/COBRA models/ENGRO2.xml marea_2_0/marea.xml marea_2_0/model_generator.py marea_2_0/model_generator.xml marea_2_0/ras_generator.xml marea_2_0/rps_generator.xml marea_2_0/utils/general_utils.py marea_2_0/utils/model_generator.py |
diffstat | 7 files changed, 61 insertions(+), 166 deletions(-) [+] |
line wrap: on
line diff
--- a/marea_2_0/flux_sampling.py Mon Jul 08 15:17:17 2024 +0000 +++ b/marea_2_0/flux_sampling.py Mon Jul 08 15:42:14 2024 +0000 @@ -31,8 +31,11 @@ type = str, required = True, help = 'your tool directory') - - + + + + + parser.add_argument('-in', '--input', required = True, type=str, @@ -150,9 +153,9 @@ def model_sampler(model_input:str, model_name:str)-> List[pd.DataFrame]: - model = load_custom_model( - utils.FilePath.fromStrPath(model_input), utils.FilePath.fromStrPath(model_name).ext) - + model_type = utils.Model.Custom + model = model_type.getCOBRAmodel(customPath = utils.FilePath.fromStrPath(model_input), customExtension = utils.FilePath.fromStrPath(model_name).ext) + utils.logWarning( "Sampling model: " + model_name, ARGS.out_log) @@ -207,34 +210,6 @@ df_quantiles.index = [model_name] return df_mean, df_median, df_quantiles - - -################################- INPUT DATA LOADING -################################ -def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model: - """ - Loads a custom model from a file, either in JSON or XML format. - - Args: - file_path : The path to the file containing the custom model. - ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour. - - Raises: - DataErr : if the file is in an invalid format or cannot be opened for whatever reason. - - Returns: - cobra.Model : the model, if successfully opened. - """ - ext = ext if ext else file_path.ext - try: - if ext is utils.FileFormat.XML: - return cobra.io.read_sbml_model(file_path.show()) - - if ext is utils.FileFormat.JSON: - return cobra.io.load_json_model(file_path.show()) - - except Exception as e: raise utils.DataErr(file_path, e.__str__()) - raise utils.DataErr(file_path, - f"Fomat \"{file_path.ext}\" is not recognized, only JSON and XML files are supported.") ############################# main ########################################### def main() -> None:
--- a/marea_2_0/model_generator.py Mon Jul 08 15:17:17 2024 +0000 +++ b/marea_2_0/model_generator.py Mon Jul 08 15:42:14 2024 +0000 @@ -54,8 +54,12 @@ parser.add_argument('-ot', '--output_type', type = str, required = True, + help = 'output type')รน + + parser.add_argument('-of', '--output_model_format', + type = str, + required = True, help = 'output type') - ARGS = parser.parse_args() return ARGS @@ -79,8 +83,39 @@ dataset.to_csv(ARGS.output_folder + name + ".csv", sep = '\t', index = keep_index) -def generate_model(cell_name, ras, medium): - # compute FVA +def generate_model(model, cell_name, ras, medium, output_model_format)->cobra.: + model_new = model.copy() + rxns_ids = [] + for rxn in model.reactions: + rxns_ids.append(rxn.id) + for reaction in medium.keys(): + if(medium[reaction] != None): + model_new.reactions.get_by_id(reaction).lower_bound=-float(medium[reaction]) + df_FVA = cobra.flux_analysis.flux_variability_analysis(model_new,fraction_of_optimum=0,processes=1).round(8) + for reaction in rxns_ids: + model_new.reactions.get_by_id(reaction).lower_bound=float(df_FVA.loc[reaction,"minimum"]) + model_new.reactions.get_by_id(reaction).upper_bound=float(df_FVA.loc[reaction,"maximum"]) + + for reaction in rxns_ids: + if reaction in ras.keys(): + lower_bound=model_new.reactions.get_by_id(reaction).lower_bound + upper_bound=model_new.reactions.get_by_id(reaction).upper_bound + valMax=float((upper_bound)*ras[reaction]) + valMin=float((lower_bound)*ras[reaction]) + if upper_bound!=0 and lower_bound==0: + model_new.reactions.get_by_id(reaction).upper_bound=valMax + if upper_bound==0 and lower_bound!=0: + model_new.reactions.get_by_id(reaction).lower_bound=valMin + if upper_bound!=0 and lower_bound!=0: + model_new.reactions.get_by_id(reaction).lower_bound=valMin + model_new.reactions.get_by_id(reaction).upper_bound=valMax + return model_new + + if(output_model_format == "SBML"): + cobra.io.write_sbml_model(model_new, ARGS.output_folder + cell_name+ "/" + cell_name + ".xml") + else: + cobra.io.save_json_model(model_new, ARGS.output_folder + cell_name+ "/" + cell_name + ".json") + pass @@ -106,17 +141,20 @@ ras = pd.read_table(ARGS.input_ras, header=0, sep=r'\s+', index_col = 0).T ras.replace("None", None, inplace=True) + ras = ras.astype(float) #medium has rows cells and columns medium reactions, not common reactions set to None medium = pd.read_csv(ARGS.input_medium, sep = '\t', header = 0, engine='python', index_col = 0) + medium = ras.astype(float) model_type :utils.Model = ARGS.model_selector if model_type is utils.Model.Custom: model = model_type.getCOBRAmodel(customPath = utils.FilePath.fromStrPath(ARGS.model), customExtension = utils.FilePath.fromStrPath(ARGS.model_name).ext) else: model = model_type.getCOBRAmodel(toolDir=ARGS.tool_dir) - '''for index, row in ras.iterrows(): #iterate over cells RAS - generate_model(index, row, medium.loc[index])''' + + for index, row in ras.iterrows(): #iterate over cells RAS + generate_model(model, index, row, medium.loc[index], ARGS.output_model_format) pass
--- a/marea_2_0/model_generator.xml Mon Jul 08 15:17:17 2024 +0000 +++ b/marea_2_0/model_generator.xml Mon Jul 08 15:42:14 2024 +0000 @@ -18,6 +18,7 @@ --input_medium $input_medium --input_ras $input_ras --output_type "${",".join(map(str, $output_types))}" + --output_model_format $output_model_format --out_log $log #if $cond_model.model_selector == 'Custom' --model $model @@ -38,12 +39,18 @@ <param name="input_medium" argument="--input_medium" multiple="false" type="data" format="tabular, csv, tsv" label="Medium:"/> - <param type="select" argument="--output_types" multiple="true" name="output_types" label="Desired outputs"> + + <param type="select" argument="--output_types" multiple="true" name="output_types" label="Desired outputs:"> <option value="FBA" selected="false">FBA</option> <option value="pFBA" selected="false">pFBA</option> <option value="FVA" selected="false">FVA</option> <option value="sensitivity" selected="false">Sensitivity knock-out</option> </param> + + <param type="select" argument="--output_model_format" multiple="false" name="output_model_format" label="Desired output model format:"> + <option value="SBML" selected="true">SBML</option> + <option value="JSON" selected="false">JSON</option> + </param> </inputs>
--- a/marea_2_0/ras_generator.xml Mon Jul 08 15:17:17 2024 +0000 +++ b/marea_2_0/ras_generator.xml Mon Jul 08 15:42:14 2024 +0000 @@ -9,6 +9,7 @@ <requirement type="package" version="4.6.3">lxml</requirement> <requirement type="package" version="1.1.0">svglib</requirement> <requirement type="package" version="3.5.67">reportlab</requirement> + <requirement type="package" version="0.29.0">cobra</requirement> </requirements> <command detect_errors="exit_code"> <![CDATA[
--- a/marea_2_0/rps_generator.xml Mon Jul 08 15:17:17 2024 +0000 +++ b/marea_2_0/rps_generator.xml Mon Jul 08 15:42:14 2024 +0000 @@ -7,6 +7,7 @@ <requirement type="package" version="0.25.3">pandas</requirement> <requirement type="package" version="4.6.3">lxml</requirement> <requirement type="package" version="1.21.6">numpy</requirement> + <requirement type="package" version="0.29.0">cobra</requirement> </requirements> <command detect_errors="exit_code"> <![CDATA[
--- a/marea_2_0/utils/general_utils.py Mon Jul 08 15:17:17 2024 +0000 +++ b/marea_2_0/utils/general_utils.py Mon Jul 08 15:42:14 2024 +0000 @@ -553,7 +553,6 @@ if(self is Model.Custom): return self.load_custom_model(customPath, customExtension) else: - (model, errors) = cobra.io.validate_sbml_model(FilePath(f"{self.name}", FileFormat.XML, prefix = f"{toolDir}/local/COBRA models/").show()) return cobra.io.read_sbml_model(FilePath(f"{self.name}", FileFormat.XML, prefix = f"{toolDir}/local/COBRA models/").show()) def load_custom_model(self, file_path :FilePath, ext :Optional[FileFormat] = None) -> cobra.Model:
--- a/marea_2_0/utils/model_generator.py Mon Jul 08 15:17:17 2024 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,126 +0,0 @@ -import argparse -import utils.general_utils as utils -from typing import Optional, List -import os -import numpy as np -import pandas as pd -import cobra -from joblib import Parallel, delayed, cpu_count -import sys - -################################# process args ############################### -def process_args(args :List[str]) -> argparse.Namespace: - """ - Processes command-line arguments. - - Args: - args (list): List of command-line arguments. - - Returns: - Namespace: An object containing parsed arguments. - """ - parser = argparse.ArgumentParser(usage = '%(prog)s [options]', - description = 'process some value\'s') - - parser.add_argument( - '-ms', '--model_selector', - type = utils.Model, default = utils.Model.ENGRO2, choices = [utils.Model.ENGRO2, utils.Model.Custom], - help = 'chose which type of model you want use') - - parser.add_argument("-mo", "--model", type = str, - help = "path to input file with custom rules, if provided") - - parser.add_argument("-mn", "--model_name", type = str, help = "custom mode name") - - parser.add_argument('-ol', '--out_log', - help = "Output log") - - parser.add_argument('-td', '--tool_dir', - type = str, - required = True, - help = 'your tool directory') - - - parser.add_argument('-im', '--input_medium', - required = True, - type=str, - help = 'input medium') - - parser.add_argument('-ir', '--input_ras', - required = True, - type=str, - help = 'input ras') - - parser.add_argument('-ot', '--output_type', - type = str, - required = True, - help = 'output type') - - ARGS = parser.parse_args() - return ARGS - -########################### warning ########################################### -def warning(s :str) -> None: - """ - Log a warning message to an output log file and print it to the console. - - Args: - s (str): The warning message to be logged and printed. - - Returns: - None - """ - with open(ARGS.out_log, 'a') as log: - log.write(s + "\n\n") - print(s) - - -def write_to_file(dataset: pd.DataFrame, name: str, keep_index:bool=False)->None: - dataset.to_csv(ARGS.output_folder + name + ".csv", sep = '\t', index = keep_index) - - -def generate_model(cell_name, ras, medium): - # compute FVA - pass - - -############################# main ########################################### -def main() -> None: - """ - Initializes everything and sets the program in motion based on the fronted input arguments. - - Returns: - None - """ - if not os.path.exists('model_generator'): - os.makedirs('model_generator') - - num_processors = cpu_count() - - global ARGS - ARGS = process_args(sys.argv) - - ARGS.output_folder = 'model_generator/' - - ARGS.output_types = ARGS.output_type.split(",") - - ras = pd.read_table(ARGS.input_ras, header=0, sep=r'\s+', index_col = 0).T - ras.replace("None", None, inplace=True) - - #medium has rows cells and columns medium reactions, not common reactions set to None - medium = pd.read_csv(ARGS.input_medium, sep = '\t', header = 0, engine='python', index_col = 0) - - model_type :utils.Model = ARGS.model_selector - if model_type is utils.Model.Custom: - model = model_type.getCOBRAmodel(utils.FilePath.fromStrPath(ARGS.model_name), utils.FilePath.fromStrPath(ARGS.model_name).ext) - else: - model = model_type.getCOBRAmodel() - - '''for index, row in ras.iterrows(): #iterate over cells RAS - generate_model(index, row, medium.loc[index])''' - - pass - -############################################################################## -if __name__ == "__main__": - main() \ No newline at end of file