Skip to content

Commit

Permalink
last updates
Browse files Browse the repository at this point in the history
  • Loading branch information
alegiac95 committed Jan 9, 2022
1 parent cdedf1d commit 3b013ec
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 85 deletions.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,12 @@ import imaging_transcriptomics as imt
my_data = np.ones(41) # MUST be of size 41
# (corresponds to the regions in left hemisphere of the DK atlas)

analysis = imt.ImagingTranscriptomics(my_data, n_components=1)
analysis.run()
analysis = imt.ImagingTranscriptomics(my_data, method="pls", n_components=1,
regions="cort+sub")
analysis.run(gsea=False)
# If instead of running PLS you want to analysze the data with correlation you can run the analysis with:
analysis.run(method="corr")
analysis = imt.ImagingTranscriptomics(my_data, method="corr",
regions="cort+sub")
```

Once completed the results will be part of the `analysis` object and can be accessed with `analysis.gene_results`.
Expand Down
2 changes: 1 addition & 1 deletion imaging_transcriptomics/pls.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def print_table(self):
def save_results(self, outdir=None):
"""Save the results of the PLS regression.
:param oudtir: output directory.
:param outdir: output directory.
"""
assert isinstance(self.gene_results.results, PLSGenes)
for i in range(self.n_components):
Expand Down
134 changes: 53 additions & 81 deletions imaging_transcriptomics/reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,53 +14,6 @@
from .transcriptomics import ImagingTranscriptomics


class PDF(FPDF):
"""Class to generate a PDF report for the imaging-transcriptomics script"""

def header(self):
"""The header will contain always the title."""
self.rect(10, 10, 190, 280)
self.line(10, 50, 200, 50)
self.set_font("Helvetica", "B", 14)
self.cell(
w=0, h=15, align="C",
txt="Imaging Transcriptomics Analysis Report", ln=True
)

def analysis_info(self, filename, date, filepath):
"""Info on the analysis performed. Information included are the name of
the scan of the input, date of the analysis and the original path of the scan.
:param filename: name of the scan used for analysis.
:param date: date when the analysis was performed.
:param filepath: absolute path of the imaging scan used for analysis.
"""
self.set_font("Courier", "", 10)
self.cell(w=100, h=8, align="L", txt=f" Scan Name: {filename}")
self.cell(w=100, h=8, align="L", txt=f" Date: {date}", ln=True)
self.cell(w=100, h=10, align="L", txt=f" File Path: {filepath}")

def pls_regression(self, path_plots):
"""Include the plots of the pls components.
:param path_plots: path where the .png plots are located.
"""
self.ln(20)
self.set_font("Helvetica", "BU", 12)
self.cell(w=0, h=10, align="L", txt="-PLS Regression")
self.ln(10)
self.image(Path(path_plots) / "individual_variance.png", x=15, w=120)
self.image(Path(path_plots) / "cumulative_variance.png", x=15, w=120)

def reproducibility_line(self, cli_commands, version):
"""Create a string with the command used from the command line to run the analysis.
:param cli_commands: commands given in the cli to run the analysis.
:param version: version of the software used to run the analysis.
"""
pass


@CheckPath
def make_folder(path, folder_name: str):
"""Create a folder based on path and name to use.
Expand Down Expand Up @@ -121,40 +74,15 @@ def make_plots(path, limit_x, data_y):
plt.bar(range(1, 16), 100 * data_y, color="sandybrown")
for index, value in enumerate(data_y):
plt.text(index + 0.5, 100 * value, "{:.1f}".format(100 * value))
plt.xlabel("PLS components")
plt.title("Individual variance explained by PLS components")
plt.xlabel("PLS component")
plt.ylabel("Variance (%)")
plt.savefig(path / "individual_variance.png", dpi=1200)
plt.close()
return


def create_pdf(filepath, save_dir):
"""Create a PDF report.
Creates a report for the imaging transcriptomics analysis with some plots and details of what was run by the user.
:param filepath: path of the image used for analysis.
:param save_dir: path where to save the report (same as where the plots are located).
"""
if not isinstance(filepath, Path):
filepath = Path(filepath)
analysis_date = datetime.now().strftime("%d-%m-%Y")

report = PDF(orientation="P", unit="mm", format="A4")
report.add_page()
report.analysis_info(filename=filepath.name, date=analysis_date,
filepath=filepath)
report.pls_regression(path_plots=save_dir)
report.output(save_dir / "Report.pdf", "F")


"""
def reorder_data(data):
"""Reorder the data from the DK convention to the ENIGMA convention for
plotting.
:param np.ndarray data: Data in the Desikan-Killiany convention. This
array should contain at least all the ROIs of the left brain hemisphere.
"""
# Indexes to match the abagen (DK) order to the enigma
enigma_index = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20,
Expand Down Expand Up @@ -196,12 +124,56 @@ def make_surface_plots(data, save_dir):
transparent_bg=True
)
plot_subcortical(array_name=data_subcortical,)


def make_pdf():
"""


def pls_components(data):
"""Return a string with the number of components, its cumulative
variance and its p value from the analysis."""
if not isinstance(data, ImagingTranscriptomics):
raise TypeError("The data must be an ImagingTranscriptomics object.")
n_components = data.analysis.n_components
res_str = "PLS Component: R2 pval "
for i in range(n_components):
res_str += f"PLS {i+1}: " \
f"{data.analysis.r2[i]:.3f}" \
f" {data.analysis.p_val[i]:.4f}"
return res_str


def make_pdf(transcriptomics_data, save_dir, name="report", scanname="", ):
if not isinstance(transcriptomics_data, ImagingTranscriptomics):
raise TypeError("The data must be an ImagingTranscriptomics object.")
save_dir = Path(save_dir)
WIDTH = 210 # mm
HEIGHT = 297 # mm
MARGIN = 5 # mm
report = PDF(orientation="P", unit="mm", format="A4")

pass
report = FPDF(orientation="P", unit="mm", format="A4")
report.set_font("Arial", size=11)
report.add_page()
# Header
report.image(str(Path(__file__).parent / "resources" / "header.png"),
x=0, y=0, w=WIDTH)
# Info on the analysis
analysis_date = datetime.now().strftime("%d-%m-%Y")
report.ln(25)
report.cell(WIDTH/2, txt=f"Scan name: {scanname}")
report.cell(WIDTH/2, txt=f"Analysis date:{analysis_date}")
# PLS plots
if transcriptomics_data.method == "pls":
report.ln(10)
make_plots(save_dir,
transcriptomics_data.analysis.n_components,
transcriptomics_data.analysis.components_var)
report.cell(WIDTH, txt="PLS Analysis")
report.image(str(save_dir / "individual_variance.png"),
x=MARGIN, y=53, w=WIDTH/2)
report.image(str(save_dir / "cumulative_variance.png"),
x=WIDTH/2 + MARGIN, y=53, w=WIDTH/2)
report.ln(90)
report.cell(WIDTH, txt=pls_components(transcriptomics_data))
# MAKE GENE RESULTS TABLE
report.ln(80)
report.cell(WIDTH, txt="For the gene results refer to the spreadsheet in "
"the report folder.")
report.output(str(save_dir / f"{name}.pdf"), "F")
Binary file added imaging_transcriptomics/resources/header.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions imaging_transcriptomics/resources/header.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions imaging_transcriptomics/script/imagingtranscriptomics.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ def main():
gene_set=geneset,
n_cpu=n_cpu)
# PLOTTING and PDF creation
imt.reporting.make_pdf(transcriptomics_data=transcriptomics,
save_dir=Path(outdir) / f"Imt_{input_name}_"
f"{transcriptomics.method}",
name=str(input_name),
scanname=str(infile.name))


if __name__ == "__main__":
Expand Down

0 comments on commit 3b013ec

Please sign in to comment.