diff --git a/.gitignore b/.gitignore
index 736c73a..68286a5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,13 +1,4 @@
-site/
code/__pycache__/
-
-# PyInstaller portable-build artifacts (see build/mpact.spec, devnotes.md).
-# dist/ and build/mpact/ are generated by `pyinstaller build/mpact.spec`;
-# build/.buildvenv/ is the throwaway venv build_windows.bat creates.
-dist/
-build/mpact/
-build/.buildvenv/
-
code/__pycache__/stats.cpython-39.pyc
code/__pycache__/plotting.cpython-39.pyc
code/__pycache__/MSFaST.cpython-39.pyc
@@ -26,26 +17,456 @@ code/__pycache__/files.cpython-39.pyc
code/__pycache__/files_rc.cpython-38.pyc
code/__pycache__/files_rc.cpython-39.pyc
code/__pycache__/main.cpython-38.pyc
+code/__pycache__/main.cpython-39.pyc
code/__pycache__/plotting.cpython-38.pyc
+code/__pycache__/plotting.cpython-39.pyc
+code/__pycache__/stats.cpython-39.pyc
code/__pycache__/ui_featureinfo.cpython-38.pyc
code/__pycache__/ui_featureinfo.cpython-39.pyc
code/__pycache__/ui_functions.cpython-38.pyc
code/__pycache__/ui_main.cpython-38.pyc
code/__pycache__/ui_main.cpython-39.pyc
code/__pycache__/ui_plotparam.cpython-39.pyc
-code/compoundimages/*.png
+code/compoundimages/(+)-5(6),13-halimadiene-15-ol.png
+code/compoundimages/(+)-caryolan-1-ol.png
+code/compoundimages/(+)-discoipyrrole A.png
+code/compoundimages/(-)-7-Geranylindolactam V.png
+code/compoundimages/(-)-Neoverrucosan-5beta-ol.png
+code/compoundimages/(-)-Verrucosan-2beta-ol.png
+code/compoundimages/(1S,3aR)-jadomycin V.png
+code/compoundimages/(2E,4E)-7-methylocta-2,4-dienoic acid amide.png
+code/compoundimages/(2S,3S)-3-Hydroxy-1,4-diphenylbutan-2-yl-acetate.png
+code/compoundimages/(5R) 5-hydroxy-3-\[\[2-(4-hydroxyphenyl)ethyl\]amino\]-5-vinyl-2-cyclopenten-1-one.png
+code/compoundimages/(5S,S)-5-methyl-3-(2-methylbutyl)furan-2(5H)-one.png
+code/compoundimages/(5S,S)-5-methyl-3-(3-methylpentyl)furan-2(5H)-one.png
+code/compoundimages/(E)-12-methyltridec-3-enenitrile.png
+code/compoundimages/(E)-ethyl 8-oxooctadec-9-enoate.png
+code/compoundimages/(E)-tetradec-3-enenitrile.png
+code/compoundimages/(S)-N-tetradecanoyl-HSL.png
+code/compoundimages/(Z)-12-methyltridec-3-enenitrile.png
+code/compoundimages/(Z)-15-Methylhexadec-10-en-2-one.png
+code/compoundimages/(Z)-octadec-11-enenitrile.png
+code/compoundimages/(Z)-tetradec-3-enenitrile.png
+code/compoundimages/(Z)-tetradec-7-enenitrile.png
+code/compoundimages/-L-glutamyl-L-leucine.png
+code/compoundimages/1 '- (beta- Glucopyranosyloxy) di- O-demethylspirilloxan thin.png
+code/compoundimages/1'-beta-glucopyranosyl-3,4,3',4'-tetradehydro-1', 2'-dihydro-beta,psi-caroten-2-one.png
+code/compoundimages/1,4-dihydroxy-2,5-dimethoxy-9,10-anthraquinone.png
+code/compoundimages/1-hydroxymethylindole-3-carboxylic acid.png
+code/compoundimages/1-methyl-pseudouridine.png
+code/compoundimages/1-methylthio-2,3-di-O-(3',7',11',15'-tetramethylhexadecyl)glycerol (diphytanylglyceryl methylthioether).png
+code/compoundimages/10,15-dihydroxyamorph-4-en-3-one.png
+code/compoundimages/12-Deoxy-deoxysaxitoxin.png
+code/compoundimages/12-hydroxy-13-butoxyethoxyfumitremorgin B.png
+code/compoundimages/16-methyloxazolomycin.png
+code/compoundimages/17-Methylenespiramycin.png
+code/compoundimages/17-O-ethylnotoamide M.png
+code/compoundimages/18-methyltacrolimus.png
+code/compoundimages/2-(2-carboxyethyl)-8-hydroxyquinazolin-4(3H)-one.png
+code/compoundimages/2-(furan-2-yl)-6-(2S,3S,4-trihydroxybutyl)pyrazine.png
+code/compoundimages/2-(Heptadecyl)-3,6-dihydroxy-1,4-benzoquinone.png
+code/compoundimages/2-amino-4-methoxy-5-cyanopyrrolo\[2,3-d\]pyrimidine.png
+code/compoundimages/2-amino-6-hydroxyphenoxazin-3-one.png
+code/compoundimages/2-Demethylmonensin B.png
+code/compoundimages/2-ethyl-7-hydroxy-6,7-dihydro-5H-indolizin-3-one.png
+code/compoundimages/23-(6-methyl)heptanoic acid demalonylazalomycin F3a ester.png
+code/compoundimages/3-hydroxydehydrodaidzein.png
+code/compoundimages/3-Isobutylpropanamide-2-cyclopenten-1-one.png
+code/compoundimages/3-N-formyl- holyrine A.png
+code/compoundimages/4,5-dihydroxy-7-methylphthalide.png
+code/compoundimages/4-\[2-O-9Z-hexadecenoyl--glucopyranosyl\]-4,4-diapolycopene-4,4-dioic acid.png
+code/compoundimages/4-desmethylepothilone D.png
+code/compoundimages/4-methoxy-3H-isobenzofuran-1-one.png
+code/compoundimages/4-quinolinecarboxylic acid.png
+code/compoundimages/41-Demethylhomooligomycin B.png
+code/compoundimages/5'-deoxyguanosine.png
+code/compoundimages/5,18-dedihydroxycyclooctatin.png
+code/compoundimages/5,7,3',4'-Tetrahydroxy-8-methylisoflavon.png
+code/compoundimages/5-Hydroxy-3-(1-hydroxy-2-methylbutyl)-4-methyl-2(5H)-furanone.png
+code/compoundimages/5-hydroxydeoxyvasicinone.png
+code/compoundimages/6-acetylphenazine-1-carboxylic acid.png
+code/compoundimages/6-deoxyerythronolide B.png
+code/compoundimages/6-Hydroxysordarin.png
+code/compoundimages/7-Hydroxy-8,16-dimethyl-9-octadecenoic acid.png
+code/compoundimages/7-Tetradecenoic acid.png
+code/compoundimages/8,9-dihydrolactimidomycin.png
+code/compoundimages/8-desmethoxy-isomigrastatin.png
+code/compoundimages/8-hydroxy-8,9-dihydrolactidomycin.png
+code/compoundimages/\[D-Asp, Dhb^7\]microcystin-LR.png
+code/compoundimages/\[D-Asp3,Ser7\]MC-LR.png
+code/compoundimages/Abenquine B2.png
+code/compoundimages/Abenquine C.png
+code/compoundimages/Abyssomicin C.png
+code/compoundimages/Abyssomicin P.png
+code/compoundimages/Acidiphilamide C.png
+code/compoundimages/Actiketal.png
+code/compoundimages/Actinoallolide D.png
+code/compoundimages/Actinoramide E.png
+code/compoundimages/AHB-6-Methylneamine.png
+code/compoundimages/AI-77-F.png
+code/compoundimages/Albatrelin F.png
+code/compoundimages/Albogrisin B.png
+code/compoundimages/Albucyclone A.png
+code/compoundimages/Albumycin.png
+code/compoundimages/Aldgamycin E.png
+code/compoundimages/Aldgamycin I.png
+code/compoundimages/Aldgamycin K.png
+code/compoundimages/Alokicenone C.png
+code/compoundimages/AM-2604 A.png
+code/compoundimages/Amphibactin T.png
+code/compoundimages/Amycolatopsin C.png
+code/compoundimages/Ananstrep C.png
+code/compoundimages/AnhydroSEK4b.png
+code/compoundimages/Antarlide F.png
+code/compoundimages/Antascomicin B.png
+code/compoundimages/Antascomicin E.png
+code/compoundimages/Antillatoxin.png
+code/compoundimages/Aquayamycin.png
+code/compoundimages/Argimicin B.png
+code/compoundimages/Arthripenoid B.png
+code/compoundimages/Ashimide B.png
+code/compoundimages/Aspergilone A.png
+code/compoundimages/Asterobactin B.png
+code/compoundimages/Azicemicin A.png
+code/compoundimages/Bacillamidin G.png
+code/compoundimages/Bacilysocin.png
+code/compoundimages/Bafilomycin C2.png
+code/compoundimages/Bafilomycin G.png
+code/compoundimages/Balgacyclamide C.png
+code/compoundimages/Bananamide 2.png
+code/compoundimages/Banegasine.png
+code/compoundimages/Bartoloside H.png
+code/compoundimages/Bartoloside I.png
+code/compoundimages/BE-10988.png
+code/compoundimages/BE-14106.png
+code/compoundimages/BE-32030A.png
+code/compoundimages/Benzastatin A.png
+code/compoundimages/Biphenomycin C.png
+code/compoundimages/Biseokeaniamide A.png
+code/compoundimages/Blastmycetin C.png
+code/compoundimages/Brasilibactin A.png
+code/compoundimages/Brasiliquinone C.png
+code/compoundimages/Brintonamide A.png
+code/compoundimages/Brintonamide B.png
+code/compoundimages/Caerulomycin G.png
+code/compoundimages/Caldorin.png
+code/compoundimages/Carboxymycobactin-7.png
+code/compoundimages/Cepafungin I.png
+code/compoundimages/Cephamycin C.png
+code/compoundimages/Chaiyaphumine D.png
+code/compoundimages/Chejuenolide A.png
+code/compoundimages/Chlorotonil B.png
+code/compoundimages/Chrondamide 12D.png
+code/compoundimages/Circumdatin D.png
+code/compoundimages/Cis-7-tetradecenoyl-D-asparagine.png
+code/compoundimages/Citreamicin alpha.png
+code/compoundimages/Citreo-g-pyrone.png
+code/compoundimages/Clavirolide A.png
+code/compoundimages/Coibacin C.png
+code/compoundimages/Columbamide B.png
+code/compoundimages/Concanamycin B.png
+code/compoundimages/Conglobatin.png
+code/compoundimages/Coronafacoyl-L-isoleucine.png
+code/compoundimages/Coronatine.png
+code/compoundimages/Cosmomycin A.png
+code/compoundimages/Crocagin A.png
+code/compoundimages/Cryptophycin-16.png
+code/compoundimages/Cryptophycin-38.png
+code/compoundimages/Cyanopeptolin 920.png
+code/compoundimages/Cyclo(D)-Pro-(D)-Leu.png
+code/compoundimages/Cyclo-(L-Ala-L-Tyr).png
+code/compoundimages/Cyclodysidin D.png
+code/compoundimages/Cylindrocyclophane C2.png
+code/compoundimages/Daryamide E.png
+code/compoundimages/Defumarylhygrolidin.png
+code/compoundimages/Dehydro tilivalline.png
+code/compoundimages/Dehydroxynocardamine.png
+code/compoundimages/Demethylblasticidin S.png
+code/compoundimages/Deoxynybomycin.png
+code/compoundimages/Desferrioxamine X4.png
+code/compoundimages/Desotamide A.png
+code/compoundimages/Desotamide C.png
+code/compoundimages/Desotamide G.png
+code/compoundimages/Diaphorin.png
+code/compoundimages/Dietziamide A.png
+code/compoundimages/Dihydromaltophilin.png
+code/compoundimages/Dioxolide A.png
+code/compoundimages/Diploptene.png
+code/compoundimages/DKxanthene 574.png
+code/compoundimages/Dokdolipid B.png
+code/compoundimages/Dolastatin 10.png
+code/compoundimages/Dragonamide D.png
+code/compoundimages/Eicosanedioic acid.png
+code/compoundimages/Emericellamide A.png
+code/compoundimages/Enniatin L.png
+code/compoundimages/Enniatin M1.png
+code/compoundimages/Epohelmin B.png
+code/compoundimages/Eponemycin.png
+code/compoundimages/Epothilone D.png
+code/compoundimages/Epothilone D1.png
+code/compoundimages/Epothilone I1.png
+code/compoundimages/Erythromycin G.png
+code/compoundimages/ethyl homononactyl homononactate.png
+code/compoundimages/Etrogol.png
+code/compoundimages/Eurystatin C.png
+code/compoundimages/F-Met I.png
+code/compoundimages/Flexirubin.png
+code/compoundimages/Fluvirucin B2.png
+code/compoundimages/Fluvirucin B6.png
+code/compoundimages/Fontonamide.png
+code/compoundimages/Formicamycin D.png
+code/compoundimages/FR-66979.png
+code/compoundimages/FR-900848.png
+code/compoundimages/Frenolicin G.png
+code/compoundimages/Fumaquinone.png
+code/compoundimages/Furaquinocin B.png
+code/compoundimages/Furaquinocin D.png
+code/compoundimages/Fusaricidin D.png
+code/compoundimages/Geralcin E.png
+code/compoundimages/GGL.3.png
+code/compoundimages/Glidobactin C.png
+code/compoundimages/Gln-Asp-Val-Leu.png
+code/compoundimages/Glomecidin.png
+code/compoundimages/Glycocinnasperimicin D.png
+code/compoundimages/Gobichelin B.png
+code/compoundimages/Griselimycin.png
+code/compoundimages/Guineamide C.png
+code/compoundimages/H2-6-Hydroxymethylpterin.png
+code/compoundimages/Halstoctacosanolide B.png
+code/compoundimages/Hapalindole D.png
+code/compoundimages/Heliomycin.png
+code/compoundimages/Hexadecanenitrile.png
+code/compoundimages/Hexose-palythine-serine.png
+code/compoundimages/Homorapamycin A.png
+code/compoundimages/Hoshinolactam.png
+code/compoundimages/IC-202-A.png
+code/compoundimages/Ilanefuranone.png
+code/compoundimages/Indigoidine.png
+code/compoundimages/Indisocin.png
+code/compoundimages/Indole-3-acetic acid methyl ester.png
+code/compoundimages/Inonotusic acid.png
+code/compoundimages/Iromycin C.png
+code/compoundimages/Isobongkrekic acid,.png
+code/compoundimages/Isobutyrylvalindomycin.png
+code/compoundimages/Isomalyngamide A.png
+code/compoundimages/Isorhizopodin.png
+code/compoundimages/Isotuberculosino.png
+code/compoundimages/Izenamide B.png
+code/compoundimages/JBIR-05.png
+code/compoundimages/JBIR-80.png
+code/compoundimages/Jomthonic acid E.png
+code/compoundimages/Juglomycin I.png
+code/compoundimages/Kalafungin.png
+code/compoundimages/Kalimantacin B.png
+code/compoundimages/Kandenol A.png
+code/compoundimages/Kijimicin.png
+code/compoundimages/Koreenceine A.png
+code/compoundimages/Koreenceine B.png
+code/compoundimages/Koreenceine C.png
+code/compoundimages/Korormicin K.png
+code/compoundimages/Kribelloside A.png
+code/compoundimages/Kribelloside B.png
+code/compoundimages/L--(3-hydroxyureido)-alanine.png
+code/compoundimages/Lactoquinomycin.png
+code/compoundimages/Lagunamide B.png
+code/compoundimages/Landomycin A.png
+code/compoundimages/Landomycin S.png
+code/compoundimages/Lentzeoside E.png
+code/compoundimages/Leptofuranin D.png
+code/compoundimages/Leualacin G.png
+code/compoundimages/Leupyrrin B2.png
+code/compoundimages/Leuseramycin.png
+code/compoundimages/Lipoamide C.png
+code/compoundimages/Lipstatin.png
+code/compoundimages/Lobarialide C.png
+code/compoundimages/Lobosamide C.png
+code/compoundimages/Lodopyridone.png
+code/compoundimages/Luminmide B.png
+code/compoundimages/Lutoside.png
+code/compoundimages/Lyngbyatoxin A.png
+code/compoundimages/Maculalactone K.png
+code/compoundimages/Maculalactone M.png
+code/compoundimages/Mandelalide A.png
+code/compoundimages/Mansouramycin D.png
+code/compoundimages/Maremycin D2.png
+code/compoundimages/Marformycin D.png
+code/compoundimages/Maridomycin III.png
+code/compoundimages/Marinactinone A.png
+code/compoundimages/Marinobactin-D1.png
+code/compoundimages/Martinomycin.png
+code/compoundimages/Matlystatin A.png
+code/compoundimages/Mer-WF3010.png
+code/compoundimages/Metacridamide A.png
+code/compoundimages/methyl 1-(methyl propionate)--carboline-3-carboxylate.png
+code/compoundimages/Microginin 576.png
+code/compoundimages/Microginin 91-A.png
+code/compoundimages/Microginin FR9.png
+code/compoundimages/Microtermolide A.png
+code/compoundimages/Milbemycin 10.png
+code/compoundimages/Milbemycin 26.png
+code/compoundimages/Minutissamide J.png
+code/compoundimages/MKN-004C.png
+code/compoundimages/Mohangic acid A.png
+code/compoundimages/Mohangic acid E.png
+code/compoundimages/Monactin.png
+code/compoundimages/Mupirocin F.png
+code/compoundimages/Mutaxanthene B.png
+code/compoundimages/Mycemycin A.png
+code/compoundimages/Mycemycin E.png
+code/compoundimages/Myxochromide S3.png
+code/compoundimages/Myxopyronin B.png
+code/compoundimages/Myxotyroside B.png
+code/compoundimages/N,N'-diisobutylurea.png
+code/compoundimages/N-Acetyl-tyramine.png
+code/compoundimages/N-carboxamido-staurosporine.png
+code/compoundimages/N-methylphloretamide.png
+code/compoundimages/N-Tetradecadienoyl-L-homoserine lactone.png
+code/compoundimages/Nai414-B.png
+code/compoundimages/Namalide C.png
+code/compoundimages/Namalide E.png
+code/compoundimages/Naphthacemycin B3.png
+code/compoundimages/Naphthgeranine A.png
+code/compoundimages/Neomacrophorin III.png
+code/compoundimages/Nevaltophin A.png
+code/compoundimages/Nigerapyrone H.png
+code/compoundimages/Nitrosoxacin C.png
+code/compoundimages/Nocapyrone R.png
+code/compoundimages/Nocardichelin B.png
+code/compoundimages/Nocardiopyrone A.png
+code/compoundimages/Nostopeptolide A3.png
+code/compoundimages/Nostopeptolide L3.png
+code/compoundimages/Nostophycin.png
+code/compoundimages/Not named.png
+code/compoundimages/NP-101A.png
+code/compoundimages/NW-G03.png
+code/compoundimages/Obscurolide-C2 methyl ester.png
+code/compoundimages/Octacyclomycin.png
+code/compoundimages/Odyverdiene B.png
+code/compoundimages/Okaramine H.png
+code/compoundimages/Oryzamide B.png
+code/compoundimages/Oscillamide B.png
+code/compoundimages/Oscillatoxin E.png
+code/compoundimages/Oxepinamide C.png
+code/compoundimages/Palmyrrolinone.png
+code/compoundimages/Panclicin E.png
+code/compoundimages/Panosialin C.png
+code/compoundimages/Paulomycin E.png
+code/compoundimages/PD-118576-A3.png
+code/compoundimages/Pepsatin Pr.png
+code/compoundimages/Pestabacillin B.png
+code/compoundimages/Phe+CO\[Lys+Val+Leu+MeHty+MetO\].png
+code/compoundimages/Phenalinolactone A.png
+code/compoundimages/Phenoxan.png
+code/compoundimages/Phenylbutenote.png
+code/compoundimages/Phenylnannolone A.png
+code/compoundimages/Phenylnannolone C.png
+code/compoundimages/Photopyrone A.png
+code/compoundimages/Phototemtide A.png
+code/compoundimages/Piericidin B5.png
+code/compoundimages/Pimprinol A.png
+code/compoundimages/Planktocyclin.png
+code/compoundimages/Planktopeptin BL843.png
+code/compoundimages/PM-toxin B.png
+code/compoundimages/Porpoisamide B.png
+code/compoundimages/Poststatin.png
+code/compoundimages/Pseudoaeruginosin NS1.png
+code/compoundimages/Pseudodestruxin A.png
+code/compoundimages/Psi-tectorigenin.png
+code/compoundimages/Psuedodestruxin C.png
+code/compoundimages/Pukeleimide E.png
+code/compoundimages/Pulicatin A.png
+code/compoundimages/Pyonitrin A.png
+code/compoundimages/Pyridindolol K2.png
+code/compoundimages/Pyridinopyrone C.png
+code/compoundimages/Pyrroindomycin B.png
+code/compoundimages/Qinimycin C.png
+code/compoundimages/Quinolobactin.png
+code/compoundimages/Rakicidin B.png
+code/compoundimages/Ralfuranone B.png
+code/compoundimages/Ralfuranone I.png
+code/compoundimages/Ralstonin B.png
+code/compoundimages/Rhabdopeptide 8.png
+code/compoundimages/Rhizomide B.png
+code/compoundimages/RHM2.png
+code/compoundimages/Rhodopeptin C1.png
+code/compoundimages/Rhodopeptin C4.png
+code/compoundimages/Ribocyclophane C.png
+code/compoundimages/Rifamycin Z.png
+code/compoundimages/RK-144171.png
+code/compoundimages/Roquefortine A.png
+code/compoundimages/Roseobacticide H.png
+code/compoundimages/Salinipostin D.png
+code/compoundimages/Salinosporamide I.png
+code/compoundimages/Sanglifehrin C.png
+code/compoundimages/Sarpeptin B.png
+code/compoundimages/SCH 38518.png
+code/compoundimages/Sch 39185.png
+code/compoundimages/Sclerolizine.png
+code/compoundimages/Semiplenamide F.png
+code/compoundimages/Serinolamides D.png
+code/compoundimages/Serratamolide C.png
+code/compoundimages/Serratamolide D.png
+code/compoundimages/Serratamolide E.png
+code/compoundimages/SF-1902-A3.png
+code/compoundimages/SF-1902-A4b.png
+code/compoundimages/SF-2140.png
+code/compoundimages/SF2738C.png
+code/compoundimages/Shikometabolin A.png
+code/compoundimages/Siastatin B.png
+code/compoundimages/Silalthride.png
+code/compoundimages/Sordarin-1-glucose ester.png
+code/compoundimages/Spliceostatin E.png
+code/compoundimages/Spongiporic acid A.png
+code/compoundimages/Sporminarin B.png
+code/compoundimages/Stoloniferone L.png
+code/compoundimages/Strepantibin C.png
+code/compoundimages/Streptoaminal-8n.png
+code/compoundimages/Streptoaminal9n.png
+code/compoundimages/Streptofactin.png
+code/compoundimages/Streptoone C.png
+code/compoundimages/Streptovirudin D1.png
+code/compoundimages/Strevertene B.png
+code/compoundimages/Syringolin G.png
+code/compoundimages/T1801 A.png
+code/compoundimages/Tasipeptin A.png
+code/compoundimages/Tasipeptin B.png
+code/compoundimages/Tautomycin.png
+code/compoundimages/Teixobactin.png
+code/compoundimages/Tenacibactin A.png
+code/compoundimages/Tenacibactin B.png
+code/compoundimages/Terresterol.png
+code/compoundimages/Tetradecanenitrile.png
+code/compoundimages/Tetronomycin.png
+code/compoundimages/Thailandamide lactone.png
+code/compoundimages/Thaxteramide A2.png
+code/compoundimages/Thaxtomin B.png
+code/compoundimages/Tjipanazole C1.png
+code/compoundimages/Trichophycin C.png
+code/compoundimages/Triedimycin A.png
+code/compoundimages/Trierixin.png
+code/compoundimages/Tyromycic acid G.png
+code/compoundimages/U-77864.png
+code/compoundimages/UK-78629.png
+code/compoundimages/Unguisin E.png
+code/compoundimages/USF-142A.png
+code/compoundimages/Uvidin-A ester 2a.png
+code/compoundimages/Violapyrone B.png
+code/compoundimages/Violapyrone E.png
+code/compoundimages/VLP T.png
+code/compoundimages/Wortmanamide B.png
+code/compoundimages/Xanthocillin-X dimethylether.png
+code/compoundimages/Xefoampeptide C.png
+code/compoundimages/Xentrivalpeptide O.png
+code/compoundimages/Yanucamide A.png
+code/compoundimages/Yatakemycin.png
+code/compoundimages/Yicathin C.png
+code/compoundimages/YM-47515 degradation product.png
+code/compoundimages/Ypaoamide C.png
+code/compoundimages/Z-4-2.png
+code/test_upsetplt.png
code/test_upsetplt.png
code/treemap.png
code/untitled0.py
-msdial.mgf
-msdial.msp
-msdial_unformatted.txt
-msdialhead.csv
-mzmine.mgf
-mzminehead.csv
-nativehead.csv
-progenesis.csv
-progenesis.msp
-241115_mpactreferenceguide.docx
-220504_mpactmanual.docx
-devnotes.md
+code/test_upsetplt.png
+code/test_upsetplt.png
+code/treemap.png
diff --git a/LICENSE b/LICENSE
index f288702..d159169 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,622 +1,281 @@
GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
+ Version 2, June 1991
- Copyright (C) 2007 Free Software Foundation, Inc.
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
this License.
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
@@ -628,15 +287,15 @@ free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
+convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
- This program is free software: you can redistribute it and/or modify
+ This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
+ the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
@@ -644,31 +303,37 @@ the "copyright" line and a pointer to where the full notice is found.
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
- Copyright (C)
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-.
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ , 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/MPACT.lnk b/MPACT.lnk
index 67e2ee3..f04656d 100644
Binary files a/MPACT.lnk and b/MPACT.lnk differ
diff --git a/code/MSFaST.py b/code/MSFaST.py
index 40df133..abc80e3 100644
--- a/code/MSFaST.py
+++ b/code/MSFaST.py
@@ -1,16 +1,15 @@
"""
MPACT
Copyright 2022, Robert M. Samples, Sara P. Puckett, and Marcy J. Balunas
-Modifications Copyright 2026, Robert M. Samples
"""
import pandas as pd
import numpy as np
import filter
import stats
-from groupsets import normalize_graphfilters
from datetime import datetime
import time
+from pathlib import Path
#---Classes---
@@ -22,11 +21,7 @@ class groupset: # parses the ions to be plotted as a specific color based on th
Args:
- name (str): The name of the group set.
- query (query_parameters): A query_parameters object.
- - iondict (DataFrame): The ion dictionary, indexed by ``Compound``, with
- a ``groups`` column. Callers already have this loaded in memory (it's
- built immediately before every groupset is constructed) -- pass that
- directly rather than a path, so each groupset doesn't re-read the same
- file from disk (previously: once per Plot Feature Set configured).
+ - iondictloc (str): The file path to the ion dictionary location.
Attributes:
- legendname (str): The legend name of the group set.
@@ -35,12 +30,13 @@ class groupset: # parses the ions to be plotted as a specific color based on th
- plotcol (str): The plot color of the group set.
- ionlist (list of str): The ions to be plotted in the group set.
"""
- def __init__(self, name, query, iondict):
+ def __init__(self, name, query, iondictloc):
self.legendname = query.name
self.excl = query.excl
self.incl = query.incl
self.plotcol = query.colour
-
+
+ iondict = pd.read_csv(iondictloc, sep = ',', header = 0, index_col = 'Compound') #block adds average and median cv to iondict.csv, move elsewhere
iondict = iondict.loc[iondict['groups'].notna(), 'groups'].to_frame()
exclgrps = ' ' + '| '.join(self.excl)
if len(exclgrps)>3: #only runs below line if there is an exclusion group
@@ -52,7 +48,7 @@ def __init__(self, name, query, iondict):
class analysis_parameters:
"""
An empty class that is used as a placeholder to hold analysis parameters.
-
+
Attributes:
- init (str): An initial string.
"""
@@ -60,23 +56,6 @@ def __init__(self):
self.init = ''
-class AnalysisResult:
- """The output of ``run_MSFaST()``: everything it computes, bundled into
- one plain object instead of written onto whichever object was passed in.
-
- Attributes:
- - ionfilters (dict): Per-filter-type ``ionfilter`` results (cv/relfil/insource).
- - groupionlists (dict): Per-biological-group lists of failing ion IDs.
- - groupsets (dict): Per-Plot-Feature-Set ``groupset`` objects.
- - filtereddfs (dict): Per-Plot-Feature-Set filtered peak tables.
- """
- def __init__(self, ionfilters, groupionlists, groupsets, filtereddfs):
- self.ionfilters = ionfilters
- self.groupionlists = groupionlists
- self.groupsets = groupsets
- self.filtereddfs = filtereddfs
-
-
#---Methods---
def start_time():
@@ -93,109 +72,98 @@ def stop_time():
def importdata():
"""Function to import data from files and format it"""
print('Loading files')
-
+
+ extractmetadata = pd.read_csv(analysis_params.extractmetadatafilename, sep = ',', header = [0], index_col = None) #imports sample/extract metadata
+ samplelist = pd.read_csv(analysis_params.samplelistfilename, sep = ',', header = [0], index_col = None) #imports instrument sample list
+ combinedmetadata = extractmetadata.set_index('Sample_Code').join(samplelist.set_index('Sample_Code')).reset_index().set_index('Injection') #joins extract metadata and sample list by the sample code, looks like a god line probabaly best to move set index into the import
+ msdata = pd.read_csv(analysis_params.filename, sep = ',', header = None, index_col = [0, 1, 2]) #imports feature list
+ position = 0
+ for elem in msdata.iloc[1]: # itterates over header to format
+ msdata.iloc[1, position] = combinedmetadata.loc[msdata.iloc[2, position], 'Sample_Code']
+ msdata.iloc[0, position] = combinedmetadata.loc[msdata.iloc[2, position], 'Biological_Group']
+ position += 1 # increments current injection index
+
# Import sample/extract metadata
- extractmetadata = pd.read_csv(analysis_params.extractmetadatafilename,
+ extractmetadata = pd.read_csv(analysis_params.extractmetadatafilename,
sep=',', header=0, index_col=None)
-
+
# Import instrument sample list
- samplelist = pd.read_csv(analysis_params.samplelistfilename,
+ samplelist = pd.read_csv(analysis_params.samplelistfilename,
sep=',', header=0, index_col=None)
-
+
# Join extract metadata and sample list by the sample code
combinedmetadata = (extractmetadata.set_index('Sample_Code')
.join(samplelist.set_index('Sample_Code'))
.reset_index().set_index('Injection'))
-
-
+
+
# Import feature list
- msdata = pd.read_csv(analysis_params.filename, sep=',', header=None,
- index_col=[0, 1, 2], low_memory=False)
-
+ msdata = pd.read_csv(analysis_params.filename, sep=',', header=None,
+ index_col=[0, 1, 2])
+
# Iterate over header to format
for position, elem in enumerate(msdata.iloc[1]):
msdata.iloc[1, position] = combinedmetadata.loc[
msdata.iloc[2, position], 'Sample_Code']
msdata.iloc[0, position] = combinedmetadata.loc[
msdata.iloc[2, position], 'Biological_Group']
-
+
# Write formatted peak table
print('Writing formatted peak table')
- msdata.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ msdata.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
header=False, index=True)
-
- # Import data from formatted peak table. This re-read is a genuine
- # reshape, not a redundant one: writing with header=False/index=True
- # then reading back with header=[0, 1, 2]/index_col=[0] promotes the
- # first 3 (already-edited) data rows into a 3-level column header and
- # collapses the 3-level row index down to one level -- replicating that
- # in memory would mean re-deriving exactly what pd.read_csv's header/
- # index parsing does (dtype inference, NaN handling, etc.) by hand, the
- # same category of subtle mismatch that caused the LossySetitemError
- # fixed earlier. Not worth the risk for one disk round-trip.
- msdata = pd.read_csv(analysis_params.outputdir /
- (analysis_params.filename.stem + '_formatted.csv'),
+
+ # Import data from formatted peak table
+ msdata = pd.read_csv(analysis_params.outputdir /
+ (analysis_params.filename.stem + '_formatted.csv'),
sep=',', header=[0, 1, 2], index_col=[0])
-
+
# Calculate mean of each row and drop rows with mean of 0
msdataave = msdata.iloc[:, 2:].astype(float)
msdataave['mean'] = msdataave.mean(axis=1, skipna=True)
msdata = msdata[msdataave['mean'] != 0]
# Save formatted peak table and original feature list
- msdata.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ msdata.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
header=True, index=True)
- msdata.to_csv(analysis_params.outputdir / (analysis_params.filename.name),
+ msdata.to_csv(analysis_params.outputdir / (analysis_params.filename.name),
header=True, index=True)
-
- # Build the feature dictionary (with KMD) from msdata already in memory
- # instead of re-reading the file just written above with yet another
- # header shape (header=[2], flattening the 3-level column header to its
- # bottom level only). Equivalent to msdata.columns.get_level_values(2)
- # plus resetting the index back to a plain Compound column -- verified
- # against the previous disk-read version with real example data
- # (identical values and dtypes) before relying on it here.
- iondict = msdata.copy()
- iondict.columns = iondict.columns.get_level_values(2)
- iondict = iondict.reset_index().iloc[:, :3]
- iondict.columns = ['Compound', 'm/z', 'Retention time (min)']
+
+ # Save feature dictionary with KMD for later use
+ iondict = pd.read_csv(analysis_params.outputdir /
+ (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[2], index_col=None).iloc[:,:3]
iondict['kmd'] = iondict['m/z'] - np.floor(iondict['m/z'])
iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=False)
-def run_MSFaST(params):
+def run_MSFaST(self):
"""
- Runs the MSFaST analysis pipeline for the given analysis parameters.
-
+ Runs MSFaST analysis with the given analysis parameters and data.
+
Args:
- params (analysis_parameters): The analysis parameters/inputs to run.
-
+ self: Object instance of the MSFaST class.
+
Returns:
- AnalysisResult: everything the pipeline computed (ionfilters,
- groupionlists, groupsets, filtereddfs) -- nothing is written onto
- ``params`` or any other caller-supplied object.
+ None
"""
start_time()
- # importdata()/filter.py/stats.py read and mutate this same object via
- # the `global analysis_params` they declare -- unchanged from before,
- # just no longer aliased through a caller-supplied `self.analysis_paramsgui`.
+ # Import analysis parameters and data
global analysis_params
- analysis_params = params
+ analysis_params = self.analysis_paramsgui
importdata()
# Filtering and error propagation
print('Filtering data')
- ionfilters = {}
- # Initialise here (not only inside `if analysis_params.grpave:`) so the
- # unconditional groupionlists[...] writes further down (and the blank
- # filter, which reads it) can't raise NameError if grpave is ever off.
- # The GUI currently forces grpave=True, but loaded sessions/tests need not.
- groupionlists = {}
+ self.ionfilters = {}
if analysis_params.relfil:
- ionfilters = filter.relationalfilter(analysis_params, ionfilters)
+ # 质量亏损过滤(在relfil/decon之前,先清掉化学上不可能的噪声离子)
+ if getattr(analysis_params, 'mdfil', False):
+ self.ionfilters = filter.mdfilter(analysis_params, self.ionfilters)
+ self.ionfilters = filter.relationalfilter(analysis_params, self.ionfilters)
if analysis_params.merge:
- filter.mergeions(analysis_params, ionfilters)
+ filter.mergeions(analysis_params, self.ionfilters)
if analysis_params.grpave:
stats.groupave(analysis_params)
print('Parsing ion lists')
@@ -209,17 +177,24 @@ def run_MSFaST(params):
iondict['pass_blnkfil'] = ~iondict.index.isin(groupionlists[analysis_params.blnkgrp])
iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
if analysis_params.CVfil:
- ionfilters = filter.cvfilter(analysis_params, ionfilters, analysis_params.cvthresh)
+ self.ionfilters = filter.cvfilter(analysis_params, self.ionfilters, analysis_params.cvthresh)
if analysis_params.decon:
- ionfilters = filter.decon(analysis_params, ionfilters)
- filter.applyfilters(analysis_params, ionfilters)
+ self.ionfilters = filter.decon(analysis_params, self.ionfilters)
+ if getattr(analysis_params, 'adductgrp', False): # 新增:加合物/在源裂解/二聚体归组
+ adduct_removed = filter.adductgroup(analysis_params, getattr(analysis_params, 'adduct_list', None))
+ self.ionfilters['adduct'] = filter.ionfilter('', list(adduct_removed))
+ filter.applyfilters(analysis_params, self.ionfilters)
if analysis_params.prperr:
stats.properr(analysis_params)
+ # Store group ion lists for later use
+ self.groupionlists = groupionlists
+
# Parse ion lists and add filter lists
- groupionlists['cv'] = ionfilters['cv'].ions if analysis_params.CVfil else []
- groupionlists['relfil'] = ionfilters['relfil'].ions if analysis_params.relfil else []
- groupionlists['insource'] = ionfilters['insource'].ions if analysis_params.decon else []
+ groupionlists['cv'] = self.ionfilters['cv'].ions if analysis_params.CVfil else []
+ groupionlists['relfil'] = self.ionfilters['relfil'].ions if analysis_params.relfil else []
+ groupionlists['insource'] = self.ionfilters['insource'].ions if analysis_params.decon else []
+ groupionlists['adduct'] = self.ionfilters['adduct'].ions if getattr(analysis_params, 'adductgrp', False) else []
# Add groups column to iondict csv
iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=0, index_col=None)
@@ -228,38 +203,36 @@ def run_MSFaST(params):
iondict.loc[iondict['Compound'].isin(groupionlists[group]), 'groups'] += (' ' + str(group))
iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=None)
- # Add default filters to querylist. Reuse the iondict already in memory
- # (just written above, unchanged since) instead of re-reading it from
- # disk -- and build the Compound-indexed view groupset needs once here,
- # rather than each groupset() call below re-reading the file from disk
- # itself (previously: once per Plot Feature Set configured).
- iondict_by_compound = iondict.set_index('Compound')
- groupsets, filtereddfs = {}, {}
+ # Add default filters to querylist
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=None)
+ self.groupsets, self.filtereddfs = {}, {}
for elem in analysis_params.querylist:
- groupsets[elem] = groupset(elem, analysis_params.querydict[elem], iondict_by_compound)
- filtereddfs[elem] = filter.listfilter(iondict, groupsets[elem].ionlist, True)
+ self.groupsets[elem] = groupset(elem, analysis_params.querydict[elem], analysis_params.outputdir / 'iondict.csv')
+ self.filtereddfs[elem] = filter.listfilter(iondict, self.groupsets[elem].ionlist, True)
#block creates user specified plots some of these can be changed to eliminate a few arguments with data pulled from analysis_params
- if analysis_params.FC:
+ if analysis_params.FC:
stats.runfc(analysis_params, analysis_params.statstgrps)
if analysis_params.Ttest:
- stats.runttest(analysis_params, analysis_params.statstgrps, groupsets)
-
+ stats.runttest(analysis_params, analysis_params.statstgrps, self.groupsets)
+
#---Analysis info file writing---
runtime = stop_time()
msdata_filtered = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_filtered.csv'), sep = ',', header = [0, 1, 2], index_col = [0])
msdata_header = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_filtered.csv'), sep = ',', header = None, index_col = [0,1,2]).iloc[:3,:].transpose()
msdata_header.columns = ['Biolgroup', 'Sample', 'Injection']
-
+
iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep = ',', header = [0], index_col = [0])
-
+ self.unfilteredgroupsets, self.unfiltereddfs = {}, {}
+
+ self.analysis_paramsgui = analysis_params
msdata_unformatted = pd.read_csv(analysis_params.filename, sep = ',', header = [0, 1, 2], index_col = [0, 1, 2]) #imports feature list
msdata = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.name), sep = ',', header = [0, 1, 2], index_col = [0, 1, 2])
msdata_filtered = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_filtered.csv'), sep = ',', header = [0, 1, 2], index_col = [0, 1, 2])
analysisrec = open(analysis_params.outputdir / 'analysisinfo.txt',"w")
analysisrec.writelines(['Analysis Date: ' + str(datetime.now()) + '\n',
- 'Runtime: ' + str(round(runtime, 2)) + ' seconds\n',
+ 'Runetime: ' + str(round(runtime, 2)) + ' seconds\n',
'Input file: ' + str(analysis_params.filename) + '\n',
'Sample list: ' + str(analysis_params.samplelistfilename) + '\n',
'Extract metadata file: ' + str(analysis_params.extractmetadatafilename) + '\n',
@@ -280,51 +253,44 @@ def run_MSFaST(params):
'max isotopic peak shift: ' + str(analysis_params.maxisowin) + '\n',
'\n',
'Total features: ' + str(len(msdata.index)) + '\n'])
-
+
text = ''
- if analysis_params.relfil:
- text += 'Features failing peak correction filtering: ' + str(len(ionfilters['relfil'].ions)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(ionfilters['relfil'].ions) / len(msdata_unformatted.index), 2)) + '%\n'
- if analysis_params.blnkfltr:
- text += 'Features failing blank filtering: ' + str(len(groupionlists[analysis_params.blnkgrp])) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(groupionlists[analysis_params.blnkgrp]) / len(msdata_unformatted.index), 2)) + '%\n'
- if analysis_params.decon:
- text += 'Features failing in-source/deconvolution filtering: ' + str(len(ionfilters['insource'].ions)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(ionfilters['insource'].ions) / len(msdata_unformatted.index), 2)) + '%\n'
- if analysis_params.CVfil:
- text += 'Features failing CV filtering: ' + str(len(ionfilters['cv'].ions)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(ionfilters['cv'].ions) / len(msdata_unformatted.index), 2)) + '%\n'
+ if self.analysis_paramsgui.relfil:
+ text += 'Features failing peak correction filtering: ' + str(len(self.ionfilters['relfil'].ions)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(self.ionfilters['relfil'].ions) / len(msdata_unformatted.index), 2)) + '%\n'
+ if self.analysis_paramsgui.blnkfltr: #FIX THIS REF TO "BLANKS"
+ text += 'Features failing blank filtering: ' + str(len(self.groupionlists[analysis_params.blnkgrp])) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(self.groupionlists[analysis_params.blnkgrp]) / len(msdata_unformatted.index), 2)) + '%\n'
+ if self.analysis_paramsgui.decon:
+ text += 'Features failing blank filtering: ' + str(len(self.ionfilters['insource'].ions)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(self.ionfilters['insource'].ions) / len(msdata_unformatted.index), 2)) + '%\n'
+ if self.analysis_paramsgui.CVfil:
+ text += 'Features failing CV filtering: ' + str(len(self.ionfilters['cv'].ions)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(self.ionfilters['cv'].ions) / len(msdata_unformatted.index), 2)) + '%\n'
text += 'Features failing any filters: ' + str(len(msdata_unformatted.index) - len(msdata_filtered.index)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * (len(msdata_unformatted.index) - len(msdata_filtered.index)) / len(msdata_unformatted.index), 2)) + '%\n'
text += 'Features passing all filters: ' + str(len(msdata_filtered.index)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(msdata_filtered.index) / len(msdata_unformatted.index), 2)) + '%\n'
-
+
analysisrec.writelines([text,
'\n',
'\n',
'---Graphing Parameters---\n',
'Filters: \n'])
-
- for elem in normalize_graphfilters(analysis_params.graphfilters):
+
+ for elem in analysis_params.graphfilters.split(' '):
analysisrec.write(elem + '\n')
-
+
analysisrec.writelines(['\n',
'-Groups-\n'])
-
+
for elem in analysis_params.querylist:
analysisrec.write(elem + '\n')
-
+
analysisrec.writelines(['\n',
'-Plots generated-\n',
'RT/mz: ' + str(analysis_params.MZRTplt) + '\n',
'RT/mz/FC: ' + str(analysis_params.FC3Dplt) + ' ' + str(analysis_params.statstgrps) + '\n',
'KMD/mz ' + str(analysis_params.KMD) + '\n',
#'KMD/mz/RT ' + str(analysis_params.___) + '\n',
- 'PCA unfiltered: ' + str(analysis_params.PCA) + '\n',
+ 'PCA unfitlered: ' + str(analysis_params.PCA) + '\n',
'PCA filtered: ' + str(analysis_params.PCA) + '\n',
'Dendrogram (ward) unfiltered: ' + str(analysis_params.Dendrogram) + '\n',
'Dendrogram (ward) Filtered: ' + str(analysis_params.Dendrogram) + '\n',
'Volcano plot: ' + str(analysis_params.Volcanoplt) + ' ' + str(analysis_params.statstgrps) + '\n',])
analysisrec.close()
-
- return AnalysisResult(
- ionfilters=ionfilters,
- groupionlists=groupionlists,
- groupsets=groupsets,
- filtereddfs=filtereddfs,
- )
diff --git a/code/adduct_config.txt b/code/adduct_config.txt
new file mode 100644
index 0000000..28773bb
--- /dev/null
+++ b/code/adduct_config.txt
@@ -0,0 +1,49 @@
+# ============================================================
+# MPACT 加合物 / 中性丢失(在源裂解)归组 配置
+# 负离子模式 | 乙腈水 + 乙酸铵 + 氨水 (碱性 HILIC)
+# 放在 code 文件夹(和 main.py 同目录)。改完保存,重跑生效。
+# ============================================================
+
+enable = True
+mode = neg
+ppm = 3
+corr_cut = 0.75
+corr_p = 0.05
+mass_defect = True
+md_halogen = False
+
+# ============================================================
+# 离子形式:质量差相对 [M-H]-,单位 Da
+# 加合为正,中性丢失为负。不用的行首加 # 即可
+# ============================================================
+
+# --- 加合物 ---
+M+Hac-H, 60.0211
+M+Cl, 35.9767
+
+# --- 中性丢失 / 在源裂解 ---
+M-H2O-H, -18.0106
+M-2H2O-H, -36.0211
+M-CO2-H, -43.9898
+M-CO-H, -27.9949
+M-SO3-H, -79.9568
+M-H2SO4-H, -97.9674
+M-GlcA-H, -176.0321
+M-Hex-H, -162.0528
+M-Taurine-H,-125.0147
+
+# --- 备用(需要时取消注释)---
+# M+Na-2H, 21.9819
+# M+K-2H, 37.9559
+# M+Cl37, 37.9737
+# M+FA-H, 46.0055
+
+# ============================================================
+# 备注:
+# - 同位素 / 振铃 / 二聚体 由 relfil 处理,不在这里配置
+# - [M+Cl]- 来自样品基质,不是流动相
+# - Cl 的质量亏损 -0.031,质量亏损下界 -0.03,刚好卡边界。跑完查
+# iondict 里 pass_mdfil=False 的离子有无成对相差 35.9767 的,
+# 有就把 md_halogen 改成 True 重跑
+# - 37Cl 与 35Cl 差 1.9971,不是 1.0034 的整数倍,relfil 抓不到
+# ============================================================
diff --git a/code/compoundimages/2-Methylthio-cis-zeatin.png b/code/compoundimages/2-Methylthio-cis-zeatin.png
new file mode 100644
index 0000000..b0ae749
Binary files /dev/null and b/code/compoundimages/2-Methylthio-cis-zeatin.png differ
diff --git a/code/filter.py b/code/filter.py
index 534edec..a7aa532 100644
--- a/code/filter.py
+++ b/code/filter.py
@@ -7,6 +7,7 @@
import numpy as np
import math
import scipy.cluster.hierarchy as spc
+from scipy import stats
import mspwriter
from tqdm import tqdm
@@ -302,72 +303,376 @@ def cvfilter(analysis_params, ionfilterlist, threshold):
# -----Deringing and relational filter algorithm-----
def relationalfilter(analysis_params, ionfilterlist):
"""
- Implements a de-ringing and relational filtering algorithm for MS data.
-
- Parameters:
- analysis_params (object): Analysis parameters.
- ionfilterlist (dict): Dictionary of ion filters.
-
- Returns:
- dict: Dictionary of ion filters.
-
- The algorithm works by first sorting the MS data by m/z, and then iterating over the data one ion at a time,
- comparing each ion to all subsequent ions that fall within a certain mass and retention time window.
- Ions that meet certain criteria are then merged into a single ion using the ionmerge class.
-
- The filtering criteria includes:
- - A mass difference of less than a specified value
- - A retention time difference of less than a specified value
- - A difference between the mass difference and its floor when multiplied by a factor, indicating the presence of ring artifacts
- - A difference between the mass difference and 0.5004 when accounting for the doubly-charged dimer, indicating the presence of dimer peaks
-
- The function returns a dictionary of ion filters, with the 'relfil' filter containing a list of ions to remove,
- and a 'merge' attribute which contains the merge groups (as an ionmerge object) that specify which ions to merge.
+ 改进版关系过滤:去除同位素、振铃、二聚体三类冗余峰。
+
+ 相比原版的改进(每处都有注释):
+ - 同位素:质量差=n×1.0033548(n=1~3),按ppm容差,且要求【弱于母峰】+ 跨样品相关高
+ - 振铃:强度<母峰的一定比例(默认1%)+ 质量差<一定ppm(默认800ppm)——文献标准,不再用过宽的 floor(md*2)%2 判据
+ - 二聚体:质量差小数部分≈0.5004(修正原版缺abs的bug)+ 弱于母峰 + 相关高
+ - 全局扫描:每个峰独立在其RT窗内寻找母峰
+
+ 新增可调参数(analysis_params,若无则用默认):
+ iso_ppm(默认3)、iso_max_n(默认3)、iso_ratio_max(默认0.7)
+ ring_ratio_max(默认0.01)、ring_ppm(默认800)
+ dimer_tol(默认0.02)、corr_cut(默认0.75)、corr_p(默认0.05)
+ (RTwin 沿用原参数)
"""
-
- print('Running relational filter')
- pdindex = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'), sep = ',', header = [2], index_col = None)
- pdindex.drop(pdindex.columns.difference(['Compound','m/z','Retention time (min)']), axis=1, inplace=True)
- pdindex = pdindex.sort_values(['m/z'], ascending=[1])
- npindex = pdindex.to_numpy()
-
- ion_position, ion_comp_pos, current_rt, current_mass, mass_diff, kmd_diff, cut_ions, mergegroups = 0, 0, 0, 0, 0, 0, [], {}
- for ions in npindex[0:,0]: #scrolls through ions in order and checks if any subsequent ions fall within time and mass filter range, any ions that are are copied to a list
- current_rt = npindex[ion_position, 2]
- current_mass = npindex[ion_position, 1]
- current_ion = npindex[ion_position, 0]
- ion_comp_pos = ion_position + 1
- if (current_ion not in cut_ions):
- for ions in npindex[ion_comp_pos:, 0]: # the following statement checks if any peaks are within 0.05 min and in the mass filtering window.
- #The mass filtering window works by checking if the difference of the two ions, when multiplied by two and floored, is even this
- #corresponds to filtering out ions within 0.5 daltons of a peak or any of its first five isotopic peaks.
- mass_diff = abs((npindex[ion_comp_pos, 1] - current_mass))
- kmd_diff = mass_diff - math.floor(mass_diff)
- if ((npindex[ion_comp_pos, 1] - current_mass) > analysis_params.maxisowin - .4):
- break # breaks loop if we are already past the maximum consideration window for isotope shift, saves considerable processsing time.
- if ((abs(npindex[ion_comp_pos, 2]-current_rt) <= analysis_params.RTwin) # RT band
- and ((npindex[ion_comp_pos, 1] - current_mass) <= analysis_params.maxisowin - .4)
- and ((math.floor(mass_diff * (1/analysis_params.ringingwin)) % (1/analysis_params.ringingwin) == 0) #band for ringing
- or ((kmd_diff - .5004 - (math.floor(mass_diff) * .007)) < analysis_params.dimerpeakwin)) #band for doubly charged dimer removal, CHECK TO SEE IF CAN USE MOD FOR THIS
- and (npindex[ion_comp_pos, 0] not in cut_ions)): # check if ion already removed
-
- cut_ions.append(npindex[ion_comp_pos, 0]) #creates or appends merge group to indicate which ions to be merged. Merge not yet implimented
- if current_ion in mergegroups:
- mergegroups[current_ion].sources.append(npindex[ion_comp_pos, 0])
+ print('Running relational filter (improved: isotope/ringing/dimer with intensity+correlation)')
+
+ # ---- 参数(可调,带默认)----
+ iso_ppm = getattr(analysis_params, 'iso_ppm', 3.0)
+ iso_max_n = getattr(analysis_params, 'iso_max_n', 3)
+ iso_ratio_max = getattr(analysis_params, 'iso_ratio_max', 0.70)
+ ring_ratio = getattr(analysis_params, 'ring_ratio_max', 0.01)
+ ring_ppm = getattr(analysis_params, 'ring_ppm', 800.0)
+ dimer_tol = getattr(analysis_params, 'dimer_tol', 0.02)
+ corr_cut = getattr(analysis_params, 'corr_cut', 0.75)
+ corr_p = getattr(analysis_params, 'corr_p', 0.05)
+ rt_win = analysis_params.RTwin
+ C13 = 1.0033548
+
+ # ---- 读 m/z, RT ----
+ pdindex = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[2], index_col=None)
+ pdindex.drop(pdindex.columns.difference(['Compound', 'm/z', 'Retention time (min)']), axis=1, inplace=True)
+
+ # ---- 读各样品强度矩阵(用于强度比较 + 跨样品相关)----
+ # 内存优化:用numpy数组+id->行号映射,不给每个峰单独存字典(省内存)
+ _full = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[0, 1, 2], index_col=[0], low_memory=False)
+ _lvl0 = [str(c[0]) for c in _full.columns]
+ _keep = [i for i, g in enumerate(_lvl0) if ('BLANK' not in g.upper()) and (g.upper() != 'QC')]
+ _IDS = _full.index.to_numpy()
+ _INT = _full.iloc[:, _keep].apply(pd.to_numeric, errors='coerce').fillna(0.0).to_numpy(dtype=np.float32) # float32省一半内存
+ _row_of = {int(_IDS[k]): k for k in range(len(_IDS))}
+ _MAX = _INT.max(axis=1)
+ del _full # 释放原始DataFrame
+ import gc; gc.collect()
+
+ def _get_int(cid):
+ k = _row_of.get(int(cid))
+ return _INT[k] if k is not None else None
+ def _get_max(cid):
+ k = _row_of.get(int(cid))
+ return float(_MAX[k]) if k is not None else 0.0
+
+ def _corr_ok(id_a, id_b):
+ """跨样品Pearson相关(CAMERA标准:r>corr_cut 且 p 0) | (b > 0)
+ if mask.sum() < 4:
+ return True # 样品太少无法检验,放行(靠质量差+RT)
+ try:
+ r, pv = stats.pearsonr(a[mask], b[mask])
+ except Exception:
+ return True
+ if not np.isfinite(r):
+ return True
+ return (r > corr_cut) and (pv < corr_p)
+
+ # ---- 全局扫描:按m/z排序,每个峰在RT窗内找母峰 ----
+ arr = pdindex.sort_values(['m/z']).to_numpy() # 列: Compound, m/z, RT
+ comp = arr[:, 0]
+ mz = arr[:, 1].astype(float)
+ rt = arr[:, 2].astype(float)
+ n = len(comp)
+ order = np.argsort(mz)
+ mzs = mz[order]
+
+ cut_ions = []
+ cut_set = set()
+ mergegroups = {}
+
+ # 迭代到收敛(删除会改变可用母峰),最多几轮
+ changed = True
+ rounds = 0
+ while changed and rounds < 6:
+ changed = False
+ rounds += 1
+ for i in range(n):
+ cid = comp[i]
+ if cid in cut_set:
+ continue
+ m0, r0 = mz[i], rt[i]
+ i0 = _get_max(cid)
+ lo = np.searchsorted(mzs, m0 - (iso_max_n + 0.1))
+ hi = np.searchsorted(mzs, m0 - 1e-9)
+ for oi in range(lo, hi):
+ j = order[oi]
+ pid = comp[j]
+ if pid in cut_set or pid == cid:
+ continue
+ dm = m0 - mz[j]
+ if dm <= 0:
+ continue
+ if abs(rt[j] - r0) > rt_win:
+ continue
+ pmax = _get_max(pid)
+ if pmax <= 0:
+ continue
+ ratio = i0 / pmax
+ kmd = dm - math.floor(dm)
+ nn = round(dm / C13)
+ iso_dev = abs(dm - nn * C13) / m0 * 1e6 if nn >= 1 else 1e9
+
+ hit = False
+ # 同位素:整数13C间隔 + 弱于母峰(<比例上限) + (相关高 或 强度比很低)
+ if (1 <= nn <= iso_max_n) and (iso_dev < iso_ppm) and (0 < ratio <= iso_ratio_max):
+ if _corr_ok(pid, cid) or ratio < 0.5:
+ hit = True
+ # 二聚体:质量差小数部分≈0.5004(修正abs) + 弱于母峰 + 相关
+ if (not hit) and (abs(kmd - 0.5004) < dimer_tol) and (ratio < 0.7):
+ if _corr_ok(pid, cid):
+ hit = True
+ # 振铃:强度<母峰比例 + 质量差corr_cut 且 p 1e-6]
+
+ # ---- 基准离子形式:由 adduct_config.txt 的 mode 决定(pos -> M+H,neg -> M-H)----
+ _mode = str(getattr(analysis_params, 'adduct_mode', '') or '').strip().lower()
+ if _mode.startswith('neg'):
+ base_form = 'M-H'
+ elif _mode.startswith('pos'):
+ base_form = 'M+H'
+ else:
+ base_form = 'M+H'
+ print(' Warning: adduct_config.txt 里没读到 mode,暂按正离子(M+H)处理')
+ # 一致性检查:mode 与离子形式表对不上就提醒(防止用错配置文件)
+ _npos = sum(1 for _nm, _ in form_deltas if str(_nm).strip().endswith('+H'))
+ _nneg = sum(1 for _nm, _ in form_deltas if str(_nm).strip().endswith('-H'))
+ if base_form == 'M-H' and _npos > _nneg:
+ print(' Warning: mode=neg,但离子形式表像是正离子的(%d 个以 +H 结尾),请检查 adduct_config.txt' % _npos)
+ if base_form == 'M+H' and _nneg > _npos:
+ print(' Warning: mode=pos,但离子形式表像是负离子的(%d 个以 -H 结尾),请检查 adduct_config.txt' % _nneg)
+ print(' base ion form: %s (mode=%s, %d ion forms)' % (base_form, _mode or 'unset', len(form_deltas)))
+
+ _full = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[0,1,2], index_col=[0], low_memory=False)
+ mz_col = _full.columns[0]; rt_col = _full.columns[1]
+ mz_all = pd.to_numeric(_full[mz_col], errors='coerce').to_numpy()
+ rt_all = pd.to_numeric(_full[rt_col], errors='coerce').to_numpy()
+ ids = _full.index.to_numpy()
+ data_cols = list(_full.columns[2:])
+ samp_cols_for_corr = [c for c in data_cols if ('BLANK' not in str(c[0]).upper()) and (str(c[0]).upper()!='QC')]
+ INT_all = _full[data_cols].apply(pd.to_numeric, errors='coerce').fillna(0.0).to_numpy(dtype=np.float32)
+ CORR_mat = _full[samp_cols_for_corr].apply(pd.to_numeric, errors='coerce').fillna(0.0).to_numpy(dtype=np.float32)
+ row_of = {int(ids[k]): k for k in range(len(ids))}
+ del _full
+ import gc; gc.collect()
+
+ def detmean(k):
+ v = CORR_mat[k]; nz = v[v>0]
+ return float(nz.mean()) if nz.size else 0.0
+ detmean_all = np.array([detmean(k) for k in range(len(ids))])
+
+ def corr_ok(ka, kb):
+ a, b = CORR_mat[ka], CORR_mat[kb]
+ mask = (a>0)|(b>0)
+ if mask.sum() < 4: return True
+ try: r, pv = stats.pearsonr(a[mask], b[mask])
+ except Exception: return True
+ if not np.isfinite(r): return True
+ return (r > corr_cut) and (pv < corr_p)
+
+ order = np.argsort(mz_all)
+ mzs_sorted = mz_all[order]
+ assigned = {}
+ groups = {}
+ for i in range(len(ids)):
+ cid = int(ids[i])
+ if cid in assigned: continue
+ m0, r0 = mz_all[i], rt_all[i]
+ if not np.isfinite(m0): continue
+ members = [(cid, base_form)]
+ for name, delta in form_deltas:
+ target_mz = m0 + delta
+ lo = np.searchsorted(mzs_sorted, target_mz*(1-ppm/1e6)-0.001)
+ hi = np.searchsorted(mzs_sorted, target_mz*(1+ppm/1e6)+0.001)
+ for oi in range(lo, hi):
+ j = order[oi]; jid = int(ids[j])
+ if jid == cid or jid in assigned: continue
+ if abs(mz_all[j]-target_mz)/target_mz*1e6 > ppm: continue
+ if abs(rt_all[j]-r0) > rt_win: continue
+ if corr_ok(i, j):
+ members.append((jid, name)); assigned[jid] = (cid, name); break
+ if len(members) > 1:
+ groups[cid] = members; assigned[cid] = (cid, 'M+H')
+
+ removed_ids = set()
+ attribution_rows = []
+ header_cols = ['Compound','m/z','Retention time (min)','adduct_form','is_main'] + [str(c[2]) for c in data_cols]
+ form_map = {}
+ for base, members in groups.items():
+ best = max(members, key=lambda x: detmean_all[row_of[x[0]]])
+ main_id = best[0]
+ mem_forms = dict(members)
+ for mid, form in members:
+ form_map[mid] = form
+ if mid != main_id: removed_ids.add(mid)
+ def make_row(pid, form, is_main):
+ k = row_of[pid]
+ return [pid, round(mz_all[k],4), round(rt_all[k],4), form, ('main' if is_main else ''), *list(INT_all[k])]
+ attribution_rows.append(make_row(main_id, mem_forms[main_id], True))
+ for mid, form in members:
+ if mid != main_id:
+ attribution_rows.append(make_row(mid, form, False))
+ attribution_rows.append([None]*len(header_cols))
+
+ pd.DataFrame(attribution_rows, columns=header_cols).to_csv(
+ analysis_params.outputdir / 'adduct_attribution.csv', index=False)
+
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
+ iondict['pass_adduct'] = ~iondict.index.isin(removed_ids)
+ iondict['adduct_form'] = iondict.index.map(lambda x: form_map.get(x,''))
+ iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
+
+ print(' adduct grouping: %d groups, %d redundant ions moved to attribution table' % (len(groups), len(removed_ids)))
+ return removed_ids
+
+
+# -----Mass defect filter-----
+def md_plausible(mz, hi_slope, hi_int, lo_slope, lo_int):
+ """
+ 判断 m/z 是否可能是单电荷 CHNOPS 小分子离子。
+
+ 允许区间(按质量线性变化的质量亏损上下界):
+ 上界 hi(m) = hi_slope*m + hi_int (饱和烃 / 脂类, H 最多)
+ 下界 lo(m) = lo_slope*m + lo_int (高度磷酸化/硫酸化, 杂原子最多)
+ 质量亏损 = m/z - 名义质量, 名义质量未知。只要存在某个整数 N 使
+ lo <= m/z - N <= hi 即视为可能。这样不会出现 floor/round 带来的"翻转"
+ 问题(脂类亏损 >0.5、高分子量 >1 时依然正确)。
+ 注意: 区间宽度在 m/z ~650 以上超过 1 Da, 此时所有 m/z 都会通过 ——
+ 这是物理事实, 不是 bug: 质量亏损只能剔除低质量端的不可能离子。
+ """
+ mz = np.asarray(mz, dtype=float)
+ hi = hi_slope * mz + hi_int
+ lo = lo_slope * mz + lo_int
+ return np.ceil(mz - hi) <= np.floor(mz - lo)
+
+
+def mdfilter(analysis_params, ionfilterlist):
+ """
+ 质量亏损过滤:剔除 m/z 在化学上不可能对应单电荷 CHNOPS 分子的离子
+ (噪声、盐簇、背景离子、未识别的多电荷离子等)。
+
+ 结果写入:
+ - ionfilterlist['massdefect']
+ - iondict.csv 新增 'mass_defect'(m/z - round(m/z))与 'pass_mdfil'
+ (applyfilters 会自动应用所有 pass_* 列)
+ 若 md_drop_early=True(默认), 还会把不通过的离子直接从 _formatted.csv 删除,
+ 避免它们参与后续 decon(在源碎片聚类会把最高 m/z 当母离子, 一个不可能的
+ 高 m/z 噪声可能把真实离子误判为它的碎片)和 relationalfilter。
+ 因此请在 relationalfilter / decon 之前调用。
+
+ 可调参数(analysis_params, 带默认):
+ md_hi_slope (0.00112) md_hi_int (0.03) 上界
+ md_lo_slope (-0.00025) md_lo_int (-0.03) 下界
+ md_halogen (False) True 时下界放宽到含多个 Cl/Br 的水平
+ md_drop_early (True)
+ 默认值按 [M+H]+ 估计, ±0.03 的截距余量覆盖 [M+Na]+、[M+NH4]+、[M-H]- 等
+ 常见加合物的偏移。若有 HMDB/RefMet 拟合的包络线, 直接替换这四个数即可。
+ """
+ print('Running mass defect filter')
+
+ hi_slope = getattr(analysis_params, 'md_hi_slope', 0.00112)
+ hi_int = getattr(analysis_params, 'md_hi_int', 0.03)
+ lo_slope = getattr(analysis_params, 'md_lo_slope', -0.00025)
+ lo_int = getattr(analysis_params, 'md_lo_int', -0.03)
+ if getattr(analysis_params, 'md_halogen', False):
+ lo_slope = getattr(analysis_params, 'md_lo_slope_halogen', -0.0011)
+ lo_int = getattr(analysis_params, 'md_lo_int_halogen', -0.05)
+ drop_early = getattr(analysis_params, 'md_drop_early', True)
+
+ fpath = analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv')
+ idx = pd.read_csv(fpath, sep=',', header=[2], index_col=None)
+ idx = idx[['Compound', 'm/z']].copy()
+ idx['m/z'] = pd.to_numeric(idx['m/z'], errors='coerce')
+
+ ok = md_plausible(idx['m/z'].to_numpy(), hi_slope, hi_int, lo_slope, lo_int)
+ ok = ok & idx['m/z'].notna().to_numpy()
+ fail_ids = idx.loc[~ok, 'Compound'].tolist()
+ fail_str = set(str(x) for x in fail_ids)
+
+ ionfilterlist['massdefect'] = ionfilter(
+ {'hi_slope': hi_slope, 'hi_int': hi_int, 'lo_slope': lo_slope, 'lo_int': lo_int},
+ fail_ids)
+
+ # iondict: 写质量亏损和 pass 列(用字符串匹配 ID, 避免 int/str 类型不一致)
+ md_map = dict(zip(idx['Compound'].astype(str), idx['m/z'] - np.round(idx['m/z'])))
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
+ key = iondict.index.astype(str)
+ iondict['mass_defect'] = [md_map.get(k, np.nan) for k in key]
+ iondict['pass_mdfil'] = ~key.isin(fail_str)
+ iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
+
+ if drop_early and fail_ids:
+ msdata = pd.read_csv(fpath, sep=',', header=[0, 1, 2], index_col=[0])
+ msdata = msdata[~msdata.index.astype(str).isin(fail_str)]
+ msdata.to_csv(fpath, header=True, index=True)
+
+ print(' mass defect filter: %d / %d ions failed' % (len(fail_ids), len(idx)))
+ return ionfilterlist
+
+
def mergeions(analysis_params, ion_filters):
"""
Merges source to target ion abundances for mispicked peak filtering.
@@ -409,29 +714,34 @@ def mergeions(analysis_params, ion_filters):
msdata_merged.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_merged.csv'), header=True, index=True)
# Format the merged data frame and save it
- msdata_merged = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_merged.csv'), sep=',', header=None, index_col=None, low_memory=False)
- # Columns 0-2 (row 2 currently blank/NaN here) get inferred as float64
- # since every other row in them is numeric -- widen to object first so
- # assigning the text header labels below doesn't try to losslessly cast
- # a string into a float64 column. Newer pandas raises on that (it used
- # to silently upcast with just a FutureWarning).
- msdata_merged[msdata_merged.columns[0:3]] = msdata_merged[msdata_merged.columns[0:3]].astype(object)
+ msdata_merged = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_merged.csv'), sep=',', header=None, index_col=None)
msdata_merged.iloc[2, 0:3] = ['Compound', 'm/z', 'Retention time (min)']
msdata_merged.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'), header=False, index=False)
def applyfilters(analysis_params, ion_filters):
"""
- Applies a list of ion filters to the data.
-
- Parameters:
- analysis_params (object): Analysis parameters.
- ion_filters (dict): Dictionary of ion filters.
-
- Returns:
- None
+ Apply filters to the data.
+
+ 改进版:以 iondict 的 pass_* 列为唯一依据删除,确保 filtered 表与 iondict 完全同步。
+ (原版用 ion_filters 字典,在多过滤器/多轮运行时易与 iondict 的 pass 列不同步,
+ 导致 filtered 里残留应删除的峰。)
+ 只有所有 pass_* 列都为 True 的特征才保留。
"""
- ms_data_out_filtered = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'), sep=',', header=None, index_col=None, low_memory=False) # reopen original data
- for elem in ion_filters:
- ms_data_out_filtered = listfilter(ms_data_out_filtered, ion_filters[elem].ions, False)
- ms_data_out_filtered.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_filtered.csv'), index=False, header=False) # saves output
-
+ ms_data_out_filtered = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=None, index_col=None)
+ # 读 iondict,取所有 pass_* 列
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
+ passcols = [c for c in iondict.columns if str(c).startswith('pass')]
+ # 全部 pass 为 True 的 Compound 才保留
+ keep_mask = pd.Series(True, index=iondict.index)
+ for _c in passcols:
+ keep_mask = keep_mask & (iondict[_c].astype(str).str.strip().str.upper() == 'TRUE')
+ keep_ids = set(iondict.index[keep_mask].astype(str))
+
+ # formatted 前3行是表头(组/样品/列名),数据从第4行;第一列是 Compound
+ header = ms_data_out_filtered.iloc[:3]
+ body = ms_data_out_filtered.iloc[3:]
+ body_keep = body[body.iloc[:, 0].astype(str).isin(keep_ids)]
+ out = pd.concat([header, body_keep], ignore_index=True)
+ out.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_filtered.csv'),
+ index=False, header=False)
diff --git a/code/filter.py.bak_before_mode_fix b/code/filter.py.bak_before_mode_fix
new file mode 100644
index 0000000..bbc0f76
--- /dev/null
+++ b/code/filter.py.bak_before_mode_fix
@@ -0,0 +1,729 @@
+"""
+MPACT
+Copyright 2022, Robert M. Samples, Sara P. Puckett, and Marcy J. Balunas
+"""
+
+import pandas as pd
+import numpy as np
+import math
+import scipy.cluster.hierarchy as spc
+from scipy import stats
+import mspwriter
+from tqdm import tqdm
+
+class ionmerge:
+ """
+ A class representing a target ion and sources to merge for mispicked filter.
+
+ Parameters:
+ target (str): The target ion to merge.
+ sources (list): A list of sources to merge with the target ion.
+
+ Attributes:
+ target (str): The target ion to merge.
+ sources (list): A list of sources to merge with the target ion.
+ """
+ def __init__(self, target, sources):
+ self.target = target
+ self.sources = []
+ self.sources.append(sources)
+
+class ionfilter:
+ """
+ A class representing a general ionfilter with parameters and a list of ions to remove.
+
+ Parameters:
+ parameters (dict): A dictionary of parameters for the ionfilter.
+ ionlist (list): A list of ions to remove.
+
+ Attributes:
+ params (dict): A dictionary of parameters for the ionfilter.
+ ions (list): A list of ions to remove.
+ merge (list): A list of ionmerge objects.
+ """
+ def __init__(self, parameters, ionlist):
+ self.params = parameters
+ self.ions = ionlist
+ self.merge = []
+
+
+
+def reformatcorr(corr): #reformat to for pos in range(1:corr.shape[0]) or something like that
+ """
+ Reformats a correlation matrix to generate a list from sequential columns.
+
+ Parameters:
+ corr (pd.DataFrame): The correlation matrix to be reformatted.
+
+ Returns:
+ np.ndarray: A reformatted array derived from the input correlation matrix.
+ """
+ corr = corr.to_numpy()
+ reformatted = corr[1:,0]
+ pos = 1
+ while pos < corr.shape[0]:
+ reformatted = np.append(reformatted, corr[pos+1:,pos], axis=0)
+ pos = pos + 1
+ reformatted = 1-np.where(reformatted<0, 0, reformatted)
+ return(reformatted)
+
+
+
+
+def decon(analysis_params, ionfilters):
+ """
+ Perform peak deconvolution on the data and update the ion filters and dictionary.
+
+ This function reads in formatted data and performs peak deconvolution using the correlation clustering method. It
+ then groups peaks into clusters, generates a list of precursor and fragment ions, and updates the ion filters and
+ dictionary. Finally, the function writes the formatted data back out to disk.
+
+ Parameters:
+ analysis_params (object): Analysis parameters.
+ ionfilters (dict): Dictionary of ion filters.
+
+ Returns:
+ dict: Updated dictionary of ion filters.
+ """
+ # Read in data
+ msdata_ind = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[2], index_col=[0, 1]).iloc[:, :1]
+ rtlist = msdata_ind['Retention time (min)'].unique()
+ msdata_ind = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[2], index_col=[0]).iloc[:, :2]
+ msdata = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[2], index_col=[0]).iloc[:, 2:]
+
+ # Initialize variables
+ singleslist = []
+ insourcelist = []
+ clusterlist = []
+ clusterdfs = []
+ filtereddf = msdata_ind
+ ftrgrps = {}
+ mergegroups = {}
+
+ # Loop through retention times
+ for elem in rtlist:
+ filtereddf = msdata_ind.loc[msdata_ind.iloc[:, 1] == elem, :]
+
+ if len(filtereddf.index) == 1:
+ singleslist.append(filtereddf.index.to_list()[0])
+ else:
+ # Perform deconvolution
+ unseplist = filtereddf.index.tolist()
+ filtereddf2 = msdata.loc[unseplist, :].transpose()
+ corr = filtereddf2.corr()
+ corr2 = reformatcorr(corr)
+ linkage = spc.linkage(corr2, method='complete')
+ np.clip(linkage, 0, None, linkage)
+ idx = spc.fcluster(linkage, 1 - analysis_params.deconthresh, 'distance')
+
+ # Group peaks by cluster
+ decongroups = {}
+ for group in range(1, max(idx) + 1):
+ decongroups[group] = []
+ for peak in range(0, idx.shape[0]):
+ if peak < len(unseplist):
+ decongroups[idx[peak]].append(unseplist[peak])
+
+ # Append groups to appropriate lists
+ for group in decongroups:
+ if len(decongroups[group]) == 1:
+ singleslist.append(decongroups[group][0])
+ else:
+ clusterlist.append(decongroups[group])
+ tempdf = msdata_ind.loc[decongroups[group]].sort_values(by=['m/z'], ascending=False)
+ if len(tempdf.index.to_list()) > 0:
+ precursor = tempdf.index.to_list()[0]
+ fragments = tempdf.index.to_list()[1:]
+ singleslist.append(precursor)
+ insourcelist += fragments
+ clusterdfs.append(tempdf)
+ mergegroups[precursor] = ionmerge(precursor, fragments)
+
+
+ # Write out data
+ msdata = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[0, 1, 2], index_col=[0])
+ msdata = msdata.loc[singleslist]
+ msdata.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ header=True, index=True)
+
+ # Update ion filters
+ ionfilters['insource'] = ionfilter('', insourcelist)
+ ionfilters['insource'].merge = mergegroups
+
+ # Update ion dictionary
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
+ iondict['pass_insource'] = ~iondict.index.isin(ionfilters['insource'].ions)
+ iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
+
+ # Convert ion filters to MSP format passes and prints errors
+ try:
+ mspwriter.convert_to_msp(ionfilters['insource'], analysis_params)
+ except Exception:
+ print('Error in MSP writer')
+ pass
+
+ return ionfilters
+
+# -----CV Filtering-----
+def listfilter(msdata, ionlist, include):
+ """
+ Filters msdata based on the ions in ionlist.
+
+ Parameters:
+ msdata (pandas.DataFrame): Dataframe to filter.
+ ionlist (list): List of ions to filter by.
+ include (bool): If True, keep ions in ionlist. If False, remove ions in ionlist.
+
+ Returns:
+ pandas.DataFrame: Filtered dataframe.
+ """
+ if include:
+ msdata = msdata[msdata.iloc[:, 0].isin(ionlist)]
+ else:
+ msdata = msdata[~msdata.iloc[:, 0].isin(ionlist)]
+ return msdata
+
+def groupfilter(group, msdata_blankfilterg, analysis_params):
+ """
+ Filters ions in msdata_blankfilterg based on presence in group.
+
+ Parameters:
+ group (str): Group to filter by.
+ msdata_blankfilterg (pandas.DataFrame): Dataframe to filter.
+ analysis_params (object): Analysis parameters.
+
+ Returns:
+ list: List of filtered ions.
+ """
+ # Filters ions based on group presence > 100 ions/abundance
+ msdata_blankfilterg = msdata_blankfilterg[msdata_blankfilterg[group] > analysis_params.blankfilthresh]
+ msdata_blankfilterg = msdata_blankfilterg.reset_index()
+ # Returns filtered dataframe index as list
+ groupfilterlist = msdata_blankfilterg.iloc[0:,0].tolist()
+ return groupfilterlist
+
+def parsionlists(analysis_params):
+ """
+ Parses lists of ions present in each group.
+
+ Parameters:
+ analysis_params (object): Analysis parameters.
+
+ Returns:
+ dict: Dictionary of group ion lists.
+ """
+ msdata_blankfilterg = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_groupaverages.csv'), sep = ',', header = [0], index_col = [0, 1, 2, 3]).unstack()
+ msdata_blankfilterg.columns = msdata_blankfilterg.columns.droplevel()
+ msdata_blankfilterg['max'] = msdata_blankfilterg.max(numeric_only=True, axis=1)
+ for column in msdata_blankfilterg:
+ msdata_blankfilterg[column] = msdata_blankfilterg[column] / msdata_blankfilterg['max']
+ msdata_blankfilterg = msdata_blankfilterg.drop(columns=['max'])
+ biolgroups = msdata_blankfilterg.columns.tolist()
+ groupionlists = {}
+ for group in biolgroups:
+ groupionlists[group] = groupfilter(group, msdata_blankfilterg, analysis_params)
+ return groupionlists
+
+
+
+def cvfilter(analysis_params, ionfilterlist, threshold):
+ """
+ Filters ions based on the coefficient of variation (CV).
+ """
+ print('Running CV filter')
+
+ # Calculate total number of cells in the dataset and set chunk size based on 100,000 cells per chunk
+ header = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'), nrows=0, header=[0, 1, 2])
+ total_columns = header.shape[1]
+ cells_per_chunk = 100_000
+ chunk_size = max(1, cells_per_chunk // total_columns) # Rows per chunk
+
+ # Initialize containers for aggregated results
+ means = []
+ stds = []
+ counts = []
+
+ # Import data and calculate sums and counts in chunks with a progress bar
+ with tqdm(desc='Processing chunks', unit='chunk') as pbar:
+ for chunk in pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[0, 1, 2], index_col=[0, 1, 2], chunksize=chunk_size):
+ try:
+ chunk_stacked = chunk.stack([0, 1, 2], future_stack=True)
+ except TypeError:
+ chunk_stacked = chunk.stack([0, 1, 2])
+
+ # Group data by the specified levels and calculate mean, std, and count per group
+ groupby_indices = chunk_stacked.groupby(level=[0, 1, 2, 3, 4])
+ means.append(groupby_indices.mean())
+ stds.append(groupby_indices.std())
+ counts.append(groupby_indices.count())
+
+ pbar.update(1)
+
+ # Concatenate results and calculate overall mean and standard deviation
+ mean_values = pd.concat(means)
+ std_values = pd.concat(stds)
+ count_values = pd.concat(counts)
+
+ # Calculate CV
+ msdata_cv = std_values / mean_values
+
+ # Calculate average and median CV across the first level
+ msdatameancv = msdata_cv.groupby(level=0).mean()
+ msdatamediancv = msdata_cv.groupby(level=0).median()
+
+ # Add average and median CV to iondict.csv
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
+ iondict['average CV'] = msdatameancv
+ iondict['median CV'] = msdatamediancv
+ iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
+
+ # Determine ions to keep and reject based on CV threshold
+ msdata_filtered = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[0, 1, 2], index_col=[0])
+ ionlist = msdata_filtered.index.tolist()
+ iondict_filtered = iondict[iondict[analysis_params.cvparam] < threshold]
+ cvkeeplist = iondict_filtered.index.tolist()
+ cvfilterlist = list(set(ionlist) - set(cvkeeplist))
+ ionfilterlist['cv'] = ionfilter(analysis_params.cvthresh, cvfilterlist)
+
+ # Update iondict with pass_cvfil column and save
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
+ iondict['pass_cvfil'] = ~iondict.index.isin(ionfilterlist['cv'].ions)
+ iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
+
+ return ionfilterlist
+
+
+
+# -----Deringing and relational filter algorithm-----
+def relationalfilter(analysis_params, ionfilterlist):
+ """
+ 改进版关系过滤:去除同位素、振铃、二聚体三类冗余峰。
+
+ 相比原版的改进(每处都有注释):
+ - 同位素:质量差=n×1.0033548(n=1~3),按ppm容差,且要求【弱于母峰】+ 跨样品相关高
+ - 振铃:强度<母峰的一定比例(默认1%)+ 质量差<一定ppm(默认800ppm)——文献标准,不再用过宽的 floor(md*2)%2 判据
+ - 二聚体:质量差小数部分≈0.5004(修正原版缺abs的bug)+ 弱于母峰 + 相关高
+ - 全局扫描:每个峰独立在其RT窗内寻找母峰
+
+ 新增可调参数(analysis_params,若无则用默认):
+ iso_ppm(默认3)、iso_max_n(默认3)、iso_ratio_max(默认0.7)
+ ring_ratio_max(默认0.01)、ring_ppm(默认800)
+ dimer_tol(默认0.02)、corr_cut(默认0.75)、corr_p(默认0.05)
+ (RTwin 沿用原参数)
+ """
+ print('Running relational filter (improved: isotope/ringing/dimer with intensity+correlation)')
+
+ # ---- 参数(可调,带默认)----
+ iso_ppm = getattr(analysis_params, 'iso_ppm', 3.0)
+ iso_max_n = getattr(analysis_params, 'iso_max_n', 3)
+ iso_ratio_max = getattr(analysis_params, 'iso_ratio_max', 0.70)
+ ring_ratio = getattr(analysis_params, 'ring_ratio_max', 0.01)
+ ring_ppm = getattr(analysis_params, 'ring_ppm', 800.0)
+ dimer_tol = getattr(analysis_params, 'dimer_tol', 0.02)
+ corr_cut = getattr(analysis_params, 'corr_cut', 0.75)
+ corr_p = getattr(analysis_params, 'corr_p', 0.05)
+ rt_win = analysis_params.RTwin
+ C13 = 1.0033548
+
+ # ---- 读 m/z, RT ----
+ pdindex = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[2], index_col=None)
+ pdindex.drop(pdindex.columns.difference(['Compound', 'm/z', 'Retention time (min)']), axis=1, inplace=True)
+
+ # ---- 读各样品强度矩阵(用于强度比较 + 跨样品相关)----
+ # 内存优化:用numpy数组+id->行号映射,不给每个峰单独存字典(省内存)
+ _full = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[0, 1, 2], index_col=[0], low_memory=False)
+ _lvl0 = [str(c[0]) for c in _full.columns]
+ _keep = [i for i, g in enumerate(_lvl0) if ('BLANK' not in g.upper()) and (g.upper() != 'QC')]
+ _IDS = _full.index.to_numpy()
+ _INT = _full.iloc[:, _keep].apply(pd.to_numeric, errors='coerce').fillna(0.0).to_numpy(dtype=np.float32) # float32省一半内存
+ _row_of = {int(_IDS[k]): k for k in range(len(_IDS))}
+ _MAX = _INT.max(axis=1)
+ del _full # 释放原始DataFrame
+ import gc; gc.collect()
+
+ def _get_int(cid):
+ k = _row_of.get(int(cid))
+ return _INT[k] if k is not None else None
+ def _get_max(cid):
+ k = _row_of.get(int(cid))
+ return float(_MAX[k]) if k is not None else 0.0
+
+ def _corr_ok(id_a, id_b):
+ """跨样品Pearson相关(CAMERA标准:r>corr_cut 且 p 0) | (b > 0)
+ if mask.sum() < 4:
+ return True # 样品太少无法检验,放行(靠质量差+RT)
+ try:
+ r, pv = stats.pearsonr(a[mask], b[mask])
+ except Exception:
+ return True
+ if not np.isfinite(r):
+ return True
+ return (r > corr_cut) and (pv < corr_p)
+
+ # ---- 全局扫描:按m/z排序,每个峰在RT窗内找母峰 ----
+ arr = pdindex.sort_values(['m/z']).to_numpy() # 列: Compound, m/z, RT
+ comp = arr[:, 0]
+ mz = arr[:, 1].astype(float)
+ rt = arr[:, 2].astype(float)
+ n = len(comp)
+ order = np.argsort(mz)
+ mzs = mz[order]
+
+ cut_ions = []
+ cut_set = set()
+ mergegroups = {}
+
+ # 迭代到收敛(删除会改变可用母峰),最多几轮
+ changed = True
+ rounds = 0
+ while changed and rounds < 6:
+ changed = False
+ rounds += 1
+ for i in range(n):
+ cid = comp[i]
+ if cid in cut_set:
+ continue
+ m0, r0 = mz[i], rt[i]
+ i0 = _get_max(cid)
+ lo = np.searchsorted(mzs, m0 - (iso_max_n + 0.1))
+ hi = np.searchsorted(mzs, m0 - 1e-9)
+ for oi in range(lo, hi):
+ j = order[oi]
+ pid = comp[j]
+ if pid in cut_set or pid == cid:
+ continue
+ dm = m0 - mz[j]
+ if dm <= 0:
+ continue
+ if abs(rt[j] - r0) > rt_win:
+ continue
+ pmax = _get_max(pid)
+ if pmax <= 0:
+ continue
+ ratio = i0 / pmax
+ kmd = dm - math.floor(dm)
+ nn = round(dm / C13)
+ iso_dev = abs(dm - nn * C13) / m0 * 1e6 if nn >= 1 else 1e9
+
+ hit = False
+ # 同位素:整数13C间隔 + 弱于母峰(<比例上限) + (相关高 或 强度比很低)
+ if (1 <= nn <= iso_max_n) and (iso_dev < iso_ppm) and (0 < ratio <= iso_ratio_max):
+ if _corr_ok(pid, cid) or ratio < 0.5:
+ hit = True
+ # 二聚体:质量差小数部分≈0.5004(修正abs) + 弱于母峰 + 相关
+ if (not hit) and (abs(kmd - 0.5004) < dimer_tol) and (ratio < 0.7):
+ if _corr_ok(pid, cid):
+ hit = True
+ # 振铃:强度<母峰比例 + 质量差corr_cut 且 p 1e-6]
+
+ _full = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=[0,1,2], index_col=[0], low_memory=False)
+ mz_col = _full.columns[0]; rt_col = _full.columns[1]
+ mz_all = pd.to_numeric(_full[mz_col], errors='coerce').to_numpy()
+ rt_all = pd.to_numeric(_full[rt_col], errors='coerce').to_numpy()
+ ids = _full.index.to_numpy()
+ data_cols = list(_full.columns[2:])
+ samp_cols_for_corr = [c for c in data_cols if ('BLANK' not in str(c[0]).upper()) and (str(c[0]).upper()!='QC')]
+ INT_all = _full[data_cols].apply(pd.to_numeric, errors='coerce').fillna(0.0).to_numpy(dtype=np.float32)
+ CORR_mat = _full[samp_cols_for_corr].apply(pd.to_numeric, errors='coerce').fillna(0.0).to_numpy(dtype=np.float32)
+ row_of = {int(ids[k]): k for k in range(len(ids))}
+ del _full
+ import gc; gc.collect()
+
+ def detmean(k):
+ v = CORR_mat[k]; nz = v[v>0]
+ return float(nz.mean()) if nz.size else 0.0
+ detmean_all = np.array([detmean(k) for k in range(len(ids))])
+
+ def corr_ok(ka, kb):
+ a, b = CORR_mat[ka], CORR_mat[kb]
+ mask = (a>0)|(b>0)
+ if mask.sum() < 4: return True
+ try: r, pv = stats.pearsonr(a[mask], b[mask])
+ except Exception: return True
+ if not np.isfinite(r): return True
+ return (r > corr_cut) and (pv < corr_p)
+
+ order = np.argsort(mz_all)
+ mzs_sorted = mz_all[order]
+ assigned = {}
+ groups = {}
+ for i in range(len(ids)):
+ cid = int(ids[i])
+ if cid in assigned: continue
+ m0, r0 = mz_all[i], rt_all[i]
+ if not np.isfinite(m0): continue
+ members = [(cid, 'M+H')]
+ for name, delta in form_deltas:
+ target_mz = m0 + delta
+ lo = np.searchsorted(mzs_sorted, target_mz*(1-ppm/1e6)-0.001)
+ hi = np.searchsorted(mzs_sorted, target_mz*(1+ppm/1e6)+0.001)
+ for oi in range(lo, hi):
+ j = order[oi]; jid = int(ids[j])
+ if jid == cid or jid in assigned: continue
+ if abs(mz_all[j]-target_mz)/target_mz*1e6 > ppm: continue
+ if abs(rt_all[j]-r0) > rt_win: continue
+ if corr_ok(i, j):
+ members.append((jid, name)); assigned[jid] = (cid, name); break
+ if len(members) > 1:
+ groups[cid] = members; assigned[cid] = (cid, 'M+H')
+
+ removed_ids = set()
+ attribution_rows = []
+ header_cols = ['Compound','m/z','Retention time (min)','adduct_form','is_main'] + [str(c[2]) for c in data_cols]
+ form_map = {}
+ for base, members in groups.items():
+ best = max(members, key=lambda x: detmean_all[row_of[x[0]]])
+ main_id = best[0]
+ mem_forms = dict(members)
+ for mid, form in members:
+ form_map[mid] = form
+ if mid != main_id: removed_ids.add(mid)
+ def make_row(pid, form, is_main):
+ k = row_of[pid]
+ return [pid, round(mz_all[k],4), round(rt_all[k],4), form, ('main' if is_main else ''), *list(INT_all[k])]
+ attribution_rows.append(make_row(main_id, mem_forms[main_id], True))
+ for mid, form in members:
+ if mid != main_id:
+ attribution_rows.append(make_row(mid, form, False))
+ attribution_rows.append([None]*len(header_cols))
+
+ pd.DataFrame(attribution_rows, columns=header_cols).to_csv(
+ analysis_params.outputdir / 'adduct_attribution.csv', index=False)
+
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
+ iondict['pass_adduct'] = ~iondict.index.isin(removed_ids)
+ iondict['adduct_form'] = iondict.index.map(lambda x: form_map.get(x,''))
+ iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
+
+ print(' adduct grouping: %d groups, %d redundant ions moved to attribution table' % (len(groups), len(removed_ids)))
+ return removed_ids
+
+
+# -----Mass defect filter-----
+def md_plausible(mz, hi_slope, hi_int, lo_slope, lo_int):
+ """
+ 判断 m/z 是否可能是单电荷 CHNOPS 小分子离子。
+
+ 允许区间(按质量线性变化的质量亏损上下界):
+ 上界 hi(m) = hi_slope*m + hi_int (饱和烃 / 脂类, H 最多)
+ 下界 lo(m) = lo_slope*m + lo_int (高度磷酸化/硫酸化, 杂原子最多)
+ 质量亏损 = m/z - 名义质量, 名义质量未知。只要存在某个整数 N 使
+ lo <= m/z - N <= hi 即视为可能。这样不会出现 floor/round 带来的"翻转"
+ 问题(脂类亏损 >0.5、高分子量 >1 时依然正确)。
+ 注意: 区间宽度在 m/z ~650 以上超过 1 Da, 此时所有 m/z 都会通过 ——
+ 这是物理事实, 不是 bug: 质量亏损只能剔除低质量端的不可能离子。
+ """
+ mz = np.asarray(mz, dtype=float)
+ hi = hi_slope * mz + hi_int
+ lo = lo_slope * mz + lo_int
+ return np.ceil(mz - hi) <= np.floor(mz - lo)
+
+
+def mdfilter(analysis_params, ionfilterlist):
+ """
+ 质量亏损过滤:剔除 m/z 在化学上不可能对应单电荷 CHNOPS 分子的离子
+ (噪声、盐簇、背景离子、未识别的多电荷离子等)。
+
+ 结果写入:
+ - ionfilterlist['massdefect']
+ - iondict.csv 新增 'mass_defect'(m/z - round(m/z))与 'pass_mdfil'
+ (applyfilters 会自动应用所有 pass_* 列)
+ 若 md_drop_early=True(默认), 还会把不通过的离子直接从 _formatted.csv 删除,
+ 避免它们参与后续 decon(在源碎片聚类会把最高 m/z 当母离子, 一个不可能的
+ 高 m/z 噪声可能把真实离子误判为它的碎片)和 relationalfilter。
+ 因此请在 relationalfilter / decon 之前调用。
+
+ 可调参数(analysis_params, 带默认):
+ md_hi_slope (0.00112) md_hi_int (0.03) 上界
+ md_lo_slope (-0.00025) md_lo_int (-0.03) 下界
+ md_halogen (False) True 时下界放宽到含多个 Cl/Br 的水平
+ md_drop_early (True)
+ 默认值按 [M+H]+ 估计, ±0.03 的截距余量覆盖 [M+Na]+、[M+NH4]+、[M-H]- 等
+ 常见加合物的偏移。若有 HMDB/RefMet 拟合的包络线, 直接替换这四个数即可。
+ """
+ print('Running mass defect filter')
+
+ hi_slope = getattr(analysis_params, 'md_hi_slope', 0.00112)
+ hi_int = getattr(analysis_params, 'md_hi_int', 0.03)
+ lo_slope = getattr(analysis_params, 'md_lo_slope', -0.00025)
+ lo_int = getattr(analysis_params, 'md_lo_int', -0.03)
+ if getattr(analysis_params, 'md_halogen', False):
+ lo_slope = getattr(analysis_params, 'md_lo_slope_halogen', -0.0011)
+ lo_int = getattr(analysis_params, 'md_lo_int_halogen', -0.05)
+ drop_early = getattr(analysis_params, 'md_drop_early', True)
+
+ fpath = analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv')
+ idx = pd.read_csv(fpath, sep=',', header=[2], index_col=None)
+ idx = idx[['Compound', 'm/z']].copy()
+ idx['m/z'] = pd.to_numeric(idx['m/z'], errors='coerce')
+
+ ok = md_plausible(idx['m/z'].to_numpy(), hi_slope, hi_int, lo_slope, lo_int)
+ ok = ok & idx['m/z'].notna().to_numpy()
+ fail_ids = idx.loc[~ok, 'Compound'].tolist()
+ fail_str = set(str(x) for x in fail_ids)
+
+ ionfilterlist['massdefect'] = ionfilter(
+ {'hi_slope': hi_slope, 'hi_int': hi_int, 'lo_slope': lo_slope, 'lo_int': lo_int},
+ fail_ids)
+
+ # iondict: 写质量亏损和 pass 列(用字符串匹配 ID, 避免 int/str 类型不一致)
+ md_map = dict(zip(idx['Compound'].astype(str), idx['m/z'] - np.round(idx['m/z'])))
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
+ key = iondict.index.astype(str)
+ iondict['mass_defect'] = [md_map.get(k, np.nan) for k in key]
+ iondict['pass_mdfil'] = ~key.isin(fail_str)
+ iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
+
+ if drop_early and fail_ids:
+ msdata = pd.read_csv(fpath, sep=',', header=[0, 1, 2], index_col=[0])
+ msdata = msdata[~msdata.index.astype(str).isin(fail_str)]
+ msdata.to_csv(fpath, header=True, index=True)
+
+ print(' mass defect filter: %d / %d ions failed' % (len(fail_ids), len(idx)))
+ return ionfilterlist
+
+
+def mergeions(analysis_params, ion_filters):
+ """
+ Merges source to target ion abundances for mispicked peak filtering.
+
+ Parameters:
+ analysis_params (object): Analysis parameters.
+ ion_filters (dict): Dictionary of ion filters.
+
+ Returns:
+ None
+ """
+ # Read in the data
+ msdata_merged = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'), sep=',', header=[2], index_col=[0])
+
+ # Initialize variables
+ merge_dict = {}
+ source_list = []
+ drop_list = []
+
+ # Loop through each target ion and its associated sources
+ for target in ion_filters['relfil'].merge:
+ target_index = (target, msdata_merged.loc[target, 'm/z'], msdata_merged.loc[target, 'Retention time (min)'])
+ source_list = []
+ for source in ion_filters['relfil'].merge[target].sources:
+ source_list.append((source, msdata_merged.loc[source, 'm/z'], msdata_merged.loc[source, 'Retention time (min)']))
+ drop_list += source_list
+ merge_dict[target_index] = source_list
+
+ # Merge the ions in the data frame
+ msdata_merged = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'), sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
+ for target in merge_dict:
+ for source in merge_dict[target]:
+ msdata_merged.loc[target] += msdata_merged.loc[source]
+
+ # Drop the source ions
+ msdata_merged = msdata_merged.drop(drop_list, axis=0)
+
+ # Save the merged data frame
+ msdata_merged.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_merged.csv'), header=True, index=True)
+
+ # Format the merged data frame and save it
+ msdata_merged = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_merged.csv'), sep=',', header=None, index_col=None)
+ msdata_merged.iloc[2, 0:3] = ['Compound', 'm/z', 'Retention time (min)']
+ msdata_merged.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'), header=False, index=False)
+
+def applyfilters(analysis_params, ion_filters):
+ """
+ Apply filters to the data.
+
+ 改进版:以 iondict 的 pass_* 列为唯一依据删除,确保 filtered 表与 iondict 完全同步。
+ (原版用 ion_filters 字典,在多过滤器/多轮运行时易与 iondict 的 pass 列不同步,
+ 导致 filtered 里残留应删除的峰。)
+ 只有所有 pass_* 列都为 True 的特征才保留。
+ """
+ ms_data_out_filtered = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
+ sep=',', header=None, index_col=None)
+ # 读 iondict,取所有 pass_* 列
+ iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
+ passcols = [c for c in iondict.columns if str(c).startswith('pass')]
+ # 全部 pass 为 True 的 Compound 才保留
+ keep_mask = pd.Series(True, index=iondict.index)
+ for _c in passcols:
+ keep_mask = keep_mask & (iondict[_c].astype(str).str.strip().str.upper() == 'TRUE')
+ keep_ids = set(iondict.index[keep_mask].astype(str))
+
+ # formatted 前3行是表头(组/样品/列名),数据从第4行;第一列是 Compound
+ header = ms_data_out_filtered.iloc[:3]
+ body = ms_data_out_filtered.iloc[3:]
+ body_keep = body[body.iloc[:, 0].astype(str).isin(keep_ids)]
+ out = pd.concat([header, body_keep], ignore_index=True)
+ out.to_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_filtered.csv'),
+ index=False, header=False)
diff --git a/code/importdependencies.py b/code/importdependencies.py
index 71715f8..a72e802 100644
--- a/code/importdependencies.py
+++ b/code/importdependencies.py
@@ -1,136 +1,75 @@
"""
MPACT
Copyright 2022, Robert M. Samples, Sara P. Puckett, and Marcy J. Balunas
-
-Dependency bootstrap.
-
-A few of MPACT's dependencies are not part of a stock Anaconda install
-(``epam.indigo``, ``UpSetPlot`` and ``squarify``). These are imported at the
-top level of ``main.py`` / ``plotting.py``, so if any of them is missing the
-program crashes on import before it can do anything useful. This module
-detects the missing packages, installs them with pip, and -- because a freshly
-pip-installed package usually cannot be imported into an already-running
-interpreter/kernel (e.g. when launched through Spyder on Anaconda) -- tells the
-user to restart when that happens.
-
-``ensure_dependencies()`` is called once, as early as possible, from
-``main.py`` (before the packages it installs are imported).
"""
-import importlib
import subprocess
import sys
-
-# pip package name -> importable module name (required: gate startup if missing)
-DEPENDENCIES = {
- "epam.indigo": "indigo",
- "UpSetPlot": "upsetplot",
- "squarify": "squarify",
-}
-
-# Performance-only packages: installed best-effort, but a failure here must
-# never block startup (the code falls back to slower implementations).
-OPTIONAL_DEPENDENCIES = {
- "fastcluster": "fastcluster", # faster hierarchical clustering (heatmap, bootstrap dendrogram)
-}
-
-
-def _is_available(import_name):
- """Return True if ``import_name`` can be imported in this interpreter."""
- try:
- return importlib.util.find_spec(import_name) is not None
- except (ImportError, ValueError):
- # find_spec can raise for half-installed / namespace edge cases.
- return False
-
+from tkinter import *
+from tkinter import messagebox
+import os
+try:
+ import indigo
+except Exception:
+ pass
+try:
+ import upsetplot
+except Exception:
+ pass
+try:
+ import squarify
+except Exception:
+ pass
def install(package):
- """Install a single package with the current interpreter's pip.
+ subprocess.check_call([sys.executable, "-m", "pip", "install", package])
+
- IMPORTANT: this runs inside a conda (Anaconda) environment whose pandas,
- matplotlib, scipy, etc. are compiled against NumPy 1.x. A bare
- ``pip install`` can upgrade NumPy to 2.x as a side effect, which makes every
- one of those conda-compiled modules fail to import ("module compiled using
- NumPy 1.x cannot be run in NumPy 2.5.0"). We therefore constrain NumPy to
- <2 and only upgrade dependencies when strictly necessary, so installing an
- optional package can never break the environment.
- """
- subprocess.check_call([
- sys.executable, "-m", "pip", "install",
- "--upgrade-strategy", "only-if-needed",
- package, "numpy<2",
- ])
+installlist = {"epam.indigo":"indigo",
+ "UpSetPlot":"upsetplot",
+ "squarify":"squarify"}
def checkdep():
- """Install any missing dependencies.
-
- Silent when every dependency is already present -- this runs on every
- launch (including every Spyder "Run File", which re-executes main.py's
- top level), so printing a "checking/already installed" block every time
- is pure console noise once the environment is set up. Only installs (or
- failures) are reported.
-
- Returns a list of the pip package names that were freshly installed (these
- may require an interpreter/kernel restart before they can be imported).
- """
- installed = []
- for pip_name, import_name in DEPENDENCIES.items():
- if _is_available(import_name):
- continue
- print("Installing " + pip_name)
- try:
- install(pip_name)
- installed.append(pip_name)
- except Exception as exc: # pragma: no cover - network/pip dependent
- print("Failed to install " + pip_name + ": " + str(exc))
-
- # Optional/perf packages: try to install, but never treat a failure as fatal
- # and never report them as gating a restart.
- for pip_name, import_name in OPTIONAL_DEPENDENCIES.items():
- if _is_available(import_name):
- continue
- print("Installing optional " + pip_name)
- try:
- install(pip_name)
- except Exception as exc: # pragma: no cover - network/pip dependent
- print("Optional dependency " + pip_name + " not installed: " + str(exc))
-
- # Allow newly installed packages to be discovered without a restart where
- # the interpreter supports it.
- importlib.invalidate_caches()
- return installed
-
-
-def _notify_restart(message):
- """Best-effort, GUI-agnostic "please restart" notice."""
- print(message)
- try:
- from tkinter import Tk, messagebox
-
+ restartflag = False
+ installlist = {"epam.indigo":"indigo",
+ "UpSetPlot":"upsetplot",
+ "squarify":"squarify"}
+ print('Checking dependencies')
+ for package in list(installlist.keys()):
+ if installlist[package] in sys.modules:
+ print(package + " already installed")
+ else:
+ restartflag = True
+ print('installing ' + package)
+ install(package)
+
+ if restartflag:
root = Tk()
- root.withdraw() # don't show an empty root window
- messagebox.showinfo("Restart required", message)
- root.destroy()
- except Exception:
- # No display / tkinter unavailable -- the printed message is enough.
- pass
-
-
-def ensure_dependencies():
- """Make sure every dependency is importable, installing as needed.
-
- If a package had to be installed but still isn't importable in this
- process (the typical Spyder/Anaconda first-run case), the user is asked to
- restart and the process exits cleanly instead of crashing with an
- ImportError.
- """
- installed = checkdep()
-
- still_missing = [name for name in DEPENDENCIES.values() if not _is_available(name)]
- if still_missing:
- _notify_restart(
- "Dependencies were installed but require a restart.\n"
- "Please restart MPACT (or restart the kernel in Spyder)."
- )
- sys.exit(0)
+ root.geometry("1x1")
+ if messagebox.showinfo("Restart", "Dependencies installed, the kernal will restart\n Please restart MPACT"):
+ os._exit(00)
+
+ root.mainloop()
+
+ """
+ #code for pyqt version, doesn't work if main window not initialized
+ def show_info_messagebox():
+ msg = QMessageBox()
+ msg.setIcon(QMessageBox.Information)
+
+ # setting message for Message Box
+ msg.setText("Information ")
+
+ # setting Message box window title
+ msg.setWindowTitle("Information MessageBox")
+
+ # declaring buttons on Message Box
+ msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
+
+ # start the app
+ retval = msg.exec_()
+
+ show_info_messagebox()
+ show_info_messagebox()
+ """
\ No newline at end of file
diff --git a/code/main.py b/code/main.py
index c087d4a..49c3647 100644
--- a/code/main.py
+++ b/code/main.py
@@ -1,30 +1,23 @@
"""
MPACT
Copyright 2022, Robert M. Samples, Sara P. Puckett, and Marcy J. Balunas
-Modifications Copyright 2026, Robert M. Samples
"""
import re
import sys
-import multiprocessing
-import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
import time
import string
+import platform
from PyQt5 import QtCore, QtWidgets
-from PyQt5.QtWidgets import QMainWindow, QSizeGrip
-from PyQt5.QtCore import QObject, Qt
-from PyQt5.QtGui import QPixmap
+from PyQt5.QtWidgets import QMainWindow, QSizeGrip, QGraphicsDropShadowEffect, QFileDialog, QListWidgetItem, QColorDialog
+from PyQt5.QtCore import (QCoreApplication, QPropertyAnimation, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent)
+from PyQt5.QtGui import QBrush, QColor, QIcon, QPalette, QPainter, QPixmap
from pathlib import Path
-# Install/verify non-stock dependencies (epam.indigo, UpSetPlot, squarify)
-# before the modules that import them are loaded below.
-from importdependencies import ensure_dependencies
-ensure_dependencies()
-
# GUI FILE
from ui_main import Ui_MainWindow
import ui_plotparam
@@ -35,22 +28,9 @@
import files
from MSFaST import run_MSFaST, analysis_parameters
-from groupsets import GroupSetModel, build_query_dict
-from plotslots import PlotSlotRegistry
-from paramfields import save_checkbox_fields
-from csvcache import cached_read_csv, invalidate as invalidate_csv_cache
-from biogroups import compute_biological_groups
-from dbsearch import search_npatlas
-from searchtree import SearchTreePanel
-from plotting import plot_abund, show_spectrum, show_featureplt, plot_heatmap, plot_mzrt, plot_samplecorr, kendrick, plot_volcano, plot_fc3d, plot_dendrogram, plot_ordination, prev_cv, plot_upset, plot_treemap
+from plotting import plot_abund, show_spectrum, show_featureplt, plot_heatmap, plot_mzrt, plot_samplecorr, kendrick, plot_volcano, plot_fc3d, plot_dendrogram, plot_PCA, prev_cv, gen_upsetplt, gen_treemap
import getfragdb
-import webbrowser
-import npatlasupdate
-import mpactupdate
-import crashreport
-from dialogs import styled_message_box
-
from indigo import Indigo
from indigo.renderer import IndigoRenderer
indigo = Indigo()
@@ -77,35 +57,34 @@
-add bypass for plots based on checkmark. possibly use if check: ... else: button.hide() then pass
- distribution of CVs on bottom of cvplt?
+- add pca option and allow visualization of key features on multivar plt?
#TODO#
-- in source spectra viewer in spectrum details tab plot with preexisting in source fragment deconvolution algoirthm
-- clean up import sections and general code for better maintability and good syntax/standards
- ~main.py's own import section done (dead PyQt5/stdlib/groupsets imports removed,
- verified unused via pyflakes + grep, no behavior change); other files not yet swept
-- do overall data quality score, AUC on CV plot or something, may be present in a different form already
+#Easy/high priority
+- in source spectra
+- do overall data quality score, AUC
- standardize method and class names
-- add terminal output with current line to status bar instead of just static status messages, perhaps with expand button to show full terminal output
-- potentially consider other database options like HMDB etc
-- fix up analysisinfo file output with better and more useful log ingo
-- add other ordination options like pca, pls-da, etc etc
- ~DONE: the multivariate tab now offers PCA / NMDS / PLS-DA via a method
- switcher (ordination.py, plotting.plot_ordination). Next candidate is
- OPLS-DA (intentionally deferred -- no native sklearn support; see
- devnotes.md "Multivariate ordination plot").
+- database management, options
+- fix up analysisinfo file output
+
+#Medium priority
+- mzmine msp file import
+- add other ordination options
- add custom keyword arguments for each plot to make calling them easier
-- make it so groups can be reordered in the groupsets widgets?
- ~model-layer support done: GroupSetModel.move() (groupsets.py), tested in
- test_groupsets.py. UI drag-drop wiring (listWidget_pltgrps InternalMove +
- syncing its rowsMoved signal to model.move()) not done -- needs a live
- GUI session to verify the selection-tracking interacts correctly with
- updatesets()'s existing blockSignals dance, which isn't something to
- guess at unverified
-- consider if indexing and feature highly functions in plot options have any easy wins for optimization or disk use. (prob not)
+- add more conditionals so if one plot fails it doesn't kill everything else
+- add runcheck before searching when switching to search tab
+- Figure out way to have only active plot be updated and then to update others
+ when plot is switched
+- change treewidget in search tab to treeview for better search, add filter options
+- make it so groups can be reordered
+- make it so iondict and msdata are saved as a parent object so they dont need to
+ be reopened each time a heatmap feature is scrolled. This may actually not
+ be a good idea depending on ram demands
- make goto buttons just one class and lambda an index for the stacked widgets
when connecting!
-likely items that need more thought and planning
+#low priority/long term
+- Switch to MVC format for groupsets
- maybe have a comparison mode for many different strains with and without elicitor
- specificity/sensitivity plot
- other statistical models
@@ -120,14 +99,17 @@
generated each time if filtering is off but they are always true
'''
-class query:
- """Legacy groupset shape, kept only so old ``.mpct`` files (which pickle
- this class by qualified name ``main.query``) can still be unpickled.
+class NumericalTreeWidgetItem(QtWidgets.QTreeWidgetItem):
+ def __lt__(self, other):
+ column = self.treeWidget().sortColumn() # the second column
+ try:
+ return float(self.text(column)) < float(other.text(column))
+ except ValueError: # fallback to alphabetical sorting if the text is not a number
+ return super().__lt__(other)
- Live code uses ``groupsets.GroupSet``/``GroupSetModel`` instead; on load,
- any ``query`` objects found in a save file are converted via
- ``GroupSet.from_legacy`` (see ``MainWindow.read_save``). Do not use this
- class for new code.
+class query:
+ """
+ Defines conditions (group presence/absence) to plot feature in a colour
"""
def __init__(self):
self.name = ''
@@ -137,35 +119,6 @@ def __init__(self):
self.colour = '#000000'
-class AnalysisWorker(QObject):
- """Runs the heavy, Qt-free computation (``run_MSFaST``) on a worker thread.
-
- Only the pure pandas/numpy/file-I/O step is moved off the GUI thread;
- matplotlib/Qt plot generation must stay on the main thread and runs in
- ``MainWindow._finish_analysis`` once ``finished`` is emitted.
- """
- finished = QtCore.pyqtSignal()
- failed = QtCore.pyqtSignal(str)
-
- def __init__(self, window):
- QObject.__init__(self)
- self.window = window
-
- def run(self):
- try:
- result = run_MSFaST(self.window.analysis_paramsgui)
- self.window.ionfilters = result.ionfilters
- self.window.groupionlists = result.groupionlists
- self.window.groupsets = result.groupsets
- self.window.filtereddfs = result.filtereddfs
- except Exception:
- import traceback
- traceback.print_exc()
- self.failed.emit('Processing failed (see console)')
- return
- self.finished.emit()
-
-
fullruntime = 0
@@ -251,16 +204,8 @@ def __init__(self):
#self.show() # makes window reappear, acts like normal window now (on top now but can be underneath if you raise another window)
self.ui.setupUi(self)
- self.ui.label_credits.setText('v1.00.02 r26.06.30')
-
- # "PCA" was a misnomer left over from when this checkbox/button only
- # ran NMDS (see plotting.plot_ordination) -- the underlying
- # checkBox_pca objectName/analysis_params.PCA attribute stay
- # unchanged for .mpct save-file compatibility; only the visible text
- # and tooltip change.
- self.ui.checkBox_pca.setText('Multivariate')
- self.ui.btn_pca.setToolTip('Multivariate Ordination (PCA/NMDS/PLS-DA)')
-
+ self.ui.label_credits.setText('v1.00 r24.11.17')
+
#initialize other dialog windows
self.dialog = dialog()
self.ftrdialog = ftrdialog()
@@ -272,7 +217,8 @@ def __init__(self):
self.pickedfeature = ''
self.highlightcol = 'yellow'
self.dbsearchdone = False
- self.groupsetmodel = GroupSetModel() # the groupset MVC model
+ self.selset = -1 #selected groupset index, refactor with MVC design
+ self.querys = [] #dictionary of the query/groupset objects
self.groups = [] #biological groups in the dataset
self.filename = Path.cwd()
self.extractmetadatafilename = Path.cwd()
@@ -289,24 +235,16 @@ def __init__(self):
- # Per-plot widget/render state, one PlotSlot per plot name internally;
- # these six attributes are dict-like views over that single registry
- # (see plotslots.py) so existing self.fig['heatmap']-style call sites
- # throughout plotting.py and main.py work unchanged.
- self._plotslots = PlotSlotRegistry()
- self.fig = self._plotslots.fig
- self.canvas = self._plotslots.canvas
- self.pltlayout = self._plotslots.pltlayout
- self.toolbar = self._plotslots.toolbar
- self.ax = self._plotslots.ax
- self.highlight = self._plotslots.highlight
+ #initialize figure element dictionaries, can call with self.currplot as key
+ self.fig = {}
+ self.canvas = {}
+ self.pltlayout = {}
+ self.toolbar = {}
+ self.ax = {}
+ self.highlight = {}
self.ui.btn_run.clicked.connect(self.run_analysis)
- # Replaces the Designer-created QTreeWidget with a real QTreeView +
- # per-column filter bar (searchtree.py) -- doesn't edit ui_main.py,
- # see SearchTreePanel's docstring for how the runtime swap works.
- self.searchtree = SearchTreePanel(self.ui.treeWidget)
- self.searchtree.view.selectionModel().selectionChanged.connect(self.on_tree_item_selection_changed)
+ self.ui.treeWidget.itemSelectionChanged.connect(self.on_tree_item_selection_changed)
def moveWindow(event):
@@ -322,12 +260,6 @@ def moveWindow(event):
UIFunctions.uiDefinitions(self)
self.show()
- # Deferred (post-show) best-effort startup checks: prompt to refresh a
- # stale NPAtlas database and to install a newer MPACT release. Run via
- # singleShot so the window paints first; fully guarded so they can
- # never block or break launch. GUI-only path -- verify by launching.
- QtCore.QTimer.singleShot(0, self._run_startup_checks)
-
#---Methods---
@@ -551,104 +483,33 @@ def update_mgf_feature_id(entry_lines, new_id):
def error(self, message):
self.ui.label_status.setText(message)
self.ui.label_status.setStyleSheet('color: rgb(150,0,0);')
-
- # ---- Startup checks (atlas freshness + app self-update) ----
- # All best-effort and fully guarded: any failure is logged to the console
- # and otherwise ignored so a check can never block or break launch. The
- # Qt-free logic lives in npatlasupdate.py / mpactupdate.py (unit-tested);
- # these methods are only the dialog/wiring layer and need a live launch to
- # verify end to end.
- def _run_startup_checks(self):
- try:
- self._check_atlas_freshness()
- except Exception as exc:
- print('Atlas update check skipped:', exc)
- try:
- self._check_app_update()
- except Exception as exc:
- print('App update check skipped:', exc)
-
- def _check_atlas_freshness(self, atlas_path='npatlas.tsv', max_age_days=30):
- """Offer to re-download the Natural Products Atlas if the local copy is
- missing or older than ``max_age_days``."""
- if not npatlasupdate.is_update_due(atlas_path, max_age_days=max_age_days):
- return
- age = npatlasupdate.atlas_age_days(atlas_path)
- age_msg = 'missing' if age is None else ('about %d days old' % int(age))
- reply = styled_message_box(
- self, QtWidgets.QMessageBox.Question, 'Update Natural Products Atlas?',
- 'Your local Natural Products Atlas database is %s.\n\n'
- 'Download the latest copy from npatlas.org now (about 30 MB)?' % age_msg,
- buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
- default=QtWidgets.QMessageBox.No)
- if reply != QtWidgets.QMessageBox.Yes:
- return
- # The download is large and runs on the main thread (wait cursor); a
- # failed/partial transfer never clobbers the existing atlas (atomic
- # replace in npatlasupdate.download_atlas). Threading this is a future
- # improvement -- see devnotes.md.
- self.ui.label_status.setText('Downloading Natural Products Atlas...')
- QtWidgets.QApplication.setOverrideCursor(Qt.WaitCursor)
- QtWidgets.QApplication.processEvents()
- try:
- n = npatlasupdate.download_atlas(atlas_path)
- self.ui.label_status.setText('Natural Products Atlas updated (%.1f MB).' % (n / 1e6))
- except Exception as exc:
- self.error('Atlas update failed (kept existing copy): ' + str(exc))
- finally:
- QtWidgets.QApplication.restoreOverrideCursor()
-
- def _check_app_update(self):
- """Check GitHub for a newer MPACT release; offer a git-pull update."""
- info = mpactupdate.check_for_update(timeout=5)
- if not info.available:
- return
- notes = (info.notes or '').strip()
- if len(notes) > 800:
- notes = notes[:800] + '...'
- reply = styled_message_box(
- self, QtWidgets.QMessageBox.Question, 'MPACT update available',
- 'A newer MPACT release is available.\n\n'
- 'Installed: %s\nLatest: %s\n\n%s\n\n'
- 'Update now (git pull)?' % (info.current, info.latest, notes),
- buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
- default=QtWidgets.QMessageBox.No)
- if reply != QtWidgets.QMessageBox.Yes:
- return
- repo_dir = Path(__file__).resolve().parent.parent
- ok, output = mpactupdate.apply_git_update(repo_dir)
- if ok:
- styled_message_box(
- self, QtWidgets.QMessageBox.Information, 'Update complete',
- 'MPACT was updated. Please restart the application.\n\n' + output)
- else:
- self.error('Automatic update failed; opening the release page instead.')
- if info.url:
- webbrowser.open(info.url)
-
+
def getgroups(self):
"""
Get biological groups on input of all input files, fills comboboxes with these.
"""
+ extractmetadata = pd.read_csv(self.extractmetadatafilename, sep=',', header=[0], index_col=None)
+ samplelist = pd.read_csv(self.samplelistfilename, sep=',', header=[0], index_col=None)
+
try:
- groups, unresolved = compute_biological_groups(
- self.extractmetadatafilename, self.samplelistfilename, self.filename)
- except ValueError as exc:
- self.error(str(exc))
+ combinedmetadata = extractmetadata.set_index('Sample_Code').join(samplelist.set_index('Sample_Code')) \
+ .reset_index().set_index('Injection')
+ except Exception:
+ self.error('Data read failure: Check input files')
return
-
- if unresolved:
- # Report once, not once per row -- a dataset with many injections
- # missing from the metadata join would otherwise spam the console
- # with no visible indication anything is wrong, and self.groups
- # would silently end up incomplete with no signal to the combo
- # boxes/groupset editor that consume it.
- unique_unresolved = sorted(set(map(str, unresolved)))
- print(f"getgroups: {len(unique_unresolved)} injection(s) had no "
- f"matching Biological_Group and were skipped: {unique_unresolved}")
- self.error(f"{len(unique_unresolved)} injection(s) missing from "
- "metadata -- biological group list may be incomplete.")
-
+
+ msdata = pd.read_csv(self.filename, sep=',', header=None, index_col=[0, 1, 2])
+ groups = []
+
+ for elem in msdata.iloc[2]:
+ biolgroup = combinedmetadata.loc[elem, 'Biological_Group']
+ try:
+ if biolgroup not in groups:
+ groups.append(combinedmetadata.loc[elem, 'Biological_Group'])
+ except Exception:
+ print(biolgroup)
+ print("")
+ print(groups)
self.groups = groups
# Set experimental and control grp defaults in ui
@@ -683,42 +544,88 @@ def fulldbsearch(self):
Run a full compound database search. Filter the database matches within a specified mass window.
Concatenate the hits and sort them by parts-per-million (ppm).
"""
- self.hitdb, _ = search_npatlas(
- self.analysis_paramsgui.outputdir,
- self.analysis_paramsgui.filename.stem,
- self.atlas,
- self.analysis_paramsgui.ppmthresh,
- )
+ self.hitdb = {}
+ iondict = pd.read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=[0])
+ iondict['hits'] = ''
+ msdata = pd.read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[2], index_col=None).iloc[:, :3]
+
+ for _, mrow in msdata.iterrows():
+ # Iterates over iondict, filters DB matches within window.
+ # Repeats for adducts, uses length of concat DF for feature hits
+ mass = mrow['m/z']
+ ppmwindow = self.analysis_paramsgui.ppmthresh
+ hits_h = self.atlas[abs(1000000 * (self.atlas['compound_m_plus_h'] - mass) / self.atlas['compound_m_plus_h']) < ppmwindow]
+ hits_h['ppm'] = abs(1000000 * (hits_h['compound_m_plus_h'] - mass) / hits_h['compound_m_plus_h'])
+ hits_na = self.atlas[abs(1000000 * (self.atlas['compound_m_plus_na'] - mass) / self.atlas['compound_m_plus_na']) < ppmwindow]
+ hits_na['ppm'] = abs(1000000 * (hits_na['compound_m_plus_na'] - mass) / hits_na['compound_m_plus_na'])
+ hits = pd.concat([hits_h, hits_na])
+ hits = hits.sort_values(by=['ppm'])
+ self.hitdb[mrow['Compound']] = hits
+ iondict.loc[mrow['Compound'], 'hits'] = hits.shape[0]
+
+ iondict.to_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', header=True, index=True)
def fillfttree(self):
# Fill feature tree with database hits
- iondict = cached_read_csv(
+ iondict = pd.read_csv(
self.analysis_paramsgui.outputdir / 'iondict.csv',
sep=',',
header=[0],
index_col=None
)
iondict = iondict[iondict['hits'] >= 0]
+ self.ui.treeWidget.setSortingEnabled(True)
- # Rows in searchtree.COLUMNS order (Compound, m/z, TR, Max, Sets,
- # Groups, FC, Hits) -- raw values, not pre-formatted strings; the
- # model formats numeric columns for display and keeps the raw value
- # available for proper numeric sort/filter (see IonTableModel).
- rows = [
- (row['Compound'], row['m/z'], row['Retention time (min)'], row['max'],
- row['groups'], row['groups'], row['fc'], row['hits'])
- for _, row in iondict.iterrows()
- ]
- self.searchtree.set_rows(rows)
-
+ itemdict = {}
+ self.ui.treeWidget.clear()
+ for i, row in iondict.iterrows():
+ item = NumericalTreeWidgetItem([
+ row['Compound'],
+ str(round(row['m/z'], 4)),
+ str(round(row['Retention time (min)'], 3)),
+ str(int(row['max'])),
+ str(row['groups']),
+ str(row['groups']),
+ str(round(row['fc'], 2)),
+ str(int(row['hits']))
+ ])
+ itemdict[i] = item
+ self.ui.treeWidget.addTopLevelItem(item)
+ # Optionally expand all items
+ # self.ui.treeWidget.expandAll()
+
+ def onItemClicked():
+ if len(self.ftrdialog.ui.treeWidget.selectedItems()) > 0:
+ item = self.ftrdialog.ui.treeWidget.selectedItems()[0]
+ smiles = item.text(5)
+ if smiles:
+ try:
+ m = indigo.loadMolecule(smiles)
+ indigo.setOption('render-image-size', '400,400')
+ image_path = f'compoundimages/{item.text(0)}.png'
+ renderer.renderToFile(m, image_path)
+ pixmap = QPixmap(image_path)
+ pixmap2 = pixmap.scaled(400, 400, QtCore.Qt.KeepAspectRatio)
+ self.ftrdialog.ui.label.setPixmap(pixmap2)
+ except Exception as e:
+ print(f"Error rendering molecule for {item.text(0)}: {e}")
+ # Optionally, display a default image or message
+ else:
+ print(f"No SMILES string available for {item.text(0)}")
+ # Handle the case where SMILES is empty
+
def on_tree_item_selection_changed(self):
- name = self.searchtree.selected_compound()
- if name:
+ selected_items = self.ui.treeWidget.selectedItems()
+ if selected_items:
+ item = selected_items[0]
+ # Get the name from the first column
+ name = item.text(0)
+ #print(f"Selection changed: {name}")
# Call the method to highlight the feature
self.highlight_feature(name)
@@ -787,20 +694,11 @@ def clean_ascii(text):
def highlight_feature(self, newfeature):
"""
- Select (or, if the same feature is clicked twice, deselect) a feature
- and highlight it across all plots.
-
- This is the entry point for actual selection events (clicking a plot
- point, a tree row, or arrow-key heatmap navigation) -- it is where the
- "click the same feature twice to clear it" toggle belongs. To simply
- refresh the displays for the *currently* selected feature (e.g. when
- switching tabs in the feature-info dialog) call ``_refresh_highlight``
- instead; calling this method with ``newfeature == self.pickedfeature``
- would incorrectly toggle the highlight off.
-
+ Highlights the selected feature in all plots.
+
Args:
newfeature (str): The name of the new feature to highlight.
-
+
Returns:
None.
"""
@@ -809,50 +707,33 @@ def highlight_feature(self, newfeature):
self.highlightcol = (0, 0, 0, 0)
else:
self.highlightcol = 'yellow'
-
- self.pickedfeature = newfeature
- self._refresh_highlight()
-
- def _refresh_highlight(self):
- """Redraw every plot/dialog for the current ``self.pickedfeature`` and
- ``self.highlightcol`` without changing selection state.
-
- Safe to call repeatedly (e.g. on every feature-info tab switch) since,
- unlike ``highlight_feature``, it never toggles ``highlightcol``. Also
- guards against the feature-info plot objects (``abundplt``/``spec``)
- not existing yet, and against the current feature not being present in
- the loaded fragmentation database.
- """
+
+ # Highlight the selected feature in all plots
for plot in self.highlight:
self.highlight[plot].set_color(self.highlightcol)
-
- if not self.pickedfeature:
- return
-
+
+ # Set the selected feature as the picked feature
+ self.pickedfeature = newfeature
+
# Read iondict file to get ion data
- iondict = cached_read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv',
+ iondict = pd.read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv',
sep=',', header=[0], index_col=[0])
-
+
# Update volcano plot with the selected feature
if self.analysis_paramsgui.Volcanoplt:
- # 'logfc' is never persisted to iondict.csv -- plot_volcano
- # computes it in-memory from 'fc' (np.log2(iondict['fc'])) each
- # time it draws, rather than writing it back to disk. Derive it
- # the same way here instead of indexing a column that doesn't
- # exist in the file.
self.highlight['volcano'].set_data(
- [np.log2(iondict.loc[self.pickedfeature, 'fc'])],
+ [iondict.loc[self.pickedfeature, 'logfc']],
[iondict.loc[self.pickedfeature, '-logq']]
)
self.canvas['volcano'].draw_idle()
-
+
# Update MZRT plot with the selected feature
self.highlight['mzrt'].set_data(
[iondict.loc[self.pickedfeature, 'Retention time (min)']],
[iondict.loc[self.pickedfeature, 'm/z']]
)
self.canvas['mzrt'].draw_idle()
-
+
# Update KMD plot with the selected feature
if self.analysis_paramsgui.KMD:
self.highlight['kmd'].set_data(
@@ -860,26 +741,19 @@ def _refresh_highlight(self):
[iondict.loc[self.pickedfeature, 'kmd']]
)
self.canvas['kmd'].draw_idle()
-
- # Update the multivariate plot's loadings-view highlight (a separate
- # concept from its scores view, which highlights a clicked *sample*
- # via parent.pickedsample, not a feature -- so this only applies
- # when self.pca exists and is currently showing loadings).
- if getattr(self, 'pca', None) is not None:
- self.pca.highlight_loading(self.pickedfeature, self.highlightcol)
-
+
# Update feature plot with the selected feature
self.highlight['featureplt'].set_data(
[iondict.loc[self.pickedfeature, 'Retention time (min)']],
[iondict.loc[self.pickedfeature, 'm/z']]
)
self.canvas['featureplt'].draw_idle()
-
+
msdata = pd.read_csv(
self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'),
sep=',', header=[2], index_col=[0]
)
-
+
# Set heatmap highlight based on view
self.heatind = self.cmind.index(msdata.index.to_list().index(self.pickedfeature))
xlim = int(self.canvas['heatmap'].figure.axes[2].get_xlim()[1])
@@ -888,23 +762,16 @@ def _refresh_highlight(self):
[self.heatind, self.heatind, self.heatind+1, self.heatind+1, self.heatind]
)
self.canvas['heatmap'].draw_idle()
-
+
# Run search when feature is selected
if self.ftrdialog.ui.stackedWidget.currentIndex() == 0 and not self.ftrdialog.isHidden():
self.runsearch(iondict.loc[self.pickedfeature, 'm/z'])
-
- # Reset spec if a fragmentation database with this feature is loaded.
- # spec may not exist yet (e.g. a prior dataset had no frag file) and
- # the feature may not be present in a newly-loaded fragdb, so both are
- # guarded rather than assumed.
- fragdb = getattr(self, 'fragdb', 'None')
- if self.fragfilename != '' and getattr(self, 'spec', None) is not None \
- and fragdb != 'None' and self.pickedfeature in getattr(fragdb, 'ions', {}):
- self.safe_generate('spectrum plot', self.spec.reset, fragdb.ions[self.pickedfeature].pattern)
-
- if self.ftrdialog.ui.stackedWidget.currentIndex() == 2 and not self.ftrdialog.isHidden() \
- and getattr(self, 'abundplt', None) is not None:
- self.safe_generate('abundance plot', self.abundplt.reset)
+
+ # Reset spec if fragfilename exists and update abundplt
+ if self.fragfilename != '':
+ self.spec.reset(self.fragdb.ions[self.pickedfeature].pattern)
+ if self.ftrdialog.ui.stackedWidget.currentIndex() == 2 and not self.ftrdialog.isHidden():
+ self.abundplt.reset()
# Move heatmap selection up or down with W/S key press
@@ -926,23 +793,10 @@ def mv_heatmap(self, shift):
"""
if self.ui.stackedWidget_plot.currentIndex() != 8 or self.ui.stackedWidget.currentIndex() != 3:
return
-
- cmind = getattr(self, 'cmind', None)
- heatind = getattr(self, 'heatind', None)
- if not cmind or heatind is None:
- return
-
- # Clamp rather than wrap/raise: Python's negative indexing would
- # silently jump to the opposite end of the list on underflow, and an
- # unclamped index overflows with IndexError on the last row -- both
- # triggerable just by holding W/S past either end of the heatmap.
- new_heatind = max(0, min(len(cmind) - 1, heatind + shift))
- if new_heatind == heatind:
- return
-
- iondict = cached_read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=[0])
- msdata = cached_read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[2], index_col=[0]).iloc[:, 2:]
- index = cmind[new_heatind]
+
+ iondict = pd.read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=[0])
+ msdata = pd.read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[2], index_col=[0]).iloc[:, 2:]
+ index = self.cmind[self.heatind + shift]
name = msdata.index.tolist()[index]
self.ui.lbl_featurename.setText('Compound: ' + name)
@@ -957,17 +811,12 @@ def read_save(self, savefile):
Args:
savefile (Path): The path to the saved session file.
"""
- # Loading a session may point at an entirely different dataset's
- # output directory -- drop any cached reads from whatever was
- # previously loaded/analysed.
- invalidate_csv_cache()
-
print("read1")
with open(savefile, 'rb') as read_pi:
print("read3")
self.savedata = pickle.load(read_pi)
print("read2")
-
+
# Assign the analysis parameters
self.analysis_paramsgui = self.savedata['parameters']
@@ -997,286 +846,96 @@ def read_save(self, savefile):
self.filename = self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata' / self.analysis_paramsgui.filename.name
- # Get groups and load groupsets (accepts both old pickled `query`
- # objects and current `GroupSet` objects -- see GroupSet.from_legacy).
+ # Get groups and update querys
self.getgroups()
- self.groupsetmodel = GroupSetModel.from_legacy_list(self.analysis_paramsgui.queries)
+ self.querys = self.analysis_paramsgui.queries
UIFunctions.updatesets(self)
def write_save(self):
- """Write the current analysis session to a ``.mpct`` (pickle) file.
-
- Each component is captured defensively, so that one unreadable input
- (e.g. a file held open by another program) does not abort the whole
- save. The pickle is written to a temporary file that atomically
- replaces the target, so an interrupted save cannot corrupt an existing
- ``.mpct``.
+ """Writes the current analysis session to a pickle file.
"""
- params = self.analysis_paramsgui
- params.queries = self.groupsetmodel.to_legacy_list() # plain GroupSet list
-
- def _capture(label, reader, default=None):
- try:
- return reader()
- except Exception:
- import traceback
- print('Warning: could not capture ' + label + ' for save:')
- traceback.print_exc()
- return default
-
- savedata = dict(self.savedata)
- savedata['parameters'] = params
- savedata['peaktable'] = _capture(
- 'peak table',
- lambda: pd.read_csv(params.outputdir / params.filename.name, sep=',', header=None, index_col=None, low_memory=False))
- savedata['samplelist'] = _capture(
- 'sample list',
- lambda: pd.read_csv(self.samplelistfilename, sep=',', header=None, index_col=None))
- savedata['extractmetadata'] = _capture(
- 'extract metadata',
- lambda: pd.read_csv(self.extractmetadatafilename, sep=',', header=None, index_col=None))
- if params.fragfilename != '':
- savedata['fragdb'] = _capture(
- 'fragment database',
- lambda: Path(params.fragfilename).read_text(), default='None')
+ self.analysis_paramsgui.queries = self.querys # WRITES QUERY DB FOR GROUPSETS IN ANALYSISPARAMETERS, WILL NEED TO CHANGE WHEN MVC IMPLEMENTED
+ file_pi = open(self.analysis_paramsgui.outputdir/(self.analysis_paramsgui.filename.stem + '.mpct'), 'wb')
+ self.savedata['parameters'] = self.analysis_paramsgui
+ self.savedata['peaktable'] = pd.read_csv(self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.name, sep = ',', header = None, index_col = None)
+ self.savedata['samplelist'] = pd.read_csv(self.samplelistfilename, sep = ',', header = None, index_col = None)
+ self.savedata['extractmetadata'] = pd.read_csv(self.extractmetadatafilename , sep = ',', header = None, index_col = None)
+ if self.analysis_paramsgui.fragfilename != '':
+ fragmsp = open(self.analysis_paramsgui.fragfilename, 'r')
+ self.savedata['fragdb'] = fragmsp.read()
+ fragmsp.close()
else:
- savedata['fragdb'] = 'None'
- self.savedata = savedata
-
- target = params.outputdir / (params.filename.stem + '.mpct')
- tmp = target.with_name(target.name + '.tmp')
- try:
- with open(tmp, 'wb') as file_pi:
- pickle.dump(savedata, file_pi)
- os.replace(tmp, target) # atomic replace on the same filesystem
- except Exception:
- import traceback
- print('Error saving .mpct file:')
- traceback.print_exc()
- self.error('Analysis complete but save failed (see console)')
- try:
- if tmp.exists():
- tmp.unlink()
- except Exception:
- pass
+ self.savedata['fragdb'] = 'None'
+ pickle.dump(self.savedata, file_pi)
+ file_pi.close()
- def export_filtered_outputs(self):
- """Write post-filter exports next to the analysis output (best-effort).
-
- - The filtered peak table in its source layout (a row subset of the
- input file; matched by compound id, falling back to m/z + RT).
- - If a fragmentation file is loaded, an MSP/MGF re-indexed so its entry
- IDs match the filtered peak-table row order -- the form GNPS2 expects.
-
- Failures are logged and never abort the analysis.
- """
- import translators
- params = self.analysis_paramsgui
- filtered_internal = params.outputdir / (params.filename.stem + '_filtered.csv')
-
- try:
- source = Path(params.filename)
- out = params.outputdir / (params.filename.stem + '_filtered_source' + source.suffix)
- count = translators.filter_source_peaktable(source, filtered_internal, out)
- print('Wrote filtered source peak table (' + str(count) + ' features): ' + str(out))
- except Exception:
- import traceback
- print('Could not export filtered source peak table:')
- traceback.print_exc()
-
- fragfile = getattr(params, 'fragfilename', '')
- if fragfile:
- try:
- fragpath = Path(fragfile)
- out = params.outputdir / (fragpath.stem + '_reindexed' + fragpath.suffix)
- count = translators.reindex_fragments(filtered_internal, fragpath, out)
- print('Wrote GNPS2 re-indexed fragments (' + str(count) + ' entries): ' + str(out))
- except Exception:
- import traceback
- print('Could not re-index fragmentation file:')
- traceback.print_exc()
-
- def safe_generate(self, label, func, *args, **kwargs):
- """Run a plot/generation step so a single failure is non-fatal.
-
- Logs the traceback and notes the failure in the status bar, then
- returns None so the remaining plots are still generated.
- """
- try:
- return func(*args, **kwargs)
- except Exception:
- import traceback
- print('Error generating ' + label + ':')
- traceback.print_exc()
- self.ui.label_status.setText('Warning: ' + label + ' failed (see console)')
- return None
-
- def _create_or_reset(self, attr, label, create_call, reset_call=None):
- """Create a plot object the first time it's needed, or reset() it if
- it already exists.
-
- Plot (re)generation used to be gated entirely on ``self.analysisrun``
- (a whole-session "has any analysis completed" flag): the very first
- analysis created every enabled plot, and every later run/regenerate
- only ever called ``.reset()`` on them. That breaks as soon as an
- optional output toggles between runs in the same session -- e.g. the
- first dataset has no fragmentation file (so ``self.spec`` is never
- created) and a later dataset does: ``self.spec.reset(...)`` would then
- raise ``AttributeError`` because the object was never created. Keying
- the create-vs-reset decision off whether the attribute already exists
- (rather than off analysisrun) fixes this for every optional plot.
- """
- if getattr(self, attr, None) is None:
- result = self.safe_generate(label, create_call)
- if result is not None:
- setattr(self, attr, result)
- elif reset_call is not None:
- self.safe_generate(label, reset_call)
-
- def _generate_plots(self):
- """Create or refresh every plot for the current analysis parameters.
-
- Shared by the post-compute step (``_finish_analysis``, after a fresh
- ``run_MSFaST``) and the dialog's "Apply" button (``regenerateplts``),
- so both paths get the same create-if-missing safety net.
- """
- params = self.analysis_paramsgui
- pltfile = params.outputdir / (params.filename.stem + '_filtered.csv')
- iondictfile = params.outputdir / 'iondict.csv'
- dfs = self.filtereddfs
- grpsts = self.groupsets
-
- self._create_or_reset('treemap', 'treemap',
- lambda: plot_treemap(self, 'treemap', self.ui.frame_treemap, pltfile, '', ''),
- lambda: self.treemap.reset(pltfile, '', ''))
- stop_functime('treemap complete')
-
- if params.CVfil:
- self._create_or_reset('prevcv', 'CV plot',
- lambda: prev_cv(self, 'cvplt', self.ui.frame_cvplt, 'none', 'none', 'none'),
- lambda: self.prevcv.reset(self, '', ''))
- stop_functime('cvplt complete')
-
- self._create_or_reset('ftplt', 'feature plot',
- lambda: show_featureplt(self, 'featureplt', self.ui.frame_featureplt, iondictfile, '', ''),
- lambda: self.ftplt.reset(iondictfile, '', ''))
- stop_functime('ftplt complete')
-
- self._create_or_reset('dend', 'dendrogram',
- lambda: plot_dendrogram(self, 'dend', self.ui.frame_dend, pltfile, '', ''),
- lambda: self.dend.reset(pltfile, '', ''))
- stop_functime('dendrogram complete')
-
- if params.PCA:
- self._create_or_reset('pca', 'multivariate ordination plot',
- lambda: plot_ordination(self, 'pca', self.ui.frame_pca, pltfile, '', ''),
- lambda: self.pca.reset(pltfile, '', ''))
- stop_functime('ordination complete')
-
- if params.FC3Dplt:
- self._create_or_reset('fc3d', '3D fold-change plot',
- lambda: plot_fc3d(self, 'fc3d', self.ui.frame_fc3d, iondictfile, dfs, grpsts),
- lambda: self.fc3d.reset(iondictfile, dfs, grpsts))
- stop_functime('fc3d complete')
-
- if params.KMD:
- self._create_or_reset('kmd', 'Kendrick mass defect plot',
- lambda: kendrick(self, 'kmd', self.ui.frame_kmd, iondictfile, dfs, grpsts),
- lambda: self.kmd.reset(iondictfile, dfs, grpsts))
- stop_functime('kmd complete')
-
- if params.MZRTplt:
- self._create_or_reset('mzrt', 'm/z vs RT plot',
- lambda: plot_mzrt(self, 'mzrt', self.ui.frame_mzrt, iondictfile, dfs, grpsts),
- lambda: self.mzrt.reset(iondictfile, dfs, grpsts))
- stop_functime('mzrt complete')
-
- if params.Volcanoplt:
- self._create_or_reset('volcano', 'volcano plot',
- lambda: plot_volcano(self, 'volcano', self.ui.frame_volcano, iondictfile, dfs, grpsts),
- lambda: self.volcano.reset(iondictfile, dfs, grpsts))
- stop_functime('volcano complete')
-
- self._create_or_reset('heatmap', 'heatmap',
- lambda: plot_heatmap(self, 'heatmap', self.ui.frame_heatmap, pltfile),
- lambda: self.heatmap.reset(self, 'heatmap', self.ui.frame_heatmap, pltfile))
- stop_functime('heatmap complete')
-
- # abundplt/spec are only ever (re)drawn for the currently picked
- # feature via _refresh_highlight, not here -- just make sure they
- # exist when needed.
- self._create_or_reset('abundplt', 'abundance plot', lambda: plot_abund(self, 'abund'))
- if self.fragfilename != '':
- self._create_or_reset('spec', 'spectrum plot', lambda: show_spectrum(self, 'spec'))
-
- self._create_or_reset('samplecorr', 'sample correlation plot',
- lambda: plot_samplecorr(self, 'samplecorr', self.ui.frame_samplecorr, iondictfile, dfs, grpsts),
- lambda: self.samplecorr.reset(iondictfile, dfs, grpsts))
- stop_functime('samplecorr complete')
-
- self._create_or_reset('upset', 'upset plot',
- lambda: plot_upset(self, 'upset', self.ui.frame_upset, iondictfile, '', ''),
- lambda: self.upset.reset(iondictfile, '', ''))
- stop_functime('upsetplt complete')
-
def run_analysis(self):
- # Ignore re-clicks while an analysis is already running on the worker thread.
- if getattr(self, '_analysis_thread', None) is not None and self._analysis_thread.isRunning():
- return
self.dbsearchdone = False
- # iondict.csv/_filtered.csv/_summarydata.csv from any previous run
- # are about to be superseded -- drop cached reads of them so feature
- # selection etc. doesn't serve stale data from before this run.
- invalidate_csv_cache()
start_functime()
self.enumerate_inputs()
print('')
stop_functime('inputs obtained')
- # Heavy, Qt-free computation runs on a worker thread so the GUI stays
- # responsive; plotting resumes on the main thread in _finish_analysis
- # once the worker emits 'finished'.
- self.ui.btn_run.setEnabled(False)
- self.ui.label_status.setText('Processing data...')
- self.ui.label_status.setStyleSheet('color: rgb(150,150,150);')
-
- self._analysis_thread = QtCore.QThread()
- self._analysis_worker = AnalysisWorker(self)
- self._analysis_worker.moveToThread(self._analysis_thread)
- self._analysis_thread.started.connect(self._analysis_worker.run)
- self._analysis_worker.finished.connect(self._on_compute_finished)
- self._analysis_worker.failed.connect(self._on_compute_failed)
- self._analysis_worker.finished.connect(self._analysis_thread.quit)
- self._analysis_worker.failed.connect(self._analysis_thread.quit)
- # The thread/worker are kept as attributes (replaced on the next run)
- # rather than deleteLater'd, so the re-entrancy guard can safely call
- # isRunning() afterwards without touching a deleted C++ object.
- self._analysis_thread.start()
-
- def _on_compute_failed(self, msg):
- stop_functime('calculations failed')
- self.error(msg)
- self.ui.btn_run.setEnabled(True)
-
- def _on_compute_finished(self):
+ # Insert working signal here, will likely need multithreading
+ run_MSFaST(self)
print('')
stop_functime('calculations complete')
+
try:
- self._finish_analysis()
+ gen_treemap(self) # move back to end
except Exception:
- import traceback
- traceback.print_exc()
- self.error('Error during plot generation (see console)')
- finally:
- self.ui.btn_run.setEnabled(True)
-
- def _finish_analysis(self):
+ print("not generating tremap due to an error")
+ stop_functime('treemap complete')
+
# Used for point opacity based on abundance colouring
- iondict = cached_read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=None)
+ iondict = pd.read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=None)
self.analysis_paramsgui.maxval = iondict['logmax'].max()
-
- self._generate_plots()
+
+ if self.analysisrun:
+ self.regenerateplts()
+ else:
+ self.ftplt = show_featureplt(self, 'featureplt', self.ui.frame_featureplt, self.analysis_paramsgui.outputdir / 'iondict.csv', '', '')
+ stop_functime('ftplt complete')
+
+ self.dend = plot_dendrogram(self, 'dend', self.ui.frame_dend, self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), '', '')
+ stop_functime('dendrogram complete')
+
+ if self.analysis_paramsgui.PCA:
+ self.pca = plot_PCA(self, 'pca', self.ui.frame_pca, self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), '', '')
+ stop_functime('nmds complete')
+
+ if self.analysis_paramsgui.FC3Dplt:
+ self.fc3d = plot_fc3d(self, 'fc3d', self.ui.frame_fc3d, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('fc3d complete')
+
+ if self.analysis_paramsgui.KMD:
+ self.kmd = kendrick(self, 'kmd', self.ui.frame_kmd, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('kmd complete')
+
+ if self.analysis_paramsgui.MZRTplt:
+ self.mzrt = plot_mzrt(self, 'mzrt', self.ui.frame_mzrt, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('mzrt complete')
+
+ if self.analysis_paramsgui.Volcanoplt:
+ self.volcano = plot_volcano(self, 'volcano', self.ui.frame_volcano, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('volcano complete')
+
+ self.heatmap = plot_heatmap(self, 'heatmap', self.ui.frame_heatmap, self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'))
+ stop_functime('heatmap complete')
+
+ self.abundplt = plot_abund(self, 'abund')
+
+ if self.fragfilename != '':
+ self.spec = show_spectrum(self, 'spec')
+
+ if self.analysis_paramsgui.CVfil:
+ self.prevcv = prev_cv(self, 'cvplt', self.ui.frame_cvplt, 'none', 'none', 'none')
+ stop_functime('cvplt complete')
+
+ self.samplecorr = plot_samplecorr(self, 'samplecorr', self.ui.frame_samplecorr, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('samplecorr complete')
+
self.analysisrun = True
#text = open(self.analysis_paramsgui.outputdir / 'analysisinfo.txt').read() #writes output text to report tab
@@ -1287,7 +946,7 @@ def _finish_analysis(self):
# Writes filtering statistics in data review summary
msdata_unformatted = pd.read_csv(self.analysis_paramsgui.filename, sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
msdata_formatted = pd.read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_formatted.csv'), sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
- msdata_filtered = cached_read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
+ msdata_filtered = pd.read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
#test = open('testionfilters.pkl', 'wb') # this exports ionfilters as a pickle for debuging
#pickle.dump(self.ionfilters, test)
@@ -1319,6 +978,11 @@ def _finish_analysis(self):
self.fillfttree()
self.dbsearchdone = True
+ try:
+ gen_upsetplt(self)
+ except Exception:
+ print("not generating upset plot due to an error")
+ stop_functime('upsetplt complete')
self.ui.label_status.setText('Analysis Complete')
stop_functime('analysis complete')
print('')
@@ -1326,10 +990,9 @@ def _finish_analysis(self):
print('')
print('')
reset_runtime()
-
-
+
+
self.write_save()
- self.export_filtered_outputs()
def enumerate_inputs(self):
self.analysis_paramsgui = analysis_parameters()
@@ -1339,20 +1002,19 @@ def enumerate_inputs(self):
self.analysis_paramsgui.blnkgrp = ''
self.analysis_paramsgui.blnkfltr = self.ui.checkBox_blankfilter.isChecked()
- if len(self.groupsetmodel) == 0:
+ if len(self.querys) == 0:
if self.analysis_paramsgui.blnkfltr:
UIFunctions.addgroup(self, 'Features not in blanks')
- src = list(self.groupsetmodel.selected.excl)
- src.remove(self.analysis_paramsgui.blnkgrp)
- self.groupsetmodel.update(self.groupsetmodel.selected_index,
- src=src, excl=[self.analysis_paramsgui.blnkgrp])
+ self.querys[0].src = self.querys[0].excl
+ self.querys[0].src.remove(self.analysis_paramsgui.blnkgrp)
+ self.querys[0].excl = [self.analysis_paramsgui.blnkgrp]
else:
UIFunctions.addgroup(self, 'All features')
- self.groupsetmodel.update(self.groupsetmodel.selected_index,
- src=self.groupsetmodel.selected.excl, excl=[])
+ self.querys[0].src = self.querys[0].excl
+ self.querys[0].excl = []
UIFunctions.updategroups(self)
else:
- self.groupsetmodel.select(self.ui.listWidget_pltgrps.currentRow())
+ self.selset = self.ui.listWidget_pltgrps.currentRow()
UIFunctions.writegroups(self)
UIFunctions.updategroups(self)
@@ -1365,24 +1027,37 @@ def enumerate_inputs(self):
self.atlas = self.atlas[self.atlas['genus'] == self.analysis_paramsgui.genus]
- # A list of active filter-name tokens, not a hand-built string --
- # consumers that need the old space-joined string shape (e.g. an
- # older .mpct save) go through groupsets.normalize_graphfilters().
- self.analysis_paramsgui.graphfilters = []
+ self.analysis_paramsgui.graphfilters = ''
if self.ui.checkBox_cv.isChecked():
- self.analysis_paramsgui.graphfilters.append('cv')
+ self.analysis_paramsgui.graphfilters += 'cv '
if self.ui.checkBox_mp.isChecked():
- self.analysis_paramsgui.graphfilters.append('rel')
+ self.analysis_paramsgui.graphfilters += 'rel '
if self.ui.checkBox_decon.isChecked():
- self.analysis_paramsgui.graphfilters.append('insource')
+ self.analysis_paramsgui.graphfilters += 'insource'
self.analysis_paramsgui.deconthresh = float(self.ui.lineEdit_insourcethresh.text())
- # Build the {descriptive_name: GroupSet} mapping MSFaST/plotting
- # consume, merging in the active graph-level filters (cv/rel/insource).
- querydict = build_query_dict(self.groupsetmodel, self.analysis_paramsgui.graphfilters)
+ tempquerydic = {}
+ for pos in range(len(self.querys)):
+ tempquery = query()
+ tempquery.colour = str(self.querys[pos].colour)
+ tempquery.name = self.querys[pos].name
+ tempquery.excl = ' '.join(self.querys[pos].excl)
+ tempquery.incl = ' '.join(self.querys[pos].incl)
+ tempquery.src = ' '.join(self.querys[pos].src)
+ tempquerydic[pos] = tempquery
+
+ querydict = {}
+ for elem in tempquerydic:
+ tempquerydic[elem].excl += ' ' + self.analysis_paramsgui.graphfilters
+ queryname = tempquerydic[elem].src + ' +' + tempquerydic[elem].incl + ' -' + tempquerydic[elem].excl + ' c=' + tempquerydic[elem].colour + ' n=' + tempquerydic[elem].name
+ tempquerydic[elem].src = tempquerydic[elem].src.split()
+ tempquerydic[elem].incl = tempquerydic[elem].incl.split()
+ tempquerydic[elem].excl = tempquerydic[elem].excl.split()
+ querydict[queryname] = tempquerydic[elem]
+
self.analysis_paramsgui.querydict = querydict
self.analysis_paramsgui.querylist = list(querydict.keys())
@@ -1400,21 +1075,80 @@ def enumerate_inputs(self):
self.analysis_paramsgui.statstgrps = [str(self.ui.combo_expgrp.currentText()), str(self.ui.combo_ctrgrp.currentText())]
self.analysis_paramsgui.cvthresh = float(self.ui.lineEdit_cvthresh.text())
+
+ # ============ 新增:读取加合物归组配置文件 adduct_config.txt ============
+ # 该文件与main.py同目录,用记事本编辑即可。控制:是否开启加合物/中性丢失归组、离子模式、离子形式列表。
+ import os as _os
+ _cfg_path = _os.path.join(_os.path.dirname(_os.path.abspath(__file__)), 'adduct_config.txt')
+ self.analysis_paramsgui.adductgrp = False
+ self.analysis_paramsgui.mdfil = False
+ self.analysis_paramsgui.md_halogen = False
+ self.analysis_paramsgui.adduct_list = None
+ self.analysis_paramsgui.adduct_mode = 'pos'
+ self.analysis_paramsgui.adduct_ppm = 3.0
+ self.analysis_paramsgui.corr_cut = 0.75
+ self.analysis_paramsgui.corr_p = 0.05
+ if _os.path.exists(_cfg_path):
+ _adducts = []
+ try:
+ with open(_cfg_path, 'r', encoding='utf-8') as _f:
+ for _line in _f:
+ _line = _line.strip()
+ if (not _line) or _line.startswith('#'):
+ continue
+ if '=' in _line and ',' not in _line:
+ _k, _v = [x.strip() for x in _line.split('=', 1)]
+ if _k.lower() == 'enable':
+ self.analysis_paramsgui.adductgrp = (_v.lower() in ('true', '1', 'yes', 'on'))
+ elif _k.lower() == 'ppm':
+ self.analysis_paramsgui.adduct_ppm = float(_v)
+ elif _k.lower() == 'corr_cut':
+ self.analysis_paramsgui.corr_cut = float(_v)
+ elif _k.lower() == 'corr_p':
+ self.analysis_paramsgui.corr_p = float(_v)
+ elif _k.lower() == 'mass_defect':
+ self.analysis_paramsgui.mdfil = (_v.lower() in ('true','1','yes','on'))
+ elif _k.lower() == 'md_halogen':
+ self.analysis_paramsgui.md_halogen = (_v.lower() in ('true','1','yes','on'))
+ elif _k.lower() == 'mode':
+ # 离子模式:决定基准离子形式([M+H]+ / [M-H]-)
+ self.analysis_paramsgui.adduct_mode = _v.strip().lower()
+ elif ',' in _line:
+ _parts = [x.strip() for x in _line.split(',')]
+ if len(_parts) >= 2:
+ try:
+ _adducts.append((_parts[0], float(_parts[1])))
+ except ValueError:
+ pass
+ if _adducts:
+ self.analysis_paramsgui.adduct_list = _adducts
+ print('adduct_config.txt loaded: mode=%s, adduct=%s, mass_defect=%s, %d ion forms, ppm=%s' %
+ (self.analysis_paramsgui.adduct_mode, self.analysis_paramsgui.adductgrp, self.analysis_paramsgui.mdfil, len(_adducts), self.analysis_paramsgui.adduct_ppm))
+ except Exception as _e:
+ print('Warning: failed to read adduct_config.txt:', _e)
+ else:
+ print('adduct_config.txt not found; adduct grouping disabled.')
+ # ============ 新增结束 ============
if self.ui.radioButton_meancv.isChecked():
self.analysis_paramsgui.cvparam = 'average CV'
else:
self.analysis_paramsgui.cvparam = 'median CV'
- # Plain 1:1 checkbox fields (no branching/derived values) -- see
- # paramfields.py for the shared save/restore schema; the matching
- # restore side is loadsession()'s restore_checkbox_fields() call.
- save_checkbox_fields(self, self.analysis_paramsgui)
-
- # pqthresh / fcthresh / colorscheme moved to the volcano & heatmap plots'
- # own live control bars (plotting.py); no longer sourced from the dialog
- # here, and intentionally not persisted to .mpct (same as the dendrogram's
- # per-plot controls).
+ self.analysis_paramsgui.PCA = self.ui.checkBox_pca.isChecked()
+ self.analysis_paramsgui.Dendrogram = self.ui.checkBox_dend.isChecked()
+ self.analysis_paramsgui.bootstrap = self.dialog.ui.checkBox_bootstrap.isChecked()
+ self.analysis_paramsgui.MZRTplt = self.ui.checkBox_mzrt.isChecked()
+ self.analysis_paramsgui.KMD = self.ui.checkBox_kmd.isChecked()
+ self.analysis_paramsgui.mdguide = self.dialog.ui.checkBox_mdguide.isChecked()
+ self.analysis_paramsgui.FC = self.ui.checkBox_fc.isChecked()
+ self.analysis_paramsgui.FC3Dplt = self.ui.checkBox_3dfc.isChecked()
+ self.analysis_paramsgui.Ttest = self.ui.checkBox_ttest.isChecked()
+ self.analysis_paramsgui.Volcanoplt = self.ui.checkBox_volcano.isChecked()
+ self.analysis_paramsgui.pqthresh = float(self.dialog.ui.lineEdit_pqthresh.text())
+ self.analysis_paramsgui.fcthresh = float(self.dialog.ui.lineEdit_fcthresh.text())
+ self.analysis_paramsgui.colorscheme = self.dialog.ui.combo_colorscheme.currentText()
+ self.analysis_paramsgui.FDR = self.ui.checkBox_FDR.isChecked()
self.analysis_paramsgui.relfil = self.ui.checkBox_mp.isChecked()
self.analysis_paramsgui.CVfil = self.ui.checkBox_cv.isChecked()
self.analysis_paramsgui.decon = self.ui.checkBox_decon.isChecked()
@@ -1440,15 +1174,46 @@ def enumerate_inputs(self):
def regenerateplts(self):
- """Re-render plots in place (e.g. from the dialog's "Apply" button)
- without re-running the analysis pipeline.
-
- Delegates to the same create-or-reset logic used after a fresh
- analysis, so a plot that doesn't exist yet (e.g. because the prior
- analysis had it disabled) is created rather than crashing on
- ``.reset()``.
- """
- self._generate_plots()
+ pltfile = self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv')
+ dfs = self.filtereddfs
+ grpsts = self.groupsets
+
+ if self.analysis_paramsgui.CVfil:
+ self.prevcv.reset(self, '', '')
+ stop_functime('cvplt complete')
+
+ self.ftplt.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', '', '')
+ stop_functime('ftplt complete')
+
+ self.dend.reset(pltfile, '', '')
+ stop_functime('dendrogram complete')
+
+ if self.analysis_paramsgui.PCA:
+ self.pca.reset(pltfile, '', '')
+ stop_functime('nmds complete')
+
+ if self.analysis_paramsgui.FC3Dplt:
+ self.fc3d.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('fc3d complete')
+
+ if self.analysis_paramsgui.KMD:
+ self.kmd.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('kmd complete')
+
+ if self.analysis_paramsgui.MZRTplt:
+ self.mzrt.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('mzrt complete')
+
+ if self.analysis_paramsgui.Volcanoplt:
+ self.volcano.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('volcano complete')
+
+ self.heatmap.reset(self, 'heatmap', self.ui.frame_heatmap, pltfile)
+ stop_functime('heatmap complete')
+
+ self.samplecorr.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('samplecorr complete')
+
self.ui.label_status.setText('Update Complete')
@@ -1460,43 +1225,9 @@ def mousePressEvent(self, event):
if __name__ == "__main__":
- # Required for pvclust.py's multiprocessing.Pool() (bootstrap dendrogram)
- # to work in a PyInstaller-frozen exe: without it, each worker process
- # re-executes the whole frozen program from scratch instead of running
- # just the pool target, spawning a new QApplication/MainWindow per
- # worker. A no-op everywhere else (plain `python main.py`, Spyder),
- # so safe to call unconditionally.
- multiprocessing.freeze_support()
app = QtWidgets.QApplication(sys.argv)
if sys.platform != 'win32':
app.setStyle('Fusion')
app.setStyleSheet("QFrame { border: 0px; }") #QToolTip { color: #999999; background-color: rgb(0, 255, 0); border: 1px solid grey; }")
-
- # Crash reporting: on an unhandled exception, log a full report and offer to
- # open a prefilled GitHub issue (nothing is sent without the user clicking
- # through). Installed after the QApplication exists so the dialog can show.
- # See crashreport.py for the design (and why not Sentry).
- def _crash_dialog(report, log_path, issue_url):
- try:
- text = 'An unexpected error occurred.'
- if log_path:
- text += '\n\nA crash log was saved to:\n' + log_path
- text += ('\n\nReport this on GitHub? Your browser will open a '
- 'prefilled issue — nothing is sent automatically.')
- if styled_message_box(
- None, QtWidgets.QMessageBox.Critical,
- 'MPACT encountered an error', text,
- buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
- default=QtWidgets.QMessageBox.No,
- detailed=report) == QtWidgets.QMessageBox.Yes and issue_url:
- webbrowser.open(issue_url)
- except Exception:
- pass
-
- crashreport.install_excepthook(
- _crash_dialog,
- log_dir=str(Path.home() / '.mpact' / 'crashlogs'),
- repo=mpactupdate.DEFAULT_REPO)
-
window = MainWindow()
sys.exit(app.exec_())
diff --git a/code/main.py.bak_before_mode_fix b/code/main.py.bak_before_mode_fix
new file mode 100644
index 0000000..c6b86f8
--- /dev/null
+++ b/code/main.py.bak_before_mode_fix
@@ -0,0 +1,1230 @@
+"""
+MPACT
+Copyright 2022, Robert M. Samples, Sara P. Puckett, and Marcy J. Balunas
+"""
+
+import re
+
+import sys
+import pandas as pd
+pd.options.mode.chained_assignment = None # default='warn'
+import time
+import string
+
+import platform
+from PyQt5 import QtCore, QtWidgets
+from PyQt5.QtWidgets import QMainWindow, QSizeGrip, QGraphicsDropShadowEffect, QFileDialog, QListWidgetItem, QColorDialog
+from PyQt5.QtCore import (QCoreApplication, QPropertyAnimation, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent)
+from PyQt5.QtGui import QBrush, QColor, QIcon, QPalette, QPainter, QPixmap
+from pathlib import Path
+
+# GUI FILE
+from ui_main import Ui_MainWindow
+import ui_plotparam
+import ui_featureinfo
+
+# IMPORT FUNCTIONS AND RESOURCES
+from ui_functions import *
+import files
+
+from MSFaST import run_MSFaST, analysis_parameters
+from plotting import plot_abund, show_spectrum, show_featureplt, plot_heatmap, plot_mzrt, plot_samplecorr, kendrick, plot_volcano, plot_fc3d, plot_dendrogram, plot_PCA, prev_cv, gen_upsetplt, gen_treemap
+import getfragdb
+
+from indigo import Indigo
+from indigo.renderer import IndigoRenderer
+indigo = Indigo()
+renderer = IndigoRenderer(indigo)
+import os
+
+import pickle
+
+
+import pathlib
+if sys.platform == 'win32':
+ temp = pathlib.PosixPath
+ pathlib.PosixPath = pathlib.WindowsPath
+else:
+ temp = pathlib.WindowsPath
+ pathlib.WindowsPath = pathlib.PosixPath
+
+low_memory=False
+
+'''
+#need to make sure rel vs absolute is stored, and that merge checkbox connected, add to load filey
+Check if low_memory=False increases ram usage for average grps?
+
+-add bypass for plots based on checkmark. possibly use if check: ... else: button.hide() then pass
+
+- distribution of CVs on bottom of cvplt?
+- add pca option and allow visualization of key features on multivar plt?
+
+#TODO#
+#Easy/high priority
+- in source spectra
+- do overall data quality score, AUC
+- standardize method and class names
+- database management, options
+- fix up analysisinfo file output
+
+#Medium priority
+- mzmine msp file import
+- add other ordination options
+- add custom keyword arguments for each plot to make calling them easier
+- add more conditionals so if one plot fails it doesn't kill everything else
+- add runcheck before searching when switching to search tab
+- Figure out way to have only active plot be updated and then to update others
+ when plot is switched
+- change treewidget in search tab to treeview for better search, add filter options
+- make it so groups can be reordered
+- make it so iondict and msdata are saved as a parent object so they dont need to
+ be reopened each time a heatmap feature is scrolled. This may actually not
+ be a good idea depending on ram demands
+- make goto buttons just one class and lambda an index for the stacked widgets
+ when connecting!
+
+#low priority/long term
+- Switch to MVC format for groupsets
+- maybe have a comparison mode for many different strains with and without elicitor
+- specificity/sensitivity plot
+- other statistical models
+- refactor the filtereddfs and groupset code. everything should probably
+ be filtered from the main file in the analysis by referencing the groups
+ column in iondict
+ ~best way to do this may be to simplify the query/groupset flow to only have
+ one object, and then to generate a list of ions that pass this filter in the
+ object. That or add a color column to the iondict file
+ ~refactor to run filtering based of a list of filters instead of several
+ conditionals each time OR do it so that the appropriate columns are still
+ generated each time if filtering is off but they are always true
+'''
+
+class NumericalTreeWidgetItem(QtWidgets.QTreeWidgetItem):
+ def __lt__(self, other):
+ column = self.treeWidget().sortColumn() # the second column
+ try:
+ return float(self.text(column)) < float(other.text(column))
+ except ValueError: # fallback to alphabetical sorting if the text is not a number
+ return super().__lt__(other)
+
+class query:
+ """
+ Defines conditions (group presence/absence) to plot feature in a colour
+ """
+ def __init__(self):
+ self.name = ''
+ self.src = '' # or groups, feature can be in
+ self.incl = '' # and groups, feature must be in
+ self.excl = '' # not groups, feature must not be in
+ self.colour = '#000000'
+
+
+fullruntime = 0
+
+
+def start_functime():
+ """
+ Used to calculate runtime
+ """
+ global initfunctime
+ initfunctime = time.time()
+
+
+def stop_functime(text):
+ """
+ Prints runtime for step and increments global runtime
+ """
+ final = time.time()
+ interval = final - initfunctime
+ global fullruntime
+ fullruntime = fullruntime + interval
+ print(text)
+ print(interval)
+ print('')
+ start_functime()
+
+
+def reset_runtime():
+ """
+ Resets for new analysis
+ """
+ global fullruntime
+ fullruntime = 0
+
+
+#UI WINDOWS#
+class ftrdialog(QMainWindow): #dialog window for feature level data (spec, abund, hits)
+ def __init__(self):
+ QMainWindow.__init__(self)
+ self.ui = ui_featureinfo.Ui_MainWindow()
+ self.ui.setupUi(self)
+
+ self.sizegrip = QSizeGrip(self.ui.frame_grip_corner)
+ self.ui.frame_grip_corner.setStyleSheet("background: transparent; background-image: url(:/resources/icons/24x24/resize.png); background-position: center; background-repeat: no-repeat;" )
+ self.sizegrip.setToolTip("Resize Window")
+
+ # MOVE WINDOW
+ def moveWindow(event):
+ # IF LEFT CLICK MOVE WINDOW
+ if event.buttons() == Qt.LeftButton:
+ self.move(self.pos() + event.globalPos() - self.dragPos2)
+ self.dragPos2 = event.globalPos()
+ event.accept()
+
+ self.ui.label_title_bar_top.mouseMoveEvent = moveWindow
+
+ def mousePressEvent(self, event):
+ self.dragPos2 = event.globalPos()
+
+class dialog(QMainWindow): #plot configuration dialog
+ def __init__(self):
+ QMainWindow.__init__(self)
+ self.ui = ui_plotparam.Ui_MainWindow()
+ self.ui.setupUi(self)
+
+ def moveWindow(event):
+ if event.buttons() == Qt.LeftButton:
+ self.move(self.pos() + event.globalPos() - self.dragPos2)
+ self.dragPos2 = event.globalPos()
+ event.accept()
+
+ self.ui.label_title_bar_top.mouseMoveEvent = moveWindow
+
+ def mousePressEvent(self, event):
+ self.dragPos2 = event.globalPos()
+
+class MainWindow(QMainWindow):
+ def __init__(self):
+ QMainWindow.__init__(self)
+ self.ui = Ui_MainWindow()
+
+ self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) # set always on top flag, makes window disappear
+ self.show() # makes window reappear, but it's ALWAYS on top
+ self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowStaysOnTopHint) # clear always on top flag, makes window disappear
+ #self.show() # makes window reappear, acts like normal window now (on top now but can be underneath if you raise another window)
+
+ self.ui.setupUi(self)
+ self.ui.label_credits.setText('v1.00 r24.11.17')
+
+ #initialize other dialog windows
+ self.dialog = dialog()
+ self.ftrdialog = ftrdialog()
+ self.ftrdialog.ui.btn_masst.hide()
+
+ #set defaults
+ self.recentdir = '..'
+ self.savedata = {}
+ self.pickedfeature = ''
+ self.highlightcol = 'yellow'
+ self.dbsearchdone = False
+ self.selset = -1 #selected groupset index, refactor with MVC design
+ self.querys = [] #dictionary of the query/groupset objects
+ self.groups = [] #biological groups in the dataset
+ self.filename = Path.cwd()
+ self.extractmetadatafilename = Path.cwd()
+ self.samplelistfilename = Path.cwd()
+ self.ui.label_status.setText('') #running/idle status label
+ self.analysisrun = False
+ self.ui.combo_maxisoshift.setCurrentIndex(3)
+ self.outputdir = ''
+ self.fragfilename = ''
+ self.colourdic = {} #dictionary of available colours
+ #self.atlas = pd.read_csv('npatlas.csv', sep = ',', header = [0], index_col = [1])
+ #self.atlas = pd.read_csv('pyranodb.csv', sep = ',', header = [0], index_col = [1])
+
+
+
+
+ #initialize figure element dictionaries, can call with self.currplot as key
+ self.fig = {}
+ self.canvas = {}
+ self.pltlayout = {}
+ self.toolbar = {}
+ self.ax = {}
+ self.highlight = {}
+
+ self.ui.btn_run.clicked.connect(self.run_analysis)
+ self.ui.treeWidget.itemSelectionChanged.connect(self.on_tree_item_selection_changed)
+
+
+ def moveWindow(event):
+ if UIFunctions.returnStatus() == 1:
+ UIFunctions.maximize_restore(self)
+
+ if event.buttons() == Qt.LeftButton:
+ self.move(self.pos() + event.globalPos() - self.dragPos)
+ self.dragPos = event.globalPos()
+ event.accept()
+
+ self.ui.label_title_bar_top.mouseMoveEvent = moveWindow
+ UIFunctions.uiDefinitions(self)
+ self.show()
+
+
+ #---Methods---
+
+
+
+ def exportgnps(self):
+ """Export filtered GNPS peak table and optionally filter MGF file with new aligned IDs."""
+
+ # Load the GNPS/MZmine file
+ df_gnps = pd.read_csv(self.gnpsfilename, sep=',')
+
+ # Find the RT and m/z columns
+ rt_col = None
+ mz_col = None
+
+ for col in df_gnps.columns:
+ if col == 'row m/z':
+ mz_col = col
+ elif col == 'row retention time':
+ rt_col = col
+
+ # Fallback to position-based if exact names not found
+ if rt_col is None or mz_col is None:
+ cols = df_gnps.columns.tolist()
+ if 'row ID' in cols[0] or cols[0].lower() == 'row id':
+ mz_col = cols[1] if mz_col is None else mz_col
+ rt_col = cols[2] if rt_col is None else rt_col
+
+ print(f"GNPS columns - RT: '{rt_col}', m/z: '{mz_col}'")
+
+ # Load the filtered file
+ filtered_file = self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv')
+ df_filtered = pd.read_csv(filtered_file, header=[0,1,2])
+
+ # Extract compound identifiers from filtered file
+ compounds_to_keep = set()
+ filtered_rt_mz = []
+
+ first_col_values = df_filtered.iloc[:, 0]
+ for val in first_col_values:
+ if pd.notna(val) and '_' in str(val):
+ compounds_to_keep.add(str(val))
+ # Parse RT and m/z
+ parts = str(val).split('_')
+ if len(parts) == 2:
+ try:
+ rt = float(parts[0])
+ mz = float(parts[1])
+ filtered_rt_mz.append((rt, mz))
+ except:
+ pass
+
+ print(f"Found {len(compounds_to_keep)} compounds in filtered file")
+
+ # Tolerance-based matching for GNPS data
+ rt_tolerance = 0.01
+ mz_tolerance = 0.01
+
+ matched_indices = []
+ matched_compounds_info = [] # Store (index, rt, mz) for matched compounds
+
+ for idx, row in df_gnps.iterrows():
+ try:
+ rt_gnps = float(row[rt_col])
+ mz_gnps = float(row[mz_col])
+
+ # Check if this matches any filtered compound
+ for rt_filt, mz_filt in filtered_rt_mz:
+ if abs(rt_gnps - rt_filt) <= rt_tolerance and abs(mz_gnps - mz_filt) <= mz_tolerance:
+ matched_indices.append(idx)
+ matched_compounds_info.append((idx, rt_gnps, mz_gnps))
+ break
+ except:
+ continue
+
+ # Create filtered dataframe with new sequential row IDs
+ df_gnps_filtered = df_gnps.loc[matched_indices].copy()
+
+ # Assign new sequential row IDs starting from 1
+ if 'row ID' in df_gnps_filtered.columns:
+ df_gnps_filtered['row ID'] = range(1, len(df_gnps_filtered) + 1)
+
+ print(f"Filtered {len(df_gnps_filtered)} rows from {len(df_gnps)} total rows")
+
+ # Save the filtered GNPS file
+ output_file = self.analysis_paramsgui.outputdir / (self.gnpsfilename.stem + '_gnps_filtered.csv')
+ df_gnps_filtered.to_csv(output_file, sep=',', index=False)
+ print(f"Saved filtered GNPS file to: {output_file}")
+
+ # ===== PROCESS MGF FILE IF IT EXISTS =====
+ # Look for MGF file in the same directory as the GNPS file
+ mgf_file = None
+ gnps_dir = Path(self.gnpsfilename).parent
+
+ # Search for .mgf file
+ mgf_files = list(gnps_dir.glob('*.mgf'))
+ if mgf_files:
+ mgf_file = mgf_files[0] # Take the first MGF file found
+ print(f"\nFound MGF file: {mgf_file.name}")
+ else:
+ print("\nNo MGF file found in GNPS directory")
+
+ if mgf_file:
+ print("Processing MGF file...")
+
+ # Create lookup for matched compounds
+ rt_mz_to_new_id = {}
+ for new_id, (orig_idx, rt, mz) in enumerate(matched_compounds_info, start=1):
+ key = (round(rt, 5), round(mz, 5))
+ rt_mz_to_new_id[key] = new_id
+
+ # Parse and filter MGF
+ matched_mgf_entries = []
+ total_mgf_entries = 0
+
+ def parse_mgf_entry(entry_lines):
+ """Parse MGF entry to extract RT and m/z."""
+ entry_data = {'lines': entry_lines}
+ for line in entry_lines:
+ if line.startswith('FEATURE_ID='):
+ entry_data['feature_id'] = int(line.split('=')[1])
+ elif line.startswith('PEPMASS='):
+ entry_data['mz'] = float(line.split('=')[1])
+ elif line.startswith('RTINSECONDS='):
+ # Convert RT from seconds to minutes
+ entry_data['rt'] = float(line.split('=')[1]) / 60.0
+ elif line.startswith('RTINMINUTES='):
+ entry_data['rt'] = float(line.split('=')[1])
+ return entry_data
+
+ def update_mgf_feature_id(entry_lines, new_id):
+ """Update FEATURE_ID in MGF entry."""
+ updated_lines = []
+ for line in entry_lines:
+ if line.startswith('FEATURE_ID='):
+ updated_lines.append(f'FEATURE_ID={new_id}\n')
+ else:
+ updated_lines.append(line)
+ return updated_lines
+
+ # Read and process MGF file
+ with open(mgf_file, 'r') as f:
+ current_entry = []
+
+ for line in f:
+ if line.strip() == 'BEGIN IONS':
+ if current_entry:
+ total_mgf_entries += 1
+ entry_data = parse_mgf_entry(current_entry)
+
+ if 'rt' in entry_data and 'mz' in entry_data:
+ rt = entry_data['rt']
+ mz = entry_data['mz']
+
+ # Debug first few entries
+ if total_mgf_entries <= 3:
+ print(f" MGF entry {total_mgf_entries}: RT={rt:.4f} min, m/z={mz:.4f}")
+
+ # Check if matches any filtered compound
+ matched = False
+ key = (round(rt, 5), round(mz, 5))
+ if key in rt_mz_to_new_id:
+ new_id = rt_mz_to_new_id[key]
+ entry_data['new_id'] = new_id
+ matched_mgf_entries.append(entry_data)
+ matched = True
+ else:
+ # Check with tolerance
+ for (comp_rt, comp_mz), new_id in rt_mz_to_new_id.items():
+ if abs(comp_rt - rt) <= rt_tolerance and abs(comp_mz - mz) <= mz_tolerance:
+ entry_data['new_id'] = new_id
+ matched_mgf_entries.append(entry_data)
+ matched = True
+ if len(matched_mgf_entries) <= 3:
+ print(f" Matched to compound RT={comp_rt:.4f}, m/z={comp_mz:.4f}")
+ break
+
+ current_entry = []
+ current_entry.append(line)
+ elif line.strip() == 'END IONS':
+ current_entry.append(line)
+ elif current_entry:
+ current_entry.append(line)
+
+ # Process last entry
+ if current_entry:
+ total_mgf_entries += 1
+ entry_data = parse_mgf_entry(current_entry)
+ if 'rt' in entry_data and 'mz' in entry_data:
+ rt = entry_data['rt']
+ mz = entry_data['mz']
+ key = (round(rt, 5), round(mz, 5))
+ if key in rt_mz_to_new_id:
+ new_id = rt_mz_to_new_id[key]
+ entry_data['new_id'] = new_id
+ matched_mgf_entries.append(entry_data)
+
+ # Sort by new ID and write filtered MGF
+ matched_mgf_entries.sort(key=lambda x: x['new_id'])
+
+ mgf_output = self.analysis_paramsgui.outputdir / (mgf_file.stem + '_filtered.mgf')
+ with open(mgf_output, 'w') as f:
+ for entry_data in matched_mgf_entries:
+ new_id = entry_data['new_id']
+ updated_lines = update_mgf_feature_id(entry_data['lines'], new_id)
+ for line in updated_lines:
+ f.write(line.rstrip('\n') + '\n')
+ f.write('\n')
+
+ print(f"Filtered MGF: {len(matched_mgf_entries)} entries from {total_mgf_entries} total")
+ print(f"Saved filtered MGF to: {mgf_output}")
+
+ # Update status
+ status_text = f'Filtered GNPS table ({len(df_gnps_filtered)} compounds)'
+ if mgf_file:
+ status_text += f' and MGF ({len(matched_mgf_entries)} entries)'
+ self.ui.label_status.setText(status_text)
+
+ print("\n✓ Export completed successfully!")
+
+ def error(self, message):
+ self.ui.label_status.setText(message)
+ self.ui.label_status.setStyleSheet('color: rgb(150,0,0);')
+
+ def getgroups(self):
+ """
+ Get biological groups on input of all input files, fills comboboxes with these.
+ """
+ extractmetadata = pd.read_csv(self.extractmetadatafilename, sep=',', header=[0], index_col=None)
+ samplelist = pd.read_csv(self.samplelistfilename, sep=',', header=[0], index_col=None)
+
+ try:
+ combinedmetadata = extractmetadata.set_index('Sample_Code').join(samplelist.set_index('Sample_Code')) \
+ .reset_index().set_index('Injection')
+ except Exception:
+ self.error('Data read failure: Check input files')
+ return
+
+ msdata = pd.read_csv(self.filename, sep=',', header=None, index_col=[0, 1, 2])
+ groups = []
+
+ for elem in msdata.iloc[2]:
+ biolgroup = combinedmetadata.loc[elem, 'Biological_Group']
+ try:
+ if biolgroup not in groups:
+ groups.append(combinedmetadata.loc[elem, 'Biological_Group'])
+ except Exception:
+ print(biolgroup)
+ print("")
+ print(groups)
+ self.groups = groups
+
+ # Set experimental and control grp defaults in ui
+ self.ui.combo_blankfil_name.clear()
+ self.ui.combo_blankfil_name.addItems(self.groups)
+ self.ui.combo_expgrp.clear()
+ self.ui.combo_expgrp.addItems(self.groups)
+ self.ui.combo_ctrgrp.clear()
+ self.ui.combo_ctrgrp.addItems(self.groups)
+
+ # Set experimental and control group defaults in ui
+ if hasattr(self, 'analysis_paramsgui') and self.analysis_paramsgui.statstgrps:
+ self.ui.combo_expgrp.setCurrentText(str(self.analysis_paramsgui.statstgrps[0]))
+ self.ui.combo_ctrgrp.setCurrentText(str(self.analysis_paramsgui.statstgrps[1]))
+ else:
+ pos = 0
+ expset = False
+ for group in self.groups:
+ if 'blank' in group.lower():
+ self.ui.combo_blankfil_name.setCurrentIndex(pos)
+ else:
+ if expset:
+ self.ui.combo_ctrgrp.setCurrentIndex(pos)
+ else:
+ self.ui.combo_expgrp.setCurrentIndex(pos)
+ expset = True
+ pos += 1
+
+
+ def fulldbsearch(self):
+ """
+ Run a full compound database search. Filter the database matches within a specified mass window.
+ Concatenate the hits and sort them by parts-per-million (ppm).
+ """
+ self.hitdb = {}
+ iondict = pd.read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=[0])
+ iondict['hits'] = ''
+ msdata = pd.read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[2], index_col=None).iloc[:, :3]
+
+ for _, mrow in msdata.iterrows():
+ # Iterates over iondict, filters DB matches within window.
+ # Repeats for adducts, uses length of concat DF for feature hits
+ mass = mrow['m/z']
+ ppmwindow = self.analysis_paramsgui.ppmthresh
+ hits_h = self.atlas[abs(1000000 * (self.atlas['compound_m_plus_h'] - mass) / self.atlas['compound_m_plus_h']) < ppmwindow]
+ hits_h['ppm'] = abs(1000000 * (hits_h['compound_m_plus_h'] - mass) / hits_h['compound_m_plus_h'])
+ hits_na = self.atlas[abs(1000000 * (self.atlas['compound_m_plus_na'] - mass) / self.atlas['compound_m_plus_na']) < ppmwindow]
+ hits_na['ppm'] = abs(1000000 * (hits_na['compound_m_plus_na'] - mass) / hits_na['compound_m_plus_na'])
+ hits = pd.concat([hits_h, hits_na])
+ hits = hits.sort_values(by=['ppm'])
+ self.hitdb[mrow['Compound']] = hits
+ iondict.loc[mrow['Compound'], 'hits'] = hits.shape[0]
+
+ iondict.to_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', header=True, index=True)
+
+
+
+
+ def fillfttree(self):
+ # Fill feature tree with database hits
+ iondict = pd.read_csv(
+ self.analysis_paramsgui.outputdir / 'iondict.csv',
+ sep=',',
+ header=[0],
+ index_col=None
+ )
+ iondict = iondict[iondict['hits'] >= 0]
+ self.ui.treeWidget.setSortingEnabled(True)
+
+ itemdict = {}
+ self.ui.treeWidget.clear()
+ for i, row in iondict.iterrows():
+ item = NumericalTreeWidgetItem([
+ row['Compound'],
+ str(round(row['m/z'], 4)),
+ str(round(row['Retention time (min)'], 3)),
+ str(int(row['max'])),
+ str(row['groups']),
+ str(row['groups']),
+ str(round(row['fc'], 2)),
+ str(int(row['hits']))
+ ])
+ itemdict[i] = item
+ self.ui.treeWidget.addTopLevelItem(item)
+ # Optionally expand all items
+ # self.ui.treeWidget.expandAll()
+
+
+
+ def onItemClicked():
+ if len(self.ftrdialog.ui.treeWidget.selectedItems()) > 0:
+ item = self.ftrdialog.ui.treeWidget.selectedItems()[0]
+ smiles = item.text(5)
+ if smiles:
+ try:
+ m = indigo.loadMolecule(smiles)
+ indigo.setOption('render-image-size', '400,400')
+ image_path = f'compoundimages/{item.text(0)}.png'
+ renderer.renderToFile(m, image_path)
+ pixmap = QPixmap(image_path)
+ pixmap2 = pixmap.scaled(400, 400, QtCore.Qt.KeepAspectRatio)
+ self.ftrdialog.ui.label.setPixmap(pixmap2)
+ except Exception as e:
+ print(f"Error rendering molecule for {item.text(0)}: {e}")
+ # Optionally, display a default image or message
+ else:
+ print(f"No SMILES string available for {item.text(0)}")
+ # Handle the case where SMILES is empty
+
+ def on_tree_item_selection_changed(self):
+ selected_items = self.ui.treeWidget.selectedItems()
+ if selected_items:
+ item = selected_items[0]
+ # Get the name from the first column
+ name = item.text(0)
+ #print(f"Selection changed: {name}")
+ # Call the method to highlight the feature
+ self.highlight_feature(name)
+
+ # Call the onItemClicked logic
+ #self.onItemClicked(item)
+
+ def runsearch(self, mass): # refactor if I can save a database of hits
+ #possibly make a third common method used in both dbsearch and this method
+ """
+ Runs a search for a mass and displays the database hits in the feature tree dialog.
+
+ Args:
+ mass (float): The mass to search for.
+
+ Returns:
+ None.
+ """
+ ppmwindow = self.analysis_paramsgui.ppmthresh
+ hits_h = self.atlas[abs(1000000*(self.atlas['compound_m_plus_h'] - mass)/self.atlas['compound_m_plus_h']) < ppmwindow]
+ hits_h['ppm'] = abs(1000000*(hits_h['compound_m_plus_h'] - mass)/hits_h['compound_m_plus_h'])
+ hits_na = self.atlas[abs(1000000*(self.atlas['compound_m_plus_na'] - mass)/self.atlas['compound_m_plus_na']) < ppmwindow]
+ hits_na['ppm'] = abs(1000000*(hits_na['compound_m_plus_na'] - mass)/hits_na['compound_m_plus_na'])
+ hits = pd.concat([hits_h, hits_na])
+ hits = hits.sort_values(by=['ppm'])
+
+ x=0 #rename this variable
+ itemdict = {}
+ smilesdict = {}
+ self.ftrdialog.ui.treeWidget.clear()
+ for index, row in hits.iterrows():
+ itemdict[x] = QtWidgets.QTreeWidgetItem( [row['compound_name'], row['compound_molecular_formula'], str(row['compound_accurate_mass']), str(row['ppm']), (str(row['genus'] + ' ' + row['origin_species'])), row['compound_smiles']])
+ self.ftrdialog.ui.treeWidget.addTopLevelItem(itemdict[x])
+ x = x + 1
+
+ def onItemClicked(): #show structure of selected match
+
+ def clean_ascii(text):
+ printable = set(string.printable)
+ ascii_chars = filter(lambda x: x in printable, text)
+ return ''.join(ascii_chars)
+
+
+ if len(self.ftrdialog.ui.treeWidget.selectedItems()) > 0:
+ item = self.ftrdialog.ui.treeWidget.selectedItems()[0]
+ cmpd = clean_ascii(item.text(0))
+ cmpd = re.sub(r'\/<>.*{}\|', ' ', cmpd)
+
+ if os.path.isfile('compoundimages/' + (cmpd + '.png')):
+ pixmap = QPixmap('compoundimages/' + (cmpd + '.png'))
+ else:
+ m = indigo.loadMolecule(item.text(5))
+ indigo.setOption('render-image-size', '400,400')
+ renderer.renderToFile(m, 'compoundimages/' + (cmpd + '.png'))
+ pixmap = QPixmap('compoundimages/' + (cmpd + '.png'))
+
+ pixmap2 = pixmap.scaled(400, 400, QtCore.Qt.KeepAspectRatio)
+ self.ftrdialog.ui.label.setPixmap(pixmap2)
+
+ self.ftrdialog.ui.treeWidget.itemSelectionChanged.connect(onItemClicked)
+ if len(hits.index) == 0:
+ pixmap = QPixmap('blank.png')
+ pixmap2 = pixmap.scaled(400, 400, QtCore.Qt.KeepAspectRatio)
+ self.ftrdialog.ui.label.setPixmap(pixmap2)
+ else:
+ self.ftrdialog.ui.treeWidget.setCurrentItem(itemdict[0])
+
+ def highlight_feature(self, newfeature):
+ """
+ Highlights the selected feature in all plots.
+
+ Args:
+ newfeature (str): The name of the new feature to highlight.
+
+ Returns:
+ None.
+ """
+ # Deselect the highlighted feature if clicked twice
+ if newfeature == self.pickedfeature and self.highlightcol != (0, 0, 0, 0):
+ self.highlightcol = (0, 0, 0, 0)
+ else:
+ self.highlightcol = 'yellow'
+
+ # Highlight the selected feature in all plots
+ for plot in self.highlight:
+ self.highlight[plot].set_color(self.highlightcol)
+
+ # Set the selected feature as the picked feature
+ self.pickedfeature = newfeature
+
+ # Read iondict file to get ion data
+ iondict = pd.read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv',
+ sep=',', header=[0], index_col=[0])
+
+ # Update volcano plot with the selected feature
+ if self.analysis_paramsgui.Volcanoplt:
+ self.highlight['volcano'].set_data(
+ [iondict.loc[self.pickedfeature, 'logfc']],
+ [iondict.loc[self.pickedfeature, '-logq']]
+ )
+ self.canvas['volcano'].draw_idle()
+
+ # Update MZRT plot with the selected feature
+ self.highlight['mzrt'].set_data(
+ [iondict.loc[self.pickedfeature, 'Retention time (min)']],
+ [iondict.loc[self.pickedfeature, 'm/z']]
+ )
+ self.canvas['mzrt'].draw_idle()
+
+ # Update KMD plot with the selected feature
+ if self.analysis_paramsgui.KMD:
+ self.highlight['kmd'].set_data(
+ [iondict.loc[self.pickedfeature, 'm/z']],
+ [iondict.loc[self.pickedfeature, 'kmd']]
+ )
+ self.canvas['kmd'].draw_idle()
+
+ # Update feature plot with the selected feature
+ self.highlight['featureplt'].set_data(
+ [iondict.loc[self.pickedfeature, 'Retention time (min)']],
+ [iondict.loc[self.pickedfeature, 'm/z']]
+ )
+ self.canvas['featureplt'].draw_idle()
+
+ msdata = pd.read_csv(
+ self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'),
+ sep=',', header=[2], index_col=[0]
+ )
+
+ # Set heatmap highlight based on view
+ self.heatind = self.cmind.index(msdata.index.to_list().index(self.pickedfeature))
+ xlim = int(self.canvas['heatmap'].figure.axes[2].get_xlim()[1])
+ self.highlight['heatmap'].set_data(
+ [0, xlim, xlim, 0, 0],
+ [self.heatind, self.heatind, self.heatind+1, self.heatind+1, self.heatind]
+ )
+ self.canvas['heatmap'].draw_idle()
+
+ # Run search when feature is selected
+ if self.ftrdialog.ui.stackedWidget.currentIndex() == 0 and not self.ftrdialog.isHidden():
+ self.runsearch(iondict.loc[self.pickedfeature, 'm/z'])
+
+ # Reset spec if fragfilename exists and update abundplt
+ if self.fragfilename != '':
+ self.spec.reset(self.fragdb.ions[self.pickedfeature].pattern)
+ if self.ftrdialog.ui.stackedWidget.currentIndex() == 2 and not self.ftrdialog.isHidden():
+ self.abundplt.reset()
+
+
+ # Move heatmap selection up or down with W/S key press
+ def keyPressEvent(self, event):
+ if event.key() == QtCore.Qt.Key_W:
+ self.mv_heatmap(-1)
+ elif event.key() == QtCore.Qt.Key_S:
+ self.mv_heatmap(1)
+
+ def mv_heatmap(self, shift):
+ """
+ Moves heatmap selection up or down by a given shift value.
+
+ Args:
+ shift (int): The value to shift the heatmap selection by.
+
+ Returns:
+ None.
+ """
+ if self.ui.stackedWidget_plot.currentIndex() != 8 or self.ui.stackedWidget.currentIndex() != 3:
+ return
+
+ iondict = pd.read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=[0])
+ msdata = pd.read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[2], index_col=[0]).iloc[:, 2:]
+ index = self.cmind[self.heatind + shift]
+ name = msdata.index.tolist()[index]
+
+ self.ui.lbl_featurename.setText('Compound: ' + name)
+ self.ui.lbl_featurert.setText('Retention time: ' + str(iondict.loc[name, 'Retention time (min)']))
+ self.ui.lbl_featuremz.setText('m/z: ' + str(iondict.loc[name, 'm/z']))
+ self.highlight_feature(name)
+
+
+ def read_save(self, savefile):
+ """Reads a saved analysis session from a pickle file.
+
+ Args:
+ savefile (Path): The path to the saved session file.
+ """
+ print("read1")
+ with open(savefile, 'rb') as read_pi:
+ print("read3")
+ self.savedata = pickle.load(read_pi)
+ print("read2")
+
+ # Assign the analysis parameters
+ self.analysis_paramsgui = self.savedata['parameters']
+
+ # Set output dir to save file directory, make rawdata folder
+ self.analysis_paramsgui.outputdir = Path(savefile).parent
+ Path(self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata').mkdir(parents=True, exist_ok=True)
+
+ # Write raw files from save file
+ self.savedata['peaktable'].to_csv(self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata' / self.analysis_paramsgui.filename.name, header=False, index=False)
+ self.savedata['samplelist'].to_csv(self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata' / self.analysis_paramsgui.samplelistfilename.name, header=False, index=False)
+ self.savedata['extractmetadata'].to_csv(self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata' / self.analysis_paramsgui.extractmetadatafilename.name, header=False, index=False)
+
+ # Write frag file if it exists
+ if self.analysis_paramsgui.fragfilename:
+ fragmsp = open(self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata' / self.analysis_paramsgui.fragfilename.name, 'w')
+ fragmsp.write(self.savedata['fragdb'])
+ fragmsp.close()
+
+ # Assign file names and output directory
+ self.outputdir = self.analysis_paramsgui.outputdir
+ self.samplelistfilename = self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata' / self.analysis_paramsgui.samplelistfilename.name
+ self.extractmetadatafilename = self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata' / self.analysis_paramsgui.extractmetadatafilename.name
+
+ # Assign frag file name if it exists
+ if self.analysis_paramsgui.fragfilename:
+ self.fragfilename = self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata' / Path(self.analysis_paramsgui.fragfilename).name
+
+ self.filename = self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'rawdata' / self.analysis_paramsgui.filename.name
+
+ # Get groups and update querys
+ self.getgroups()
+ self.querys = self.analysis_paramsgui.queries
+ UIFunctions.updatesets(self)
+
+
+ def write_save(self):
+ """Writes the current analysis session to a pickle file.
+ """
+ self.analysis_paramsgui.queries = self.querys # WRITES QUERY DB FOR GROUPSETS IN ANALYSISPARAMETERS, WILL NEED TO CHANGE WHEN MVC IMPLEMENTED
+ file_pi = open(self.analysis_paramsgui.outputdir/(self.analysis_paramsgui.filename.stem + '.mpct'), 'wb')
+ self.savedata['parameters'] = self.analysis_paramsgui
+ self.savedata['peaktable'] = pd.read_csv(self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.name, sep = ',', header = None, index_col = None)
+ self.savedata['samplelist'] = pd.read_csv(self.samplelistfilename, sep = ',', header = None, index_col = None)
+ self.savedata['extractmetadata'] = pd.read_csv(self.extractmetadatafilename , sep = ',', header = None, index_col = None)
+ if self.analysis_paramsgui.fragfilename != '':
+ fragmsp = open(self.analysis_paramsgui.fragfilename, 'r')
+ self.savedata['fragdb'] = fragmsp.read()
+ fragmsp.close()
+ else:
+ self.savedata['fragdb'] = 'None'
+ pickle.dump(self.savedata, file_pi)
+ file_pi.close()
+
+ def run_analysis(self):
+ self.dbsearchdone = False
+ start_functime()
+ self.enumerate_inputs()
+ print('')
+ stop_functime('inputs obtained')
+
+ # Insert working signal here, will likely need multithreading
+ run_MSFaST(self)
+ print('')
+ stop_functime('calculations complete')
+
+ try:
+ gen_treemap(self) # move back to end
+ except Exception:
+ print("not generating tremap due to an error")
+ stop_functime('treemap complete')
+
+ # Used for point opacity based on abundance colouring
+ iondict = pd.read_csv(self.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=None)
+ self.analysis_paramsgui.maxval = iondict['logmax'].max()
+
+ if self.analysisrun:
+ self.regenerateplts()
+ else:
+ self.ftplt = show_featureplt(self, 'featureplt', self.ui.frame_featureplt, self.analysis_paramsgui.outputdir / 'iondict.csv', '', '')
+ stop_functime('ftplt complete')
+
+ self.dend = plot_dendrogram(self, 'dend', self.ui.frame_dend, self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), '', '')
+ stop_functime('dendrogram complete')
+
+ if self.analysis_paramsgui.PCA:
+ self.pca = plot_PCA(self, 'pca', self.ui.frame_pca, self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), '', '')
+ stop_functime('nmds complete')
+
+ if self.analysis_paramsgui.FC3Dplt:
+ self.fc3d = plot_fc3d(self, 'fc3d', self.ui.frame_fc3d, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('fc3d complete')
+
+ if self.analysis_paramsgui.KMD:
+ self.kmd = kendrick(self, 'kmd', self.ui.frame_kmd, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('kmd complete')
+
+ if self.analysis_paramsgui.MZRTplt:
+ self.mzrt = plot_mzrt(self, 'mzrt', self.ui.frame_mzrt, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('mzrt complete')
+
+ if self.analysis_paramsgui.Volcanoplt:
+ self.volcano = plot_volcano(self, 'volcano', self.ui.frame_volcano, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('volcano complete')
+
+ self.heatmap = plot_heatmap(self, 'heatmap', self.ui.frame_heatmap, self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'))
+ stop_functime('heatmap complete')
+
+ self.abundplt = plot_abund(self, 'abund')
+
+ if self.fragfilename != '':
+ self.spec = show_spectrum(self, 'spec')
+
+ if self.analysis_paramsgui.CVfil:
+ self.prevcv = prev_cv(self, 'cvplt', self.ui.frame_cvplt, 'none', 'none', 'none')
+ stop_functime('cvplt complete')
+
+ self.samplecorr = plot_samplecorr(self, 'samplecorr', self.ui.frame_samplecorr, self.analysis_paramsgui.outputdir / 'iondict.csv', self.filtereddfs, self.groupsets)
+ stop_functime('samplecorr complete')
+
+ self.analysisrun = True
+
+ #text = open(self.analysis_paramsgui.outputdir / 'analysisinfo.txt').read() #writes output text to report tab
+ #self.ui.textBrowser_info.setPlainText(text)
+
+
+
+ # Writes filtering statistics in data review summary
+ msdata_unformatted = pd.read_csv(self.analysis_paramsgui.filename, sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
+ msdata_formatted = pd.read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_formatted.csv'), sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
+ msdata_filtered = pd.read_csv(self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
+ #test = open('testionfilters.pkl', 'wb') # this exports ionfilters as a pickle for debuging
+ #pickle.dump(self.ionfilters, test)
+
+ text = ''
+ if self.analysis_paramsgui.relfil:
+ text += 'Features failing peak correction filtering: ' + str(len(self.ionfilters['relfil'].ions)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(self.ionfilters['relfil'].ions) / len(msdata_unformatted.index), 2)) + '%\n'
+ if self.analysis_paramsgui.blnkfltr:
+ text += 'Features failing blank filtering: ' + str(len(self.groupionlists[self.analysis_paramsgui.blnkgrp])) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(self.groupionlists[self.analysis_paramsgui.blnkgrp]) / len(msdata_unformatted.index), 2)) + '%\n'
+ if self.analysis_paramsgui.decon:
+ text += 'Features in-source ion filtering: ' + str(len(self.ionfilters['insource'].ions)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(self.ionfilters['insource'].ions) / len(msdata_unformatted.index), 2)) + '%\n'
+ if self.analysis_paramsgui.CVfil:
+ text += 'Features failing CV filtering: ' + str(len(self.ionfilters['cv'].ions)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(self.ionfilters['cv'].ions) / len(msdata_unformatted.index), 2)) + '%\n'
+ text += 'Features failing any filters: ' + str(len(msdata_unformatted.index) - len(msdata_filtered.index)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * (len(msdata_unformatted.index) - len(msdata_filtered.index)) / len(msdata_unformatted.index), 2)) + '%\n'
+ text += 'Features passing all filters: ' + str(len(msdata_filtered.index)) + '/' + str(len(msdata_unformatted.index)) + ' ' + str(round(100 * len(msdata_filtered.index) / len(msdata_unformatted.index), 2)) + '%\n'
+
+ self.ui.textBrowser_mp_prev.setPlainText(text)
+
+ # Imports msp fragment database
+ if self.fragfilename != '':
+ self.fragdb = getfragdb.importfrag(self.analysis_paramsgui.fragfilename)
+ self.ftrdialog.ui.btn_spectrum.show()
+ else:
+ self.fragdb = 'None'
+ self.ftrdialog.ui.btn_spectrum.hide()
+
+ # Runs DB search only if tab is active
+ if self.ui.stackedWidget.currentIndex() == 5:
+ self.fulldbsearch()
+ self.fillfttree()
+ self.dbsearchdone = True
+
+ try:
+ gen_upsetplt(self)
+ except Exception:
+ print("not generating upset plot due to an error")
+ stop_functime('upsetplt complete')
+ self.ui.label_status.setText('Analysis Complete')
+ stop_functime('analysis complete')
+ print('')
+ print('full runtime:' + str(fullruntime))
+ print('')
+ print('')
+ reset_runtime()
+
+
+ self.write_save()
+
+ def enumerate_inputs(self):
+ self.analysis_paramsgui = analysis_parameters()
+ if self.ui.checkBox_blankfilter.isChecked():
+ self.analysis_paramsgui.blnkgrp = str(self.ui.combo_blankfil_name.currentText())
+ else:
+ self.analysis_paramsgui.blnkgrp = ''
+ self.analysis_paramsgui.blnkfltr = self.ui.checkBox_blankfilter.isChecked()
+
+ if len(self.querys) == 0:
+ if self.analysis_paramsgui.blnkfltr:
+ UIFunctions.addgroup(self, 'Features not in blanks')
+ self.querys[0].src = self.querys[0].excl
+ self.querys[0].src.remove(self.analysis_paramsgui.blnkgrp)
+ self.querys[0].excl = [self.analysis_paramsgui.blnkgrp]
+ else:
+ UIFunctions.addgroup(self, 'All features')
+ self.querys[0].src = self.querys[0].excl
+ self.querys[0].excl = []
+ UIFunctions.updategroups(self)
+ else:
+ self.selset = self.ui.listWidget_pltgrps.currentRow()
+ UIFunctions.writegroups(self)
+ UIFunctions.updategroups(self)
+
+ self.analysis_paramsgui.kingdom = self.ui.combo_kingdom.currentText()
+ self.analysis_paramsgui.genus = str(self.ui.lineEdit_genus.text())
+ self.atlas = pd.read_csv('npatlas.tsv', sep='\t', header=0, index_col=1)
+ if len(self.analysis_paramsgui.kingdom) > 3:
+ self.atlas = self.atlas[self.atlas['origin_type'] == self.analysis_paramsgui.kingdom]
+ if len(self.analysis_paramsgui.genus) > 3:
+ self.atlas = self.atlas[self.atlas['genus'] == self.analysis_paramsgui.genus]
+
+
+ self.analysis_paramsgui.graphfilters = ''
+ if self.ui.checkBox_cv.isChecked():
+ self.analysis_paramsgui.graphfilters += 'cv '
+ if self.ui.checkBox_mp.isChecked():
+ self.analysis_paramsgui.graphfilters += 'rel '
+ if self.ui.checkBox_decon.isChecked():
+ self.analysis_paramsgui.graphfilters += 'insource'
+ self.analysis_paramsgui.deconthresh = float(self.ui.lineEdit_insourcethresh.text())
+
+
+
+
+ tempquerydic = {}
+ for pos in range(len(self.querys)):
+ tempquery = query()
+ tempquery.colour = str(self.querys[pos].colour)
+ tempquery.name = self.querys[pos].name
+ tempquery.excl = ' '.join(self.querys[pos].excl)
+ tempquery.incl = ' '.join(self.querys[pos].incl)
+ tempquery.src = ' '.join(self.querys[pos].src)
+ tempquerydic[pos] = tempquery
+
+ querydict = {}
+ for elem in tempquerydic:
+ tempquerydic[elem].excl += ' ' + self.analysis_paramsgui.graphfilters
+ queryname = tempquerydic[elem].src + ' +' + tempquerydic[elem].incl + ' -' + tempquerydic[elem].excl + ' c=' + tempquerydic[elem].colour + ' n=' + tempquerydic[elem].name
+ tempquerydic[elem].src = tempquerydic[elem].src.split()
+ tempquerydic[elem].incl = tempquerydic[elem].incl.split()
+ tempquerydic[elem].excl = tempquerydic[elem].excl.split()
+ querydict[queryname] = tempquerydic[elem]
+
+ self.analysis_paramsgui.querydict = querydict
+ self.analysis_paramsgui.querylist = list(querydict.keys())
+
+ # Set analysis parameters
+ self.analysis_paramsgui.filename = self.filename
+ self.analysis_paramsgui.samplelistfilename = self.samplelistfilename
+ self.analysis_paramsgui.extractmetadatafilename = self.extractmetadatafilename
+ if self.outputdir == '':
+ self.outputdir = (Path(self.analysis_paramsgui.filename).parent)
+ self.analysis_paramsgui.outputdir = self.outputdir
+ self.analysis_paramsgui.fragfilename = self.fragfilename
+ Path(self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem).mkdir(parents=True, exist_ok=True)
+ Path(self.analysis_paramsgui.outputdir / self.analysis_paramsgui.filename.stem / 'plots').mkdir(parents=True, exist_ok=True)
+ self.analysis_paramsgui.outputdir /= self.analysis_paramsgui.filename.stem
+
+ self.analysis_paramsgui.statstgrps = [str(self.ui.combo_expgrp.currentText()), str(self.ui.combo_ctrgrp.currentText())]
+ self.analysis_paramsgui.cvthresh = float(self.ui.lineEdit_cvthresh.text())
+
+ # ============ 新增:读取加合物归组配置文件 adduct_config.txt ============
+ # 该文件与main.py同目录,用记事本编辑即可。控制:是否开启加合物/中性丢失归组、离子模式、离子形式列表。
+ import os as _os
+ _cfg_path = _os.path.join(_os.path.dirname(_os.path.abspath(__file__)), 'adduct_config.txt')
+ self.analysis_paramsgui.adductgrp = False
+ self.analysis_paramsgui.mdfil = False
+ self.analysis_paramsgui.md_halogen = False
+ self.analysis_paramsgui.adduct_list = None
+ self.analysis_paramsgui.adduct_ppm = 3.0
+ self.analysis_paramsgui.corr_cut = 0.75
+ self.analysis_paramsgui.corr_p = 0.05
+ if _os.path.exists(_cfg_path):
+ _adducts = []
+ try:
+ with open(_cfg_path, 'r', encoding='utf-8') as _f:
+ for _line in _f:
+ _line = _line.strip()
+ if (not _line) or _line.startswith('#'):
+ continue
+ if '=' in _line and ',' not in _line:
+ _k, _v = [x.strip() for x in _line.split('=', 1)]
+ if _k.lower() == 'enable':
+ self.analysis_paramsgui.adductgrp = (_v.lower() in ('true', '1', 'yes', 'on'))
+ elif _k.lower() == 'ppm':
+ self.analysis_paramsgui.adduct_ppm = float(_v)
+ elif _k.lower() == 'corr_cut':
+ self.analysis_paramsgui.corr_cut = float(_v)
+ elif _k.lower() == 'corr_p':
+ self.analysis_paramsgui.corr_p = float(_v)
+ elif _k.lower() == 'mass_defect':
+ self.analysis_paramsgui.mdfil = (_v.lower() in ('true','1','yes','on'))
+ elif _k.lower() == 'md_halogen':
+ self.analysis_paramsgui.md_halogen = (_v.lower() in ('true','1','yes','on'))
+ # mode(pos/neg)暂存,可用于将来自动选表
+ elif ',' in _line:
+ _parts = [x.strip() for x in _line.split(',')]
+ if len(_parts) >= 2:
+ try:
+ _adducts.append((_parts[0], float(_parts[1])))
+ except ValueError:
+ pass
+ if _adducts:
+ self.analysis_paramsgui.adduct_list = _adducts
+ print('adduct_config.txt loaded: adduct=%s, mass_defect=%s, %d ion forms, ppm=%s' %
+ (self.analysis_paramsgui.adductgrp, self.analysis_paramsgui.mdfil, len(_adducts), self.analysis_paramsgui.adduct_ppm))
+ except Exception as _e:
+ print('Warning: failed to read adduct_config.txt:', _e)
+ else:
+ print('adduct_config.txt not found; adduct grouping disabled.')
+ # ============ 新增结束 ============
+ if self.ui.radioButton_meancv.isChecked():
+ self.analysis_paramsgui.cvparam = 'average CV'
+ else:
+ self.analysis_paramsgui.cvparam = 'median CV'
+
+
+ self.analysis_paramsgui.PCA = self.ui.checkBox_pca.isChecked()
+ self.analysis_paramsgui.Dendrogram = self.ui.checkBox_dend.isChecked()
+ self.analysis_paramsgui.bootstrap = self.dialog.ui.checkBox_bootstrap.isChecked()
+ self.analysis_paramsgui.MZRTplt = self.ui.checkBox_mzrt.isChecked()
+ self.analysis_paramsgui.KMD = self.ui.checkBox_kmd.isChecked()
+ self.analysis_paramsgui.mdguide = self.dialog.ui.checkBox_mdguide.isChecked()
+ self.analysis_paramsgui.FC = self.ui.checkBox_fc.isChecked()
+ self.analysis_paramsgui.FC3Dplt = self.ui.checkBox_3dfc.isChecked()
+ self.analysis_paramsgui.Ttest = self.ui.checkBox_ttest.isChecked()
+ self.analysis_paramsgui.Volcanoplt = self.ui.checkBox_volcano.isChecked()
+ self.analysis_paramsgui.pqthresh = float(self.dialog.ui.lineEdit_pqthresh.text())
+ self.analysis_paramsgui.fcthresh = float(self.dialog.ui.lineEdit_fcthresh.text())
+ self.analysis_paramsgui.colorscheme = self.dialog.ui.combo_colorscheme.currentText()
+ self.analysis_paramsgui.FDR = self.ui.checkBox_FDR.isChecked()
+ self.analysis_paramsgui.relfil = self.ui.checkBox_mp.isChecked()
+ self.analysis_paramsgui.CVfil = self.ui.checkBox_cv.isChecked()
+ self.analysis_paramsgui.decon = self.ui.checkBox_decon.isChecked()
+ self.analysis_paramsgui.merge = self.ui.checkBox_merge.isChecked()
+ self.analysis_paramsgui.RTwin = float(self.ui.lineEdit_rtwin.text())
+ self.analysis_paramsgui.ringingwin = float(self.ui.lineEdit_ringwin.text())
+ self.analysis_paramsgui.isopeakwin = float(self.ui.lineEdit_isowin.text())
+ self.analysis_paramsgui.dimerpeakwin = float(self.ui.lineEdit_isowin.text())
+ self.analysis_paramsgui.maxisowin = float(self.ui.combo_maxisoshift.currentText())
+ self.analysis_paramsgui.grpave = True
+ self.analysis_paramsgui.prperr = True
+ self.analysis_paramsgui.blnkfltr = self.ui.checkBox_blankfilter.isChecked()
+
+ if self.ui.radioButton_blankfilter_abs.isChecked():
+ self.analysis_paramsgui.blankfilparam = 'absolute'
+ self.analysis_paramsgui.blankfilthresh = float(self.ui.lineEdit_blankfilter_absthresh.text())
+ else:
+ self.analysis_paramsgui.blankfilparam = 'relative'
+ self.analysis_paramsgui.blankfilthresh = float(self.ui.lineEdit_blankfilter_relthresh.text())
+ if self.ui.checkBox_blankfilter.isChecked() and self.analysis_paramsgui.blnkgrp == '':
+ self.analysis_paramsgui.blnkgrp = 'Blanks'
+ self.analysis_paramsgui.ppmthresh = float(self.ui.lineEdit_ppmthresh.text())
+
+
+ def regenerateplts(self):
+ pltfile = self.analysis_paramsgui.outputdir / (self.analysis_paramsgui.filename.stem + '_filtered.csv')
+ dfs = self.filtereddfs
+ grpsts = self.groupsets
+
+ if self.analysis_paramsgui.CVfil:
+ self.prevcv.reset(self, '', '')
+ stop_functime('cvplt complete')
+
+ self.ftplt.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', '', '')
+ stop_functime('ftplt complete')
+
+ self.dend.reset(pltfile, '', '')
+ stop_functime('dendrogram complete')
+
+ if self.analysis_paramsgui.PCA:
+ self.pca.reset(pltfile, '', '')
+ stop_functime('nmds complete')
+
+ if self.analysis_paramsgui.FC3Dplt:
+ self.fc3d.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('fc3d complete')
+
+ if self.analysis_paramsgui.KMD:
+ self.kmd.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('kmd complete')
+
+ if self.analysis_paramsgui.MZRTplt:
+ self.mzrt.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('mzrt complete')
+
+ if self.analysis_paramsgui.Volcanoplt:
+ self.volcano.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('volcano complete')
+
+ self.heatmap.reset(self, 'heatmap', self.ui.frame_heatmap, pltfile)
+ stop_functime('heatmap complete')
+
+ self.samplecorr.reset(self.analysis_paramsgui.outputdir / 'iondict.csv', dfs, grpsts)
+ stop_functime('samplecorr complete')
+
+ self.ui.label_status.setText('Update Complete')
+
+
+
+ ## APP EVENTS
+ ########################################################################
+ def mousePressEvent(self, event):
+ self.dragPos = event.globalPos()
+
+
+if __name__ == "__main__":
+ app = QtWidgets.QApplication(sys.argv)
+ if sys.platform != 'win32':
+ app.setStyle('Fusion')
+ app.setStyleSheet("QFrame { border: 0px; }") #QToolTip { color: #999999; background-color: rgb(0, 255, 0); border: 1px solid grey; }")
+ window = MainWindow()
+ sys.exit(app.exec_())
diff --git a/code/mspwriter.py b/code/mspwriter.py
index 41e56a6..b2d5085 100644
--- a/code/mspwriter.py
+++ b/code/mspwriter.py
@@ -41,15 +41,10 @@ def convert_to_msp(ionfilter_obj, analysis_params):
f.write('Charge:\n') # MSP file requires a formula field, but it can be left empty
f.write('Precursor: ' + mass + '\n') # MSP file requires a formula field, but it can be left empty
f.write('Comment: ' + ionmerge[precursor].target + '\n') # MSP file requires a formula field, but it can be left empty
+ numpeaks = 0
sources = ionmerge[precursor].sources
- # Num peaks must equal the total number of fragment lines actually
- # written below (the nested loop emits one line per fragment across
- # every sublist). The previous ``numpeaks = len(frags)`` overwrote
- # rather than accumulated, so it only reported the last sublist's
- # length; identical for the sole live caller (decon, where
- # ``sources == [[frag, ...]]`` is a single sublist) but wrong for any
- # multi-sublist merge. ``sum`` makes the count correct by construction.
- numpeaks = sum(len(frags) for frags in sources)
+ for frags in sources:
+ numpeaks = len(frags)
f.write('Num peaks: ' + str(numpeaks) + '\n') # Number of peaks
for frags in sources:
for fragment in frags:
diff --git a/code/mzmineimport.py b/code/mzmineimport.py
index 7a42e4c..f27fb2a 100644
--- a/code/mzmineimport.py
+++ b/code/mzmineimport.py
@@ -10,49 +10,29 @@
def format_check(parent):
- """Detect the peak table's source format and convert it to MPACT's internal
- layout.
-
- Uses the content-based detection in ``translators`` (so it is robust to
- column shuffling between tool versions) and reports failures instead of
- silently swallowing them, so a bad import is visible to the user rather than
- producing a mysteriously broken analysis downstream.
"""
- import translators
-
+ Check if the file has the right format, and if not, reformat it.
+ """
try:
- path = Path(parent.filename)
- fmt = translators.detect_peaktable_format(path)
- print('Peak table format detected: ' + fmt)
-
- if fmt == translators.MSDIAL:
- reformat_msdial(path)
- # MS-DIAL conversion writes a sibling .csv; make it the active file.
- parent.filename = path.parent / (path.stem + '.csv')
- path = Path(parent.filename)
- elif fmt == translators.MZMINE:
- reformat_mzmine(path)
- elif fmt == translators.METABOSCAPE:
- reformat_metaboscape(path)
- # PROGENESIS is already the internal layout; nothing to convert.
-
- if path.suffix == '.csv':
- # Normalise/deduplicate compound ids (preserves prior behaviour:
- # rename_duplicates is a no-op when there are no duplicates).
- rename_duplicates(path)
-
- if fmt == translators.UNKNOWN:
- try:
- parent.error('Unrecognised peak-table format; import may fail')
- except Exception:
- pass
+ if parent.filename.suffix == '.txt':
+ reformat_msdial(Path(parent.filename))
+ parent.filename = Path(str(parent.filename)[:-4] + '.csv')
+
+
+ if parent.filename.suffix == '.csv':
+ msdata = pd.read_csv(parent.filename, sep = ',', header = None, index_col = None) #imports feature list
+ if msdata.iloc[0, 0] == 'row ID':
+ reformat_mzmine(Path(parent.filename))
+ if msdata.iloc[0, 0] == 'Bucket label':
+ reformat_metaboscape(Path(parent.filename))
+
+ msdata = pd.read_csv(Path(parent.filename), sep = ',', header = [0,1,2], index_col = [0]) #imports data
+ if len(msdata[~msdata.index.duplicated()].index) > 0:
+ rename_duplicates(Path(parent.filename))
+
except Exception:
- import traceback
- traceback.print_exc()
- try:
- parent.error('Could not read/convert peak table (see console)')
- except Exception:
- pass
+ pass
+ return()
def reformat_metaboscape(file):
diff --git a/code/plotting.py b/code/plotting.py
index 5a6f754..8c70bb5 100644
--- a/code/plotting.py
+++ b/code/plotting.py
@@ -1,7 +1,6 @@
"""
MPACT
Copyright 2022, Robert M. Samples, Sara P. Puckett, and Marcy J. Balunas
-Modifications Copyright 2026, Robert M. Samples
"""
import concurrent.futures
import concurrent
@@ -9,11 +8,6 @@
import pandas as pd
import pickle
-from csvcache import cached_read_csv, invalidate as invalidate_csv_cache
-import ordination
-import clusterpurity
-import qualityscore
-
import matplotlib
#matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
@@ -33,51 +27,59 @@
import platform
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import (QCoreApplication, QPropertyAnimation, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent)
-from PyQt5.QtGui import (QBrush, QColor, QIcon, QPalette, QPainter)
+from PyQt5.QtGui import (QBrush, QColor, QIcon, QPalette, QPainter, QPixmap)
from PyQt5.QtWidgets import *
from pathlib import Path
import scipy.cluster.hierarchy as shc
from sklearn.preprocessing import normalize
+from sklearn import manifold
+from sklearn.metrics import pairwise_distances
+from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from matplotlib.patches import Ellipse
from filter import listfilter
import time
+import math
from pvclust import PvClust
-# The plot toolbars previously used a NavigationToolbar2QT subclass whose only
-# addition was a cog "Configure" button that opened the plot-config dialog.
-# Every option that dialog held has since moved onto the individual plots' own
-# control bars, so the dialog (and the cog that launched it) is redundant --
-# reverted to matplotlib's stock toolbar. The name is kept as an alias so the
-# existing NavigationToolbar(canvas, parent) call sites don't change.
-NavigationToolbar = NavigationToolbar2QT
-
-def _is_duplicate_pick(parent, event):
- """True if this pick event's underlying mouse click already triggered a
- pick on another overlapping artist.
-
- Matplotlib fires one ``pick_event`` per artist whose hit-test matches a
- click, not one per click. When the same feature is plotted in more than
- one groupset/colour layer (separate ``ax.scatter()`` calls at the same
- coordinates), clicking it fires our callback once per overlapping layer
- for a single physical click. Each call reselects the same feature, which
- -- because selecting an already-selected feature toggles the highlight
- off -- made the net result of clicking an overplotted feature an
- immediate deselect. Deduplicating by the shared ``mouseevent`` (every pick
- event from one click carries the same ``mouseevent`` instance) makes one
- click produce exactly one selection regardless of how many layers it hits.
- """
- mouseevent = getattr(event, 'mouseevent', None)
- if mouseevent is None:
- return False
- if getattr(parent, '_last_pick_mouseevent', None) is mouseevent:
- return True
- parent._last_pick_mouseevent = mouseevent
- return False
-
+class NavigationToolbar(NavigationToolbar2QT):
+ """
+ This is a subclass of the NavigationToolbar2QT that provides additional functionality. It is responsible for creating a custom button in the plot toolbar. The custom button is used to configure the plot.
+ Constructor arguments:
+ - canvas: a FigureCanvasQTAgg instance representing the plot canvas
+ - parent: the parent widget
+
+ Attributes:
+ - clearButtons: a list of QToolButton instances representing the plot toolbar buttons
+ - picker: a QAction instance representing the custom button
+
+ Methods:
+ - __init__(self, canvas, parent): constructs a NavigationToolbar instance
+ """
+ def __init__(self, canvas, parent):
+ NavigationToolbar2QT.__init__(self,canvas,parent)
+ self.clearButtons=[]
+ next=None
+ for c in self.findChildren(QToolButton):
+ if next is None:
+ next=c
+ if str(c.text()) in ('Pan','Zoom','Subplots'):
+ self.clearButtons.append(c)
+ next=None
+ # create custom button
+ icon = QtGui.QIcon("cog.ico")
+ picker=QAction("Pick",self)
+ picker.setIcon(icon)
+ picker.setToolTip("Configure")
+ self.picker = picker
+ button=QToolButton(self)
+ button.setDefaultAction(self.picker)
+ button.clicked.connect(lambda: parent.dialog.show())
+ self.addWidget(button)
+
#General plot method#
class ui_plot:
"""
@@ -120,13 +122,9 @@ def __init__(self, parent, currplt, frame):
parent.ax[currplt].set_facecolor(self.plotbackground)
def onpick(self, event, parent, iondict, plotcols):
- if _is_duplicate_pick(parent, event):
- return
ind = event.ind
coord = event.artist.get_offsets()[ind, :]
pickedfeature = iondict.loc[iondict[plotcols[0]] == coord[0, 0], :].loc[iondict[plotcols[1]] == coord[0, 1], :]
- if pickedfeature.empty:
- return
parent.ui.lbl_featurename.setText('Compound: ' + str(pickedfeature.iloc[0, 0]))
parent.ui.lbl_featurert.setText('Retention time: ' + str(round(pickedfeature.iloc[0, 2], 4)))
parent.ui.lbl_featuremz.setText('m/z: ' + str(round(pickedfeature.iloc[0, 1], 4)))
@@ -185,13 +183,13 @@ def __init__(self, parent, currplt):
def plot(self, parent):
# Get header info
currplt = self.currplt
- msdata = cached_read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[0, 1, 2], index_col=[0]).iloc[:, 2:].loc[parent.pickedfeature]
+ msdata = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[0, 1, 2], index_col=[0]).iloc[:, 2:].loc[parent.pickedfeature]
msdata = msdata.reset_index()
msdata.columns = ['biolgroup','sample','injection','abundance']
msdata = msdata.drop(columns=['injection'])
-
+
# Get stats for the given ion
- summary = cached_read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_summarydata.csv'), sep=',', header=[0, 1], index_col=[0]).iloc[:, 2:].loc[parent.pickedfeature]
+ summary = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_summarydata.csv'), sep=',', header=[0, 1], index_col=[0]).iloc[:, 2:].loc[parent.pickedfeature]
combasd = summary.loc[['combASD']].to_frame()
combasd.index = combasd.index.droplevel(level=0)
neff = summary.loc[['neff']].to_frame()
@@ -205,30 +203,18 @@ def plot(self, parent):
ionsummary['neff'] = neff
if parent.analysis_paramsgui.blnkfltr:
ionsummary = ionsummary.drop([parent.analysis_paramsgui.blnkgrp], axis=0)
- # Force the index to be unnamed before resetting it, so the new column
- # is always literally named "index" (used below by sns.barplot) --
- # newer pandas versions can carry a level name through droplevel()
- # where older ones silently dropped it, which otherwise renames this
- # column out from under the hardcoded x="index" reference.
- ionsummary.index.name = None
ionsummary = ionsummary.reset_index()
-
- # Use one explicit, shared palette keyed by biolgroup so the bar
- # chart's per-group colors (left) match the stripplot's hue colors
- # (right) instead of each picking its own default palette.
- groups = sorted(msdata['biolgroup'].unique())
- palette = dict(zip(groups, sns.color_palette(n_colors=len(groups))))
-
+
# Define the plotting function for stripplot
def plot_stripplot():
sns.stripplot(ax=parent.ax[currplt][1], x="sample", y="abundance", hue="biolgroup",
- data=msdata, palette=palette, size=7, dodge=False, alpha=.5, zorder=2)
+ data=msdata, size=7, dodge=False, alpha=.5, zorder=2)
# Define the plotting function for pointplot
def plot_pointplot():
sns.pointplot(ax=parent.ax[currplt][1], x="sample", y="abundance", color="#999999",
- data=msdata, dodge=False, linestyle='none', markers="d", markersize=6,
- zorder=1, capsize=.1, err_kws={'linewidth': 1}, errorbar=('ci', 95))
+ data=msdata, dodge=False, join=False, markers="d", scale=.75,
+ zorder=1, capsize=.1, errwidth=1, ci=95)
# Define a list of plotting functions to be run in parallel
plot_functions = [plot_stripplot, plot_pointplot]
@@ -241,14 +227,7 @@ def plot_pointplot():
for result in results:
result.result()
- # ionsummary is already one pre-aggregated row per category, not raw
- # per-sample data -- use matplotlib's ax.bar (not sns.barplot) since
- # newer seaborn no longer supports passing a manual yerr array through
- # to barplot (it routes kwargs through an internal single-point
- # "scout" call that only accepts a scalar/1-matching yerr).
- barcolors = [palette[g] for g in ionsummary["index"]]
- parent.ax[currplt][0].bar(ionsummary["index"], ionsummary["average"], yerr=ionsummary["combASD"],
- color=barcolors, ecolor=".2", edgecolor=".2", zorder=1, capsize=3)
+ sns.barplot(ax=parent.ax[currplt][0], x="index", y="average", yerr=ionsummary["combASD"], errcolor=".2", edgecolor=".2", data=ionsummary, zorder=1)
parent.ax[currplt][1].set_xticklabels(parent.ax[currplt][1].get_xticklabels(), rotation=90, horizontalalignment='center')
ylims = (0, parent.ax[currplt][1].get_ylim()[1] * 1.05)
@@ -373,37 +352,19 @@ class plot_heatmap():
frame (object): The object that the heatmap will be added to.
file (str): The file that contains the data for the heatmap.
"""
- VIEWS = ('Technical Replicates', 'Biological Replicates')
-
def __init__(self, parent, currplt, frame, file):
- # Colour scheme / View / Use-names: moved off the global plot-config
- # dialog onto this plot's own control bar, all live. Colour default
- # 'rocket' matches the old combo's first item; View defaults to
- # "Technical Replicates" (every injection its own column -- the plot's
- # previous behaviour). Cache the creation args so the control handlers
- # can call reset() with them.
- self.colorscheme = 'rocket'
- self.view = 'Technical Replicates'
- self.use_sample_names = False
- self._parent, self._currplt, self._frame, self._file = parent, currplt, frame, file
- msdata = self._heatmap_matrix(parent)
- cm = sns.clustermap(msdata, standard_scale=0, metric="euclidean", method="ward", cmap = self.colorscheme) #viridis
+ msdata = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep = ',', header = [2], index_col = [0]).iloc[:,2:]
+ cm = sns.clustermap(msdata, standard_scale=0, metric="euclidean", method="ward", cmap = parent.analysis_paramsgui.colorscheme) #viridis
parent.cmind = cm.dendrogram_row.reordered_ind #saves reordered index so that we can increment selection up and down.
parent.fig[currplt] = cm.fig
parent.pltlayout[currplt] = QtWidgets.QVBoxLayout()
- # Hug the control bar to the top edge -- the default QVBoxLayout margins
- # left a noticeably larger gap above this plot's option bar than the
- # other plots' bars.
- parent.pltlayout[currplt].setContentsMargins(0, 0, 0, 0)
- parent.pltlayout[currplt].setSpacing(0)
parent.canvas[currplt] = FigureCanvas(parent.fig[currplt])
parent.pltlayout[currplt].addWidget(parent.canvas[currplt])
parent.toolbar[currplt] = NavigationToolbar(parent.canvas[currplt], parent)
parent.toolbar[currplt].setStyleSheet("background-color:rgba(225,225,225,255);")
parent.pltlayout[currplt].addWidget(parent.toolbar[currplt])
parent.ui.frame_heatmap.setLayout(parent.pltlayout[currplt])
- self._build_control_bar(parent, currplt)
-
+
self.plotbackground = (.89, .89, .89, 0)
parent.canvas[currplt].figure.set_facecolor(self.plotbackground)
self.fcsfont = {'fontname':'Bahnschrift',
@@ -417,9 +378,7 @@ def __init__(self, parent, currplt, frame, file):
def onpick8(event): #rename
# this gets the position of the selected item, finds the item in the reodered index,
# and highlights the feature by name on other plots
- if _is_duplicate_pick(parent, event):
- return
- iondict = cached_read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep = ',', header = [0], index_col = [0])
+ iondict = pd.read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep = ',', header = [0], index_col = [0])
coord = [event.mouseevent.xdata,event.mouseevent.ydata]
parent.heatind = int(np.floor(coord[1]))
name = msdata.index.tolist()[parent.cmind[parent.heatind]]
@@ -455,89 +414,10 @@ def on_ylims_change(event_ax): #changes the limits of the y dendrogram when the
#parent.canvas[currplt].figure.axes[2].set_xticklabels(colind, rotation=0)
parent.canvas[currplt].draw()
- def _heatmap_matrix(self, parent):
- """Features x samples matrix for the clustermap, honouring the View and
- Use-Names controls.
-
- Feature ROWS are always kept in the peak table's file order (header=[2])
- regardless of view, so the cmind/heatind feature<->row mapping used by
- onpick8 and MainWindow's highlight/W-S navigation stays valid -- only the
- columns (and their labels) change between views."""
- pltfile = parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv')
- msdata = cached_read_csv(pltfile, sep=',', header=[2], index_col=[0]).iloc[:, 2:]
- raw_header = cached_read_csv(pltfile, sep=',', header=None, index_col=[0, 1, 2]).iloc[:3, :].transpose()
- raw_header.columns = ['Biolgroup', 'Sample', 'Injection']
- if self.view == 'Biological Replicates':
- # Average technical replicates (injection columns) within each
- # Sample. Group only the columns (via transpose) so the feature row
- # order is untouched.
- sample_of_injection = raw_header.set_index('Injection')['Sample']
- msdata = msdata.transpose().groupby(sample_of_injection).mean().transpose()
- if self.use_sample_names:
- msdata = msdata.copy()
- msdata.columns = self._display_labels(raw_header, msdata.columns.tolist())
- return msdata
-
- def _display_labels(self, raw_header, textlabels):
- """Short ``Biolgroup_b#[_s#]`` column labels in place of the raw
- injection/sample names, mirroring plot_dendrogram's labelling."""
- components = ordination.replicate_label_components(raw_header)
- if self.view == 'Biological Replicates':
- per_sample = components.drop_duplicates('Sample').set_index('Sample')
- return [f"{per_sample.loc[s, 'Biolgroup']}_b{per_sample.loc[s, 'BioRep']}" for s in textlabels]
- return [
- f"{components.loc[inj, 'Biolgroup']}_b{components.loc[inj, 'BioRep']}_s{components.loc[inj, 'TechRep']}"
- for inj in textlabels
- ]
-
- def _build_control_bar(self, parent, currplt):
- bar = QtWidgets.QWidget()
- bar.setStyleSheet(_SWITCHER_BAR_STYLE)
- bar.setMaximumHeight(_SWITCHER_BAR_HEIGHT)
- layout = QtWidgets.QHBoxLayout(bar)
- layout.setContentsMargins(4, 2, 4, 2)
-
- layout.addWidget(QtWidgets.QLabel('View:'))
- view_combo = QtWidgets.QComboBox()
- view_combo.addItems(self.VIEWS)
- view_combo.setCurrentText(self.view)
- view_combo.currentTextChanged.connect(self._on_view_changed)
- layout.addWidget(view_combo)
-
- layout.addWidget(QtWidgets.QLabel('Color scheme:'))
- color_combo = QtWidgets.QComboBox()
- color_combo.addItems(_COLORSCHEMES)
- color_combo.setCurrentText(self.colorscheme)
- color_combo.currentTextChanged.connect(self._on_colorscheme_changed)
- layout.addWidget(color_combo)
-
- use_names_check = QtWidgets.QCheckBox('Use Sample/Group Names')
- use_names_check.setChecked(self.use_sample_names)
- use_names_check.toggled.connect(self._on_use_names_toggled)
- layout.addWidget(use_names_check)
- layout.addStretch()
-
- self.view_combo = view_combo
- self.color_combo = color_combo
- self.use_names_check = use_names_check
- parent.pltlayout[currplt].insertWidget(0, bar)
-
- def _on_colorscheme_changed(self, scheme):
- self.colorscheme = scheme
- self.reset(self._parent, self._currplt, self._frame, self._file)
-
- def _on_view_changed(self, view):
- self.view = view
- self.reset(self._parent, self._currplt, self._frame, self._file)
-
- def _on_use_names_toggled(self, checked):
- self.use_sample_names = checked
- self.reset(self._parent, self._currplt, self._frame, self._file)
-
def reset(self, parent, currplt, frame, file):
#makes new figure with updated heatmap and saves
- msdata = self._heatmap_matrix(parent)
- cm2 = sns.clustermap(msdata, standard_scale=0, metric="euclidean", method="ward", cmap = self.colorscheme) #viridis
+ msdata = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep = ',', header = [2], index_col = [0]).iloc[:,2:]
+ cm2 = sns.clustermap(msdata, standard_scale=0, metric="euclidean", method="ward", cmap = parent.analysis_paramsgui.colorscheme) #viridis
parent.cmind = cm2.dendrogram_row.reordered_ind
updatedfig = cm2.fig
parent.canvas[currplt].figure.clf()
@@ -616,7 +496,7 @@ def __init__(self, parent, currplt, frame, file, filtereddfs, groupsets):
self.plot(parent, file, filtereddfs, groupsets)
def plot(self, parent, file, filtereddfs, groupsets): # abundance tied opacity used here currently
- iondict = cached_read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=None)
+ iondict = pd.read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=None)
for elem in filtereddfs:
if parent.analysis_paramsgui.blnkfltr:
@@ -637,7 +517,7 @@ def plot(self, parent, file, filtereddfs, groupsets): # abundance tied opacity u
parent.highlight[self.currplt], = parent.ax[self.currplt].plot([], [], 'o', markersize=12, color='yellow')
parent.ax[self.currplt].set_xlabel("Retention time (min)", **self.fcsfont)
parent.ax[self.currplt].set_ylabel('m/z', **self.fcsfont)
- parent.ax[self.currplt].set_xlim(0, 11.5)
+ parent.ax[self.currplt].set_xlim(-.5, 11.5)
parent.ax[self.currplt].set_ylim(0, 1850)
parent.ax[self.currplt].legend()
@@ -649,185 +529,49 @@ def plot(self, parent, file, filtereddfs, groupsets): # abundance tied opacity u
class plot_samplecorr(ui_plot):
"""
- Sample-correlation heatmap, with a Method/View/label switcher bar
- inserted into the *shared* Group Analysis nav bar (frame_12 /
- horizontalLayout_25, alongside the pre-existing "Sets"/"Sample
- Correlations" buttons) rather than this plot's own canvas -- unlike
- plot_dendrogram/plot_ordination's per-canvas bars, these controls only
- apply to this page, and the nav bar is shared with the UpSet plot page.
- UIFunctions.switch_grpanalysis_tab (ui_functions.py) greys the controls
- out when the UpSet page is active.
-
- Views (same collapsing semantics as plot_dendrogram/plot_ordination,
- via ordination.load_ordination_matrix):
- - "Biological Replicates" (default, matches this plot's previous,
- checkbox-less behaviour): technical replicates averaged per Sample,
- biological replicates kept separate.
- - "Individual Injections": no averaging, every injection is its own
- row/column.
- - "Biological Groups": both technical and biological replicates
- averaged together, one row/column per Biolgroup -- "see only
- biological groups" with technical-replicate averaging implied.
-
- Methods (ordination.similarity_matrix):
- - "Spearman" (default): rank correlation of abundance profiles.
- - "Jaccard": presence/absence (feature detected or not), ignoring
- abundance.
- - "Bray-Curtis": abundance-weighted, the standard ecology/metabolomics
- similarity measure.
-
- "Use Sample/Group Names" checkbox: same nomenclature as the
- dendrogram's -- ``_b_s`` (Individual
- Injections), ``_b`` (Biological Replicates), or the
- raw Biolgroup name (Biological Groups -- nothing left to shorten).
+ The plot_samplecorr class generates a heatmap plot of the Spearman or Pearson correlation between samples.
+
+ Parameters:
+
+ parent: the parent widget for the plot
+ currplt: the index of the current plot within the parent widget
+ frame: the parent frame for the plot
+ file: a path to the file containing the ion dictionary
+ filtereddfs: a dictionary containing filtered dataframes for each group in the plot
+ groupsets: a dictionary containing GroupSet objects for each group in the plot
+ Methods:
+
+ __init__(self, parent, currplt, frame, file, filtereddfs, groupsets): initializes the plot by calling the plot() method with the given parameters
+ plot(self, parent, file, filtereddfs, groupsets): generates the plot with the given data. Reads the ion dictionary from a csv file and reads the filtered data from a csv file generated by the program. Calculates the Spearman correlation matrix and generates a heatmap plot using the Seaborn library. Adjusts the layout of the plot and draws it on the parent canvas.
"""
-
- VIEWS = ('Biological Replicates', 'Individual Injections', 'Biological Groups')
- METHODS = ('Spearman', 'Jaccard', 'Bray-Curtis')
-
def __init__(self, parent, currplt, frame, file, filtereddfs, groupsets):
ui_plot.__init__(self, parent, currplt, frame)
self.parent = parent
self.currplt = currplt
- self.view = 'Biological Replicates'
- self.method = 'Spearman'
- self.use_sample_names = False
- # Colour scheme shares the same param the heatmap tab uses; it moved off
- # the global plot-config dialog (combo_colorscheme) so this plot keeps
- # its own live copy here rather than reading a now-removed dialog widget.
- self.colorscheme = 'rocket'
- self._build_grpanalysis_controls(parent)
self.plot(parent, file, filtereddfs, groupsets)
-
- def _build_grpanalysis_controls(self, parent):
- bar = QtWidgets.QWidget()
- bar.setStyleSheet(_SWITCHER_BAR_STYLE)
- bar.setMaximumHeight(_SWITCHER_BAR_HEIGHT)
- layout = QtWidgets.QHBoxLayout(bar)
- layout.setContentsMargins(4, 2, 4, 2)
-
- layout.addWidget(QtWidgets.QLabel('Method:'))
- method_combo = QtWidgets.QComboBox()
- method_combo.addItems(self.METHODS)
- method_combo.setCurrentText(self.method)
- method_combo.currentTextChanged.connect(self._on_method_changed)
- layout.addWidget(method_combo)
-
- layout.addWidget(QtWidgets.QLabel('View:'))
- view_combo = QtWidgets.QComboBox()
- view_combo.addItems(self.VIEWS)
- view_combo.setCurrentText(self.view)
- view_combo.currentTextChanged.connect(self._on_view_changed)
- layout.addWidget(view_combo)
-
- use_names_check = QtWidgets.QCheckBox('Use Sample/Group Names')
- use_names_check.setChecked(self.use_sample_names)
- use_names_check.toggled.connect(self._on_use_sample_names_toggled)
- layout.addWidget(use_names_check)
-
- layout.addWidget(QtWidgets.QLabel('Color:'))
- color_combo = QtWidgets.QComboBox()
- color_combo.addItems(_COLORSCHEMES)
- color_combo.setCurrentText(self.colorscheme)
- color_combo.currentTextChanged.connect(self._on_colorscheme_changed)
- layout.addWidget(color_combo)
-
- self.method_combo = method_combo
- self.view_combo = view_combo
- self.use_names_check = use_names_check
- self.color_combo = color_combo
- self.controls_bar = bar
-
- # Pushes the new controls to the right of the pre-existing
- # Sets/Sample Correlations buttons within the same shared bar,
- # rather than editing the generated horizontalLayout_25 itself.
- parent.ui.horizontalLayout_25.addStretch(1)
- parent.ui.horizontalLayout_25.addWidget(bar)
-
- def set_controls_enabled(self, enabled):
- """Grey the Method/View/Use-Names controls out when the UpSet Plot
- page (the nav bar's other tab) is active -- they don't apply there."""
- self.controls_bar.setEnabled(enabled)
-
- def _on_method_changed(self, method):
- self.method = method
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _on_view_changed(self, view):
- self.view = view
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _on_use_sample_names_toggled(self, checked):
- self.use_sample_names = checked
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _on_colorscheme_changed(self, scheme):
- self.colorscheme = scheme
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _load_matrix(self, parent):
- pltfile = parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv')
- raw_header = cached_read_csv(pltfile, sep=',', header=None, index_col=[0, 1, 2]).iloc[:3, :].transpose()
- x, biolgroup = ordination.load_ordination_matrix(
- pltfile, raw_header.copy(), collapse_replicates=(self.view != 'Individual Injections'))
- if self.view == 'Biological Groups':
- x = x.groupby(biolgroup).mean()
- return x, raw_header
-
- def _display_labels(self, raw_header, leaf_names):
- """Build short ``Biolgroup_b#[_s#]`` labels, mirroring
- plot_dendrogram's ``_display_labels`` -- nomenclature switches on
- the active View the same way."""
- if self.view == 'Biological Groups':
- return leaf_names # already bare Biolgroup names
- components = ordination.replicate_label_components(raw_header)
- if self.view == 'Biological Replicates':
- per_sample = components.drop_duplicates('Sample').set_index('Sample')
- return [f"{per_sample.loc[sample, 'Biolgroup']}_b{per_sample.loc[sample, 'BioRep']}" for sample in leaf_names]
- return [
- f"{components.loc[injection, 'Biolgroup']}_b{components.loc[injection, 'BioRep']}_s{components.loc[injection, 'TechRep']}"
- for injection in leaf_names
- ]
-
+
def plot(self, parent, file, filtereddfs, groupsets):
- self._last_file = file
- self._last_filtereddfs = filtereddfs
- self._last_groupsets = groupsets
-
- x, raw_header = self._load_matrix(parent)
- pmatrix = ordination.similarity_matrix(x, self.method)
-
- leaf_names = pmatrix.columns.tolist()
- display_labels = self._display_labels(raw_header, leaf_names) if self.use_sample_names else leaf_names
-
- fig = self.parent.fig[self.currplt]
- # clf() + add_subplot: sns.heatmap permanently shrinks the axes each
- # call to make room for its colorbar; removing the extra colorbar axes
- # afterwards doesn't restore the original size. Starting fresh each
- # call keeps the axes at a consistent width.
- fig.clf()
- ax = fig.add_subplot(111)
- ax.set_facecolor(self.plotbackground)
- ax.set_axisbelow(True)
- self.parent.ax[self.currplt] = ax
- # Spearman is mathematically capable of going negative, but real
- # sample-vs-sample correlations in practice cluster tightly positive
- # (e.g. 0.7-1.0) -- a -1..1 scale would compress all of that
- # meaningful variation into a sliver of the colour range. 0..1 for
- # every method keeps the full range informative.
- sns.heatmap(pmatrix, ax=ax, cmap=self.colorscheme, vmin=0, vmax=1)
+ iondict = pd.read_csv(self.parent.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=None)
+ msdata = pd.read_csv(self.parent.analysis_paramsgui.outputdir / (self.parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
+ try:
+ msdata = msdata.stack([0, 1, 2], future_stack=True).groupby(level=[0, 1, 2, 3, 4]).mean().droplevel(level=3, axis=0).unstack()
+ except TypeError:
+ msdata = msdata.stack([0, 1, 2]).groupby(level=[0, 1, 2, 3, 4]).mean().droplevel(level=3, axis=0).unstack()
+ msdata.index = msdata.index.droplevel([1, 2])
+ pmatrix = msdata.corr(method='spearman')
+ ax = self.parent.ax[self.currplt].figure.axes[0] if len(self.parent.ax[self.currplt].figure.axes) > 1 else self.parent.ax[self.currplt]
+ sns.heatmap(pmatrix, ax=ax, cmap=self.parent.analysis_paramsgui.colorscheme, vmin=0, vmax=1)
ax.tick_params(axis='both', which='both', labelsize=10)
ax.set_xticks(range(len(pmatrix.columns)))
- ax.set_xticklabels(display_labels, rotation=90)
+ ax.set_xticklabels(pmatrix.columns, rotation=90)
ax.set_yticks(range(len(pmatrix.index)))
- ax.set_yticklabels(display_labels, rotation=0)
+ ax.set_yticklabels(pmatrix.index, rotation=0)
ax.axes.get_xaxis().get_label().set_visible(False)
ax.axes.get_yaxis().get_label().set_visible(False)
- ax.set_title(self.method, fontsize=10)
self.parent.fig[self.currplt].subplots_adjust(left=.1, right=.95, bottom=0.15, top=0.9, hspace=0.2, wspace=0.2)
self.parent.canvas[self.currplt].draw()
-
-
+
+
class kendrick(ui_plot):
"""
The purpose of this class is to plot the mass defect versus the nominal mass of compounds based on the input files and parameters provided.
@@ -845,42 +589,15 @@ def __init__(self, parent, currplt, frame, file, filtereddfs, groupsets):
super().__init__(parent, currplt, frame)
self.parent = parent
self.currplt = currplt
- # Mass-defect guideline reference lines: moved off the global plot-config
- # dialog (checkBox_mdguide) onto this plot's own control bar, live (a
- # toggle re-renders immediately via reset()), the same pattern as
- # plot_dendrogram's switcher bar. Default on, matching the old checkbox's
- # Designer default.
- self.show_mdguide = True
- self._build_control_bar(parent, currplt)
self.plot(parent, file, filtereddfs, groupsets)
- def _build_control_bar(self, parent, currplt):
- bar = QtWidgets.QWidget()
- bar.setStyleSheet(_SWITCHER_BAR_STYLE)
- bar.setMaximumHeight(_SWITCHER_BAR_HEIGHT)
- layout = QtWidgets.QHBoxLayout(bar)
- layout.setContentsMargins(4, 2, 4, 2)
- guide_check = QtWidgets.QCheckBox('Mass Defect Guidelines')
- guide_check.setChecked(self.show_mdguide)
- guide_check.toggled.connect(self._on_mdguide_toggled)
- layout.addWidget(guide_check)
- layout.addStretch()
- self.guide_check = guide_check
- parent.pltlayout[currplt].insertWidget(0, bar)
-
- def _on_mdguide_toggled(self, checked):
- self.show_mdguide = checked
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
def plot(self, parent, file, filtereddfs, groupsets):
"""
The method first reads the input file as a pandas dataframe iondict. If the blnkfltr parameter in parent.analysis_paramsgui is True, then the dataframes in filtereddfs are filtered to exclude blank data.
For each element in filtereddfs, the nominal mass (m/z) and mass defect (kmd) data is plotted as a scatter plot. The color of each point is determined by the plotcol parameter in groupsets. The legendname parameter in groupsets is used to label the points in the plot.
- If self.show_mdguide is True (the per-plot "Mass Defect Guidelines" checkbox), then reference lines are plotted.
+ If the mdguide parameter in parent.analysis_paramsgui is True, then reference lines are plotted.
+ less
"""
- self._last_file = file
- self._last_filtereddfs = filtereddfs
- self._last_groupsets = groupsets
iondict = pd.read_csv(file, sep=',', header=0, index_col=None)
if parent.analysis_paramsgui.blnkfltr:
@@ -903,18 +620,13 @@ def plot(self, parent, file, filtereddfs, groupsets):
parent.ax[self.currplt].legend()
self.event = parent.canvas[self.currplt].figure.canvas.mpl_connect('pick_event', lambda event: self.onpick(event, parent, iondict, ('m/z', 'kmd')))
parent.fig[self.currplt].subplots_adjust(left=0.1, right=0.95, bottom=0.15, top=0.9, hspace=0.2, wspace=0.2)
+ parent.canvas[self.currplt].draw()
- # Draw the guideline reference lines BEFORE canvas.draw() -- they used to
- # be added after draw(), so re-checking the box added the artists but
- # never repainted (the lines only reappeared on the next unrelated
- # redraw). Adding them before the draw() makes the toggle symmetric.
- if self.show_mdguide:
+ if parent.analysis_paramsgui.mdguide:
parent.ax[self.currplt].plot([0, 733.314], [0.00112, 0.8408], color='dimgrey', linestyle='-', linewidth=1)
parent.ax[self.currplt].plot([63.6623, 733.314], [1, 0.8408], color='dimgrey', linestyle='-', linewidth=1)
parent.ax[self.currplt].plot([0, 465.456], [0.9884, 0.5408], color='dimgrey', linestyle='-', linewidth=1)
- parent.canvas[self.currplt].draw()
-
class plot_volcano(ui_plot):
"""
volcano plot of -log10p vs log2 abundance value
@@ -923,67 +635,9 @@ def __init__(self, parent, currplt, frame, file, filtereddfs, groupsets):
super().__init__(parent, currplt, frame)
self.parent = parent
self.currplt = currplt
- # Significance thresholds: moved off the global plot-config dialog
- # (lineEdit_pqthresh/lineEdit_fcthresh) onto this plot's own control bar,
- # live (editing a value re-renders immediately), same pattern as
- # plot_dendrogram. Defaults match the old line-edits' Designer text.
- self.pqthresh = 0.05
- self.fcthresh = 1.5
- self._build_control_bar(parent, currplt)
self.plot(parent, file, filtereddfs, groupsets)
- def _build_control_bar(self, parent, currplt):
- bar = QtWidgets.QWidget()
- bar.setStyleSheet(_SWITCHER_BAR_STYLE)
- bar.setMaximumHeight(_SWITCHER_BAR_HEIGHT)
- layout = QtWidgets.QHBoxLayout(bar)
- layout.setContentsMargins(4, 2, 4, 2)
-
- layout.addWidget(QtWidgets.QLabel('p/q threshold:'))
- pq_edit = QtWidgets.QLineEdit(str(self.pqthresh))
- pq_edit.setMaximumWidth(70)
- pq_edit.editingFinished.connect(self._on_pqthresh_changed)
- layout.addWidget(pq_edit)
-
- layout.addWidget(QtWidgets.QLabel('Fold-change threshold:'))
- fc_edit = QtWidgets.QLineEdit(str(self.fcthresh))
- fc_edit.setMaximumWidth(70)
- fc_edit.editingFinished.connect(self._on_fcthresh_changed)
- layout.addWidget(fc_edit)
- layout.addStretch()
-
- self.pq_edit = pq_edit
- self.fc_edit = fc_edit
- parent.pltlayout[currplt].insertWidget(0, bar)
-
- def _on_pqthresh_changed(self):
- # editingFinished can fire on focus-out even when nothing changed; parse
- # defensively and revert the field (rather than re-rendering) on bad input.
- try:
- val = float(self.pq_edit.text())
- except ValueError:
- self.pq_edit.setText(str(self.pqthresh))
- return
- if val == self.pqthresh:
- return
- self.pqthresh = val
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _on_fcthresh_changed(self):
- try:
- val = float(self.fc_edit.text())
- except ValueError:
- self.fc_edit.setText(str(self.fcthresh))
- return
- if val == self.fcthresh:
- return
- self.fcthresh = val
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
def plot(self, parent, file, filtereddfs, groupsets):
- self._last_file = file
- self._last_filtereddfs = filtereddfs
- self._last_groupsets = groupsets
pqvar = '-logq' if parent.analysis_paramsgui.FDR else '-logp'
parent.ui.lbl_volcanowarn.setText('' if parent.analysis_paramsgui.FDR else 'False discovery rate correction off')
@@ -998,10 +652,6 @@ def plot(self, parent, file, filtereddfs, groupsets):
filtereddfs[elem]['logfc'] = np.log2(filtereddfs[elem]['fc']) #not sure if best to move this bit to stats?
iondict['logfc'] = np.log2(iondict['fc'])
iondict.to_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', header = True, index = False)
- # iondict.csv just changed on disk -- drop every cached read of it so
- # other code (e.g. fillfttree(), _refresh_highlight()) doesn't keep
- # serving a stale pre-volcano-plot copy under some other cache key.
- invalidate_csv_cache()
maxpval = 0
for elem in filtereddfs:
@@ -1011,8 +661,8 @@ def plot(self, parent, file, filtereddfs, groupsets):
if max_val > maxpval:
maxpval = max_val
- sig = filtereddfs[elem][filtereddfs[elem][pqvar] >= -np.log10(self.pqthresh)]
- sig = sig[sig['logfc'].abs() >= np.log2(self.fcthresh)]
+ sig = filtereddfs[elem][filtereddfs[elem][pqvar] >= -np.log10(parent.analysis_paramsgui.pqthresh)]
+ sig = sig[sig['logfc'].abs() >= np.log2(parent.analysis_paramsgui.fcthresh)]
nonsig = filtereddfs[elem][~filtereddfs[elem]['Compound'].isin(sig['Compound'].to_list())]
parent.ax[self.currplt].scatter(sig[sig['logfc'] > 0]['logfc'], sig[sig['logfc'] > 0][pqvar], color='red', picker=True, alpha=0.5)
@@ -1021,9 +671,9 @@ def plot(self, parent, file, filtereddfs, groupsets):
parent.highlight[self.currplt], = parent.ax[self.currplt].plot([], [], 'o', markersize=12, color='yellow')
- parent.ax[self.currplt].plot([-np.log2(self.fcthresh), -np.log2(self.fcthresh)], [0, maxpval*1.2], color='dimgrey', linestyle='-', linewidth=1)
- parent.ax[self.currplt].plot([np.log2(self.fcthresh), np.log2(self.fcthresh)], [0, maxpval*1.2], color='dimgrey', linestyle='-', linewidth=1)
- parent.ax[self.currplt].plot([-6.75, 6.75], [-np.log10(self.pqthresh), -np.log10(self.pqthresh)], color='dimgrey', linestyle='-', linewidth=1)
+ parent.ax[self.currplt].plot([-np.log2(parent.analysis_paramsgui.fcthresh), -np.log2(parent.analysis_paramsgui.fcthresh)], [0, maxpval*1.2], color='dimgrey', linestyle='-', linewidth=1)
+ parent.ax[self.currplt].plot([np.log2(parent.analysis_paramsgui.fcthresh), np.log2(parent.analysis_paramsgui.fcthresh)], [0, maxpval*1.2], color='dimgrey', linestyle='-', linewidth=1)
+ parent.ax[self.currplt].plot([-6.75, 6.75], [-np.log10(parent.analysis_paramsgui.pqthresh), -np.log10(parent.analysis_paramsgui.pqthresh)], color='dimgrey', linestyle='-', linewidth=1)
parent.ax[self.currplt].set_xlabel("log2 fold change", **self.fcsfont)
parent.ax[self.currplt].set_ylabel('-log10 ' + pqvar[-1] + '-value', **self.fcsfont)
@@ -1078,7 +728,7 @@ def plot(self, parent, file, filtereddfs, groupsets):
parent.ax[self.currplt].set_ylabel('Retention time (min)', **self.fcsfont, labelpad=20)
parent.ax[self.currplt].set_zlabel('m/z', **self.fcsfont, labelpad=25)
parent.ax[self.currplt].tick_params(axis='z', pad=10)
- parent.ax[self.currplt].set_ylim(0, 11.5)
+ parent.ax[self.currplt].set_ylim(-0.5, 11.5)
parent.ax[self.currplt].grid()
parent.ax[self.currplt].legend()
parent.fig[self.currplt].subplots_adjust(
@@ -1087,498 +737,181 @@ def plot(self, parent, file, filtereddfs, groupsets):
class plot_dendrogram(ui_plot):
"""
- Dendrogram generation, with combo-box switchers (same pattern as
- plot_ordination's method/view bar) for which leaves to cluster and how
- to color the branches:
-
- Views:
- - "Technical Replicates": every injection is its own leaf -- branches
- are judged for purity against Sample membership, a quick visual QC
- for whether technical replicates are tight.
- - "Biological Replicates": injections are first averaged per Sample
- (same collapsing logic as the ordination tab's "Collapse Technical
- Replicates" checkbox, via ordination.load_ordination_matrix), then
- leaves are Samples, judged for purity against Biolgroup -- a quick
- visual QC for whether biological groups are separable at all,
- independent of technical noise.
-
- Coloring:
- - "Purity": green wherever a branch's leaves are entirely one group
- (correctly clustered), magenta wherever a branch mixes more than one
- group (polyphyletic). Green/magenta rather than the more conventional
- green/red since red-green colorblindness can't distinguish the latter.
- - "None": plain black dendrogram, no purity coloring or title -- the
- tab's original (pre-purity-coloring) appearance.
-
- Either view/coloring combination can be regular or bootstrapped
- (PvClust) depending on the "Bootstrap" checkbox in this tab's own
- switcher bar (formerly the plot-config dialog's global "Bootstrap
- Analysis" checkbox -- moved here since it only ever applied to this
- plot). The purity-coloring math lives in the Qt-free clusterpurity.py.
-
- A "Use Sample/Group Names" checkbox swaps the leaf labels from the raw
- file/injection names (which can be long or uninformative) to
- ``_b_s`` (Technical Replicates view) or
- ``_b`` (Biological Replicates view, no TechRep#
- since replicates are already collapsed) -- see
- ``ordination.replicate_label_components()``.
+ Dendrogram generation.
+
+ A CSV file of data for clustering is read and code performs hierarchical clustering using the ward method
+ and the euclidean distance metric. The resulting dendrogram is plotted on the given frame using the parent object's
+ figure and canvas. The dendrogram can be either regular or bootstrapped depending on the value of the
+ parent.analysis_paramsgui.bootstrap parameter. The resulting plot is saved to the parent object's figure and
+ displayed on the canvas.
"""
- VIEWS = ('Technical Replicates', 'Biological Replicates')
- COLOR_MODES = ('Purity', 'None')
-
def __init__(self, parent, currplt, frame, file, filtereddfs, groupsets):
ui_plot.__init__(self, parent, currplt, frame)
self.parent = parent
self.currplt = currplt
- # Defaults match the plot's previous (injection-level, uncolored)
- # behaviour exactly, so existing sessions see no change until they
- # explicitly switch the new controls. ``bootstrap`` defaults to True
- # to match the checked-on-startup state the old global checkbox was
- # forced to in ui_functions.py (its Designer default was actually
- # False, overridden at runtime -- True is what users actually saw).
- self.view = 'Technical Replicates'
- self.color_mode = 'Purity'
- self.bootstrap = True
- self.use_sample_names = False
- self._build_switcher_bar(parent, currplt)
self.plot(parent, file, filtereddfs, groupsets)
- def _build_switcher_bar(self, parent, currplt):
- bar = QtWidgets.QWidget()
- bar.setStyleSheet(_SWITCHER_BAR_STYLE)
- bar.setMaximumHeight(_SWITCHER_BAR_HEIGHT)
- layout = QtWidgets.QHBoxLayout(bar)
- layout.setContentsMargins(4, 2, 4, 2)
-
- layout.addWidget(QtWidgets.QLabel('View:'))
- view_combo = QtWidgets.QComboBox()
- view_combo.addItems(self.VIEWS)
- view_combo.setCurrentText(self.view)
- view_combo.currentTextChanged.connect(self._on_view_changed)
- layout.addWidget(view_combo)
-
- layout.addWidget(QtWidgets.QLabel('Color:'))
- color_combo = QtWidgets.QComboBox()
- color_combo.addItems(self.COLOR_MODES)
- color_combo.setCurrentText(self.color_mode)
- color_combo.currentTextChanged.connect(self._on_color_mode_changed)
- layout.addWidget(color_combo)
-
- bootstrap_check = QtWidgets.QCheckBox('Bootstrap')
- bootstrap_check.setChecked(self.bootstrap)
- bootstrap_check.toggled.connect(self._on_bootstrap_toggled)
- layout.addWidget(bootstrap_check)
-
- use_names_check = QtWidgets.QCheckBox('Use Sample/Group Names')
- use_names_check.setChecked(self.use_sample_names)
- use_names_check.toggled.connect(self._on_use_sample_names_toggled)
- layout.addWidget(use_names_check)
- layout.addStretch()
-
- self.view_combo = view_combo
- self.color_combo = color_combo
- self.bootstrap_check = bootstrap_check
- self.use_names_check = use_names_check
- parent.pltlayout[currplt].insertWidget(0, bar)
-
- def _on_view_changed(self, view):
- self.view = view
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _on_color_mode_changed(self, color_mode):
- self.color_mode = color_mode
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _on_bootstrap_toggled(self, checked):
- self.bootstrap = checked
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _on_use_sample_names_toggled(self, checked):
- self.use_sample_names = checked
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _display_labels(self, raw_header, textlabels):
- """Build short ``Biolgroup_b#[_s#]`` leaf labels in place of the raw
- file/injection names, when "Use Sample/Group Names" is checked."""
- components = ordination.replicate_label_components(raw_header)
- if self.view == 'Biological Replicates':
- per_sample = components.drop_duplicates('Sample').set_index('Sample')
- return [f"{per_sample.loc[sample, 'Biolgroup']}_b{per_sample.loc[sample, 'BioRep']}" for sample in textlabels]
- return [
- f"{components.loc[injection, 'Biolgroup']}_b{components.loc[injection, 'BioRep']}_s{components.loc[injection, 'TechRep']}"
- for injection in textlabels
- ]
-
def plot(self, parent, file, filtereddfs, groupsets):
- self._last_file = file
- self._last_filtereddfs = filtereddfs
- self._last_groupsets = groupsets
-
- # PvClust (bootstrap path) expects "variables x objects" -- it
- # bootstraps over the rows (features) and transposes internally
- # before clustering the columns (the objects/leaves). shc.linkage
- # (regular path) expects the opposite, "objects x variables" --
- # build both orientations from the same scaled data below.
- if self.view == 'Biological Replicates':
- # Collapse technical replicates first -- leaves are Samples,
- # purity is judged against Biolgroup.
- raw_header = cached_read_csv(
- parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'),
- sep=',', header=None, index_col=[0, 1, 2]).iloc[:3, :].transpose()
- x, biolgroup = ordination.load_ordination_matrix(file, raw_header.copy(), collapse_replicates=True)
- data_scaled = normalize(x.values, axis=1) # normalize each sample's profile
- data_scaled = pd.DataFrame(data_scaled, columns=x.columns, index=x.index) # samples x features
- textlabels = data_scaled.index.tolist()
- leaf_labels = [biolgroup[sample] for sample in textlabels]
- data_for_linkage = data_scaled
- data_for_pvclust = data_scaled.transpose()
- purity_noun = 'biological groups separable'
- else:
- heirarch = pd.read_csv(file, sep=',', header=[2], index_col=[0]).drop(['m/z', 'Retention time (min)'], axis=1)
- data_scaled = normalize(heirarch, axis=0) # normalize features
- data_scaled = pd.DataFrame(data_scaled, columns=heirarch.columns, index=heirarch.index) # features x injections
- textlabels = data_scaled.columns.tolist()
- raw_header = cached_read_csv(
- parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'),
- sep=',', header=None, index_col=[0, 1, 2]).iloc[:3, :].transpose()
- raw_header.columns = ['Biolgroup', 'Sample', 'Injection']
- sample_of_injection = raw_header.set_index('Injection')['Sample'].to_dict()
- leaf_labels = [sample_of_injection[name] for name in textlabels]
- data_for_linkage = data_scaled.transpose()
- data_for_pvclust = data_scaled
- purity_noun = "samples' replicates clustered together"
-
- if self.bootstrap:
+ heirarch = pd.read_csv(file, sep=',', header=[2], index_col=[0]).drop(['m/z', 'Retention time (min)'], axis=1)
+ data_scaled = normalize(heirarch, axis=0) # normalize features
+ data_scaled = pd.DataFrame(data_scaled, columns=heirarch.columns, index=heirarch.index)
+ textlabels = [elem for elem in data_scaled.columns.tolist()]
+
+ if parent.analysis_paramsgui.bootstrap:
# bootstrap dendrogram
- pv = PvClust(data_for_pvclust, method="ward", metric="euclidean", nboot=1000, parallel=True)
- Z = pv.linkage_matrix
+ pv = PvClust(data_scaled, method="ward", metric="euclidean", nboot=1000, parallel=True)
+ dend = pv.plot(parent.ax[self.currplt], labels=textlabels)
else:
# regular dendrogram
- Z = shc.linkage(data_for_linkage, method='ward')
-
- if self.color_mode == 'Purity':
- # Green = monophyletic (correctly clustered); magenta =
- # polyphyletic (mixes more than one group). Magenta rather than
- # the conventional red -- distinguishable from green under
- # red-green colorblindness, the most common form.
- link_color_func = clusterpurity.purity_link_color_func(Z, leaf_labels, true_color='green', false_color='magenta')
- else:
- link_color_func = None # plain black dendrogram, scipy's own default
-
- display_labels = self._display_labels(raw_header, textlabels) if self.use_sample_names else textlabels
-
- if self.bootstrap:
- dend = pv.plot(parent.ax[self.currplt], labels=display_labels, link_color_func=link_color_func)
- else:
- dend = shc.dendrogram(Z, ax=parent.ax[self.currplt], leaf_rotation=90, color_threshold=0, above_threshold_color='black', link_color_func=link_color_func, labels=display_labels) # default leaf label size 16
-
- if self.color_mode == 'Purity':
- n_pure, n_total = clusterpurity.purity_summary(Z, leaf_labels)
- parent.ax[self.currplt].set_title(f'{n_pure}/{n_total} {purity_noun}', fontsize=10)
- # "None" coloring intentionally leaves no title -- this tab had none
- # before purity coloring was added.
+ dend = shc.dendrogram(shc.linkage(data_scaled.transpose(), method='ward'), ax=parent.ax[self.currplt], leaf_rotation=90, color_threshold=0, above_threshold_color='black', labels=textlabels) # default leaf label size 16
parent.fig[self.currplt].subplots_adjust(
left=0.1, right=0.95, bottom=0.35, top=0.9, hspace=0.2, wspace=0.2)
parent.canvas[self.currplt].draw()
-# Shared by plot_dendrogram's and plot_ordination's combo-box switcher bars
-# -- page_dend and page_pca both have the same light background
-# (rgba(225,225,225,255), see ui_main.py), unlike searchtree.py's filter bar
-# (a dark-themed tab) -- dark text on a light/white combo box, not
-# searchtree's light-on-dark scheme.
-_SWITCHER_BAR_HEIGHT = 32
-
-# matplotlib/seaborn colormap names offered by the heatmap & sample-correlation
-# colour-scheme dropdowns (these moved off the plot-config dialog's
-# combo_colorscheme onto the plots' own bars). Order/contents match the old
-# combo's items; 'rocket' (index 0) stays the default.
-_COLORSCHEMES = ('rocket', 'mako', 'flare', 'crest', 'magma', 'viridis')
-
-_SWITCHER_BAR_STYLE = """
-QWidget {
- background: transparent;
-}
-QComboBox {
- background-color: rgb(255,255,255);
- color: rgb(30,30,30);
- border: 1px solid rgb(150,150,150);
- border-radius: 2px;
- padding: 2px;
-}
-QComboBox:disabled {
- background-color: rgb(220,220,220);
- color: rgb(150,150,150);
- border: 1px solid rgb(195,195,195);
-}
-QLabel {
- color: rgb(30,30,30);
- background: transparent;
-}
-QLabel:disabled {
- color: rgb(150,150,150);
-}
-QCheckBox:disabled {
- color: rgb(150,150,150);
-}
-QLineEdit {
- background-color: rgb(255,255,255);
- color: rgb(30,30,30);
- border: 1px solid rgb(150,150,150);
- border-radius: 2px;
- padding: 2px;
-}
-"""
-
-
-class plot_ordination(ui_plot):
- """Multivariate ordination plot: PCA, NMDS, or PLS-DA, with a
- scores-vs-loadings view toggle.
-
- A combo-box switcher bar (built once in ``__init__``, inserted above the
- canvas the same way ``SearchTreePanel``'s filter bar is substituted into
- a Designer placeholder -- see searchtree.py) lets the user pick the
- ordination method and the scores/loadings view; both redraw onto the
- same axes via ``self.plot(...)`` rather than rebuilding the canvas.
-
- The actual math lives in the Qt-free ``ordination.py`` (PCA/NMDS/PLS-DA,
- technical-replicate collapsing, top-N loadings selection); this class is
- just the Qt plumbing and rendering on top of it.
-
- The switcher bar also has a "Collapse Replicates" checkbox (formerly the
- plot-config dialog's global "Collapse Technical Replicates" checkbox --
- moved here since it only ever applied to this plot).
- """
-
- METHODS = ('NMDS', 'PCA', 'PLS-DA')
- VIEWS = ('Scores', 'Loadings')
-
+class plot_PCA(ui_plot):
+ #plots NMDS data
+ # should include opion to allow user specified pca colors
+ # need to fix selection of samples on PCA plot
+ # should add PCA vs NMDS option
def __init__(self, parent, currplt, frame, file, filtereddfs, groupsets):
ui_plot.__init__(self, parent, currplt, frame)
self.parent = parent
self.currplt = currplt
- # Defaults match the plot's previous (NMDS-only, scores-only)
- # behaviour exactly, so existing sessions see no change until they
- # explicitly switch the new controls. ``collapse_replicates``
- # defaults to True, matching the old global checkbox's Designer
- # default.
- self.method = 'NMDS'
- self.view = 'Scores'
- self.collapse_replicates = True
- self.loadings_df = None
- self._build_switcher_bar(parent, currplt)
self.plot(parent, file, filtereddfs, groupsets)
- def _build_switcher_bar(self, parent, currplt):
- bar = QtWidgets.QWidget()
- bar.setStyleSheet(_SWITCHER_BAR_STYLE)
- bar.setMaximumHeight(_SWITCHER_BAR_HEIGHT)
- layout = QtWidgets.QHBoxLayout(bar)
- layout.setContentsMargins(4, 2, 4, 2)
-
- layout.addWidget(QtWidgets.QLabel('Method:'))
- method_combo = QtWidgets.QComboBox()
- method_combo.addItems(self.METHODS)
- method_combo.setCurrentText(self.method)
- method_combo.currentTextChanged.connect(self._on_method_changed)
- layout.addWidget(method_combo)
-
- layout.addWidget(QtWidgets.QLabel('View:'))
- view_combo = QtWidgets.QComboBox()
- view_combo.addItems(self.VIEWS)
- view_combo.setCurrentText(self.view)
- view_combo.currentTextChanged.connect(self._on_view_changed)
- layout.addWidget(view_combo)
-
- collapse_check = QtWidgets.QCheckBox('Collapse Replicates')
- collapse_check.setChecked(self.collapse_replicates)
- collapse_check.toggled.connect(self._on_collapse_replicates_toggled)
- layout.addWidget(collapse_check)
- layout.addStretch()
-
- self.method_combo = method_combo
- self.view_combo = view_combo
- self.collapse_check = collapse_check
- parent.pltlayout[currplt].insertWidget(0, bar)
-
- def _on_method_changed(self, method):
- self.method = method
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _on_view_changed(self, view):
- self.view = view
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
- def _on_collapse_replicates_toggled(self, checked):
- self.collapse_replicates = checked
- self.reset(self._last_file, self._last_filtereddfs, self._last_groupsets)
-
def plot(self, parent, file, filtereddfs, groupsets):
- """(Re)draw the ordination plot for the current method/view.
-
+ """Plot principal component analysis (PCA) or NMDS data.
+
Args:
- parent (QWidget): Parent widget (MainWindow).
- file (str): Path to the ``_filtered.csv`` peak table.
- filtereddfs, groupsets: unused here (kept for the shared
- ``_create_or_reset``/``reset`` call signature every plot
- class follows).
+ parent (QWidget): Parent widget.
+ currplt (int): Current plot number.
+ frame (QFrame): Frame to hold the plot.
+ file (str): Path to the file containing the PCA data.
+ filtereddfs (list): List of filtered data.
+ groupsets (list): List of group sets.
+
+ Attributes:
+ highlightcol (tuple): Tuple containing RGBA values used for highlighting.
+ event (int): Identifier for the pick event used to select points on the plot.
+
+ Methods:
+ plot(self, parent, file, filtereddfs, groupsets): Plot the PCA data.
+ plot_point_cov(self, points, nstd=2, ax=None, **kwargs): Generate an ellipse for the confidence interval.
+ lighten_color(self, color, amount=0.5): Lighten a given color by a given amount.
+ plot_cov_ellipse(self, cov, pos, nstd=2, ax=None, **kwargs): Generate an optimized ellipse for the confidence interval.
"""
parent = self.parent
- self._last_file = file
- self._last_filtereddfs = filtereddfs
- self._last_groupsets = groupsets
-
- collapse_replicates = self.collapse_replicates
- raw_header = cached_read_csv(
- parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'),
- sep=',', header=None, index_col=[0, 1, 2]).iloc[:3, :].transpose()
- x, biolgroup = ordination.load_ordination_matrix(file, raw_header.copy(), collapse_replicates)
-
- n_components = max(2, min(len(x) - 1, 10))
+ parent.collapsereps = False#parent.dialog.ui.checkBox_collapsereps.isChecked()
+
+ if parent.collapsereps:
+ # Average techreps if replicate collapse is selected
+ msdata = pd.read_csv(file, sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
+ try:
+ msdata = msdata.stack([0, 1, 2], future_stack=True)
+ except TypeError:
+ msdata = msdata.stack([0, 1, 2])
+ msdata = msdata.groupby(level=[0, 1, 2, 3, 4]).mean().unstack(level=[-1, -2])
+ test2 = msdata.columns.to_list()
+ msdata = msdata.reset_index()
+ header = [('','','Compound'), ('','','m/z'), ('','','Retention time (min)')]
+ for elem in test2:
+ header.append((elem[1], '', elem[0]))
+ msdata.columns = pd.MultiIndex.from_tuples(header)
+ msdata.to_csv('averagepca.csv', header=True, index=False)
+
+ msdata_header = pd.read_csv('averagepca.csv', sep=',', header=None, index_col=[0, 1, 2]).iloc[:3, :].transpose()
+ pcadf = pd.read_csv('averagepca.csv', sep=',', header=[2], index_col=[0]).drop(['m/z', 'Retention time (min)'], axis=1).transpose().astype(float).reset_index().rename(columns={'index': 'File'})
+ else:
+ msdata_header = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=None, index_col=[0, 1, 2]).iloc[:3, :].transpose()
+ pcadf = pd.read_csv(file, sep=',', header=[2], index_col=[0]).drop(['m/z', 'Retention time (min)'], axis=1).transpose().astype(float).reset_index().rename(columns={'index': 'File'})
+ components = len(msdata_header.index)
+ if components > 10:
+ components = 10
+ msdata_header.columns = ['Biolgroup', 'Sample', 'Injection']
+ msdata_header = msdata_header.set_index('Injection')
colors = ['red', 'blue', 'black', 'grey', 'purple', 'orange', 'green', 'yellow', 'lime', 'plum', 'teal', 'olivedrab', 'sienna', 'maroon', 'navy', 'lightcoral', 'darkgoldenrod', 'seagreen', 'lightseagreen', 'aqua', 'lightsteelblue', 'slateblue', 'blueviolet', 'plum', 'burlywood', 'salmon', 'aquamarine', 'magenta', 'tan']
colorpos, biolgroupmap = 0, {}
- for elem in biolgroup:
+ for elem in msdata_header['Biolgroup']:
if elem not in biolgroupmap and elem != parent.analysis_paramsgui.blnkgrp: ###### delete blank clause OR CHANGE TO THE BLNKFILTER OPTION
biolgroupmap[elem] = colors[colorpos]
colorpos += 1
-
- plot_title = None
- if self.method == 'PCA':
- scores, loadings, expvar = ordination.run_pca(x, n_components)
- axis_labels = [f'PC{i + 1} ({100 * expvar[i]:.1f}%)' for i in range(2)]
- elif self.method == 'PLS-DA':
- scores, loadings, expvar = ordination.run_plsda(x, biolgroup, n_components)
- axis_labels = [f'PLS{i + 1} ({100 * expvar[i]:.1f}%)' for i in range(2)]
- else:
- scores, expvar, stress = ordination.run_nmds(x, n_components)
- loadings = ordination.nmds_loading_proxy(x, scores)
- # NMDS doesn't canonically report percent-variance-explained the
- # way PCA/PLS-DA do (it's a rank-based embedding, not a linear
- # decomposition of the feature space) -- stress is the
- # conventional thing to report for NMDS instead.
- axis_labels = ['NMDS1', 'NMDS2']
- plot_title = f'Stress: {stress:.4f}'
-
- self.loadings_df = loadings
- principalDf = scores.copy()
- principalDf['Biolgroup'] = biolgroup
-
- if self.view == 'Loadings':
- self._plot_loadings(parent, loadings, axis_labels)
- else:
- self._plot_scores(parent, principalDf, biolgroupmap, axis_labels)
-
- if plot_title:
- parent.ax[self.currplt].set_title(plot_title, fontsize=10)
-
- parent.fig[self.currplt].subplots_adjust(left=.1, right=.9, bottom=0.1, top=0.9, hspace=0.2, wspace=0.2)
- parent.canvas[self.currplt].draw()
-
- def _plot_scores(self, parent, principalDf, biolgroupmap, axis_labels):
+
+ features = pcadf.columns.values[1:]
+ x = pcadf[features].values
+ y = pcadf[['File']].values
+ x -= x.mean()
+ similarities = pairwise_distances(x, metric='braycurtis')
+
+ mds = manifold.MDS(n_components=components, max_iter=3000, eps=1e-9, random_state=1,
+ dissimilarity="precomputed", n_jobs=1)
+ pos = mds.fit(similarities).embedding_
+
+ nmds = manifold.MDS(n_components=components, metric=False, max_iter=3000, eps=1e-12,
+ dissimilarity="precomputed", random_state=1, n_jobs=1,
+ n_init=1)
+ npos = nmds.fit_transform(similarities, init=pos)
+ stress_value = nmds.stress_
+ print("NMDS stress: " +str(stress_value))
+
+ pca = PCA(n_components=components)
+ nmdspc = pca.fit_transform(npos)
+ expvar = pca.explained_variance_ratio_
+ pcadftest = pd.DataFrame(data=nmdspc)
+
+ ncomplist = list(range(components))
+ nmdspc = pd.DataFrame(data=nmdspc, columns=ncomplist)
+ nmdspc['File'] = pcadf['File']
+ nmdspc['Biolgroup'] = ''
+ for i, elem in enumerate(nmdspc.iloc[:, components]):
+ nmdspc.iloc[i, components + 1] = msdata_header.loc[elem, 'Biolgroup']
+ principalDf = nmdspc.set_index('File')
+
for elem in biolgroupmap:
scatterframe = principalDf[principalDf['Biolgroup'] == elem]
- points = scatterframe.iloc[:, [0, 1]].to_numpy()
+ points = scatterframe.iloc[:,[0,1]].to_numpy()
if np.shape(points)[0] > 2:
self.plot_point_cov(points, nstd=2, ax=parent.ax[self.currplt], alpha=0.5, color=self.lighten_color(biolgroupmap[elem], 0.3))
- parent.ax[self.currplt].scatter(scatterframe.iloc[:, 0], scatterframe.iloc[:, 1], color=biolgroupmap[elem], marker='o', s=30, label=str(elem), picker=True)
-
+ parent.ax[self.currplt].scatter(scatterframe.iloc[:,0], scatterframe.iloc[:,1], color=biolgroupmap[elem], marker='o', s=30, label=str(elem), picker=True)
+
parent.highlight[self.currplt], = parent.ax[self.currplt].plot([], [], 'o', markersize=12, color='yellow')
- parent.ax[self.currplt].set_xlabel(axis_labels[0], **self.fcsfont)
- parent.ax[self.currplt].set_ylabel(axis_labels[1], **self.fcsfont)
-
+ parent.ax[self.currplt].set_xlabel('NMDS1', **self.fcsfont) # (' + str(round(100*expvar[0], 2)) + '%)'
+ parent.ax[self.currplt].set_ylabel('NMDS2', **self.fcsfont) #(' + str(round(100*expvar[1], 2)) + '%)'
+
+ #following two lines put a hard limit on the axis tick distance
+ #parent.ax[self.currplt].xaxis.set_major_locator(ticker.MultipleLocator(0.1))
+ #parent.ax[self.currplt].yaxis.set_major_locator(ticker.MultipleLocator(0.1))
+
self.highlightcol = (0, 0, 0, 0)
parent.pickedsample = pd.DataFrame(0, index=['empty'], columns=['empty'])
-
- def picksample(event):
- if _is_duplicate_pick(parent, event):
- return
+
+ def picksample(event): # fix this
ind = event.ind
- coord = event.artist.get_offsets()[ind, :]
- newsample = principalDf.loc[principalDf.iloc[:, 0] == coord[0, 0], :].loc[principalDf.iloc[:, 1] == coord[0, 1], :].reset_index()
- if newsample.empty:
- return
-
- if newsample.iloc[0, 0] == parent.pickedsample.iloc[0, 0] and self.highlightcol != (0, 0, 0, 0):
+ coord = event.artist.get_offsets()[ind,:]
+ newsample = principalDf.loc[principalDf.iloc[:,0] == coord[0,0], :].loc[principalDf.iloc[:,1] == coord[0,1], :].reset_index()
+
+ if newsample.iloc[0,0] == parent.pickedsample.iloc[0,0] and self.highlightcol != (0, 0, 0, 0):
self.highlightcol = (0, 0, 0, 0)
else:
self.highlightcol = 'yellow'
-
+
parent.pickedsample = newsample
- parent.ui.lbl_injname.setText('Injection/Sample: ' + str(parent.pickedsample.iloc[0, 0]))
- parent.highlight[self.currplt].set_data(coord[0, 0], coord[0, 1])
+ parent.ui.lbl_injname.setText('Injection/Sample: ' + str(parent.pickedsample.iloc[0,0]))
+ parent.highlight[self.currplt].set_data(coord[0,0],coord[0,1])
parent.highlight[self.currplt].set_color(self.highlightcol)
parent.canvas[self.currplt].draw_idle()
-
+
self.event = parent.canvas[self.currplt].figure.canvas.mpl_connect('pick_event', picksample)
+ parent.fig[self.currplt].subplots_adjust(left=.1, right=.9, bottom=0.1, top=0.9, hspace=0.2, wspace=0.2)
+ #x0,x1 = parent.ax[self.currplt].get_xlim()
+ #0,y1 = parent.ax[self.currplt].get_ylim()
+ #parent.ax[self.currplt].set_aspect(abs(x1-x0)/abs(y1-y0))
+ #parent.ax[self.currplt].set_aspect('equal')
parent.ax[self.currplt].legend()
-
- def _plot_loadings(self, parent, loadings, axis_labels):
- """Loadings (biplot-style) view: origin-anchored arrows for the
- top-N features by vector magnitude, plus -- regardless of
- magnitude -- whichever feature is currently highlighted elsewhere
- in the app (``parent.pickedfeature``), so a feature too small to
- make the default cut is still visible on demand.
- """
- always_include = [parent.pickedfeature] if getattr(parent, 'pickedfeature', '') else []
- # Rank by magnitude within the 2 displayed components only, not the
- # full (up to 10-component) loadings -- a feature could rank in the
- # overall top-25 purely from a large contribution to some other,
- # unplotted component while barely showing up here, displacing a
- # feature that's actually prominent in this 2D view.
- subset = ordination.top_loadings(loadings.iloc[:, :2], n=25, always_include=always_include)
-
- # ax.annotate()'s arrows don't reliably drive matplotlib's autoscale
- # the way ax.scatter()/ax.plot() do (confirmed empirically: points
- # can end up outside the auto-picked view limits), so the axis
- # range is set explicitly here instead of relying on autoscale.
- # Symmetric around 0 since loadings/correlations are naturally
- # origin-centered (a biplot convention).
- limit = subset.iloc[:, :2].abs().values.max() * 1.2 if len(subset) else 1.0
- parent.ax[self.currplt].set_xlim(-limit, limit)
- parent.ax[self.currplt].set_ylim(-limit, limit)
-
- for feature, row in subset.iterrows():
- xcoord, ycoord = row.iloc[0], row.iloc[1]
- parent.ax[self.currplt].annotate(
- '', xy=(xcoord, ycoord), xytext=(0, 0),
- arrowprops=dict(arrowstyle='->', color='steelblue', lw=1))
- parent.ax[self.currplt].annotate(
- str(feature), xy=(xcoord, ycoord), fontsize=8, color='black')
-
- # Pre-created empty artist for the highlighted-loading marker,
- # following the same convention as the scores view's
- # parent.highlight[currplt] -- updated on demand by
- # MainWindow._refresh_highlight() via self.highlight_loading(),
- # even when the highlighted feature isn't in the default top-25.
- self.loadings_highlight, = parent.ax[self.currplt].plot([], [], 'o', markersize=12, color='yellow', zorder=5)
- self.highlight_loading(getattr(parent, 'pickedfeature', ''), getattr(parent, 'highlightcol', (0, 0, 0, 0)))
-
- parent.ax[self.currplt].axhline(0, color='grey', lw=0.5)
- parent.ax[self.currplt].axvline(0, color='grey', lw=0.5)
- parent.ax[self.currplt].set_xlabel(axis_labels[0], **self.fcsfont)
- parent.ax[self.currplt].set_ylabel(axis_labels[1], **self.fcsfont)
-
- def highlight_loading(self, feature, colour):
- """Update the loadings-view highlight marker for ``feature`` (a
- no-op outside the loadings view or before it's been drawn once).
-
- Called from ``MainWindow._refresh_highlight()`` -- the same
- pre-create-empty-artist/update-via-set_data convention every other
- plot's highlight already follows, just driven by this plot's own
- last-computed loadings instead of ``iondict``.
- """
- if self.view != 'Loadings' or self.loadings_df is None or not hasattr(self, 'loadings_highlight'):
- return
- if not feature or feature not in self.loadings_df.index:
- self.loadings_highlight.set_data([], [])
- else:
- row = self.loadings_df.loc[feature]
- self.loadings_highlight.set_data([row.iloc[0]], [row.iloc[1]])
- self.loadings_highlight.set_color(colour)
- self.parent.canvas[self.currplt].draw_idle()
-
+ parent.canvas[self.currplt].draw()
+
def plot_point_cov(self, points, nstd=2, ax=None, **kwargs):
"""Generate an ellipse for the confidence interval.
@@ -1662,23 +995,63 @@ def __init__(self, parent, currplt, frame, file, filtereddfs, groupsets):
self.plot(parent, file, filtereddfs, groupsets)
def plot(self, parent, file, filtereddfs, groupsets):
- # Load ion data and the average injections-per-sample (for the noise
- # model that scales the CV axis), then compute the quality metrics in
- # the Qt-free qualityscore module (unit-tested; see qualityscore.py).
- iondict = cached_read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', header=0, index_col=0)
- msdata_header = cached_read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=None, index_col=[0,1,2]).iloc[:3,:].transpose()
+ # Load and filter ion data
+ iondict = pd.read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', header=0, index_col=0)
+ iondict = iondict[~np.isnan(iondict['average CV'])]
+
+ # Calculate mean and median CV, and scale data
+ iondictmean = iondict.sort_values(['average CV']).reset_index()
+ iondictmed = iondict.sort_values(['median CV']).reset_index()
+ iondictmean = iondictmean.reset_index()
+ iondictmed = iondictmed.reset_index()
+ iondictmean.iloc[:,0] = 100 * iondictmean.iloc[:,0]/len(iondictmean['average CV'])
+ iondictmed.iloc[:,0] = 100 * iondictmed.iloc[:,0]/len(iondictmed['median CV'])
+
+ # Calculate maximum theoretical CV based on neff
+ msdata_header = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=None, index_col=[0,1,2]).iloc[:3,:].transpose()
msdata_header.columns = ['Biolgroup', 'Sample', 'Injection']
average_n = msdata_header['Injection'].nunique() / msdata_header['Sample'].nunique()
-
- result = qualityscore.compute_cv_quality(iondict, average_n)
- iondictmean = result.iondictmean
- iondictmed = result.iondictmed
- modelstdev = result.modelstdev
+ modelstdevlist = [1] + [0] * (int(average_n) - 1)
+ modelstdev = pd.Series(modelstdevlist).std() / pd.Series(modelstdevlist).mean()
+ cv50 = iondictmean.iloc[(iondictmean.iloc[:,0] - 50).abs().argsort()[:1]]['average CV']
+ sortedcv = iondictmean.iloc[(iondictmean.iloc[:,0]).argsort()]['average CV']
+ prevav = 0
+ aucav = 0
+ prevmed = 0
+ aucmed = 0
+ for pos in range(0,len(iondictmean.iloc[:,0])):
+ dist = iondictmean.iloc[pos,:]['average CV'] - prevav
+ aucav += dist*iondictmean.iloc[pos,0]
+ prevav = iondictmean.iloc[pos,:]['average CV']
+
+ dist = iondictmed.iloc[pos,:]['median CV'] - prevmed
+ aucmed += dist*iondictmed.iloc[pos,0]
+ prevmed = iondictmed.iloc[pos,:]['median CV']
+
+ meanav = 0
+ meanmed = 0
+ sumskew = 0
+ if math.isnan(modelstdev):
+ modelstdev = 1.7
+ for val in range(1, int((modelstdev*100))):
+ pos = val/100
+ meanav = iondictmean[abs(iondictmean['average CV'] - pos-modelstdev/200) < modelstdev/200].iloc[:,0].mean()
+ meanmed = iondictmed[abs(iondictmed['average CV'] - pos-modelstdev/200) < modelstdev/200].iloc[:,0].mean()
+ skew = abs(meanmed-meanav)
+ if not np.isnan(skew):
+ sumskew += skew * modelstdev/100
+
+
+ sumskew = sumskew/ ((aucmed+aucav)/2)
+ rep = ((aucmed+aucav)/2)/(modelstdev*100)
+ qualscore = (1-sumskew)*rep*100
+
+ #qualscore = round(100 * (1 - cv50 / modelstdev), 1)
# Update UI
- parent.ui.lbl_spllist_3.setText('Reproducibility:\n' + str(round(100*result.rep,1)) + '%\n' +
- 'Skewnewss:\n' + str(round(100*result.sumskew,1)) + '%\n\n' +
- 'Overall:\n' + str(round(result.qualscore,1)) + '%')
+ parent.ui.lbl_spllist_3.setText('Reproducibility:\n' + str(round(100*rep,1)) + '%\n' +
+ 'Skewnewss:\n' + str(round(100*sumskew,1)) + '%\n\n' +
+ 'Overall:\n' + str(round(qualscore,1)) + '%')
# Plot data
currplt = 'cvplt' #instead take this from input
@@ -1700,165 +1073,208 @@ def plot(self, parent, file, filtereddfs, groupsets):
parent.canvas[currplt].draw()
-def _detach_placeholder_widget(frame, old_widget):
- """Remove a Designer-placed placeholder widget (and the layout holding
- it) from ``frame`` so a fresh layout can be installed in its place.
-
- Most plot frames in this app start out empty in Designer, so
- ``ui_plot.__init__`` can just call ``frame.setLayout(...)`` directly.
- ``frame_treemap``/``frame_upset`` are the exception -- Designer gave
- them a layout with a placeholder ``QLabel`` (the old static-image
- target) already in it, and Qt refuses ``setLayout()`` on a frame that
- already has one. Reparenting the old layout onto a throwaway widget
- (the standard Qt trick for "delete this layout") detaches it from
- ``frame`` without touching anything else -- same runtime
- widget-substitution pattern as searchtree.py's filter-bar swap.
+def gen_upsetplt(parent): #need to do something to handle groups with names that are substrings of other group names
"""
- old_layout = frame.layout()
- if old_layout is not None:
- old_layout.removeWidget(old_widget)
- old_widget.setParent(None)
- old_widget.deleteLater()
- QtWidgets.QWidget().setLayout(old_layout)
-
-
-class plot_treemap(ui_plot):
- """Treemap of how many features each enabled filter removed.
-
- Drawn directly onto a persistent FigureCanvas (same runtime-widget-
- substitution + ui_plot pattern as every other plot tab) instead of the
- previous ``squarify.plot()`` -> ``savefig('treemap.png')`` -> ``QPixmap``
- round trip into a Designer-placed ``QLabel`` (``label_treemap``) -- that
- PNG round trip meant no zoom/pan/save-at-resolution toolbar, and a flat
- raster file rewritten at the repo root on every run.
- """
-
- def __init__(self, parent, currplt, frame, file, filtereddfs, groupsets):
- _detach_placeholder_widget(frame, parent.ui.label_treemap)
- ui_plot.__init__(self, parent, currplt, frame)
- self.parent = parent
- self.currplt = currplt
- self.plot(parent, file, filtereddfs, groupsets)
-
- def plot(self, parent, file, filtereddfs, groupsets):
- msdata_filtered = cached_read_csv(
- parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'),
- sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
- iondict = cached_read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=[0])
-
- fltrcnt, color = {}, []
- current = len(iondict.index)
-
- if parent.analysis_paramsgui.relfil:
- filteredsetsize = len(iondict[iondict['pass_relfil']].index)
- fltrcnt['Mispicked'] = current - filteredsetsize
- current = filteredsetsize
- color.append('#0000ff')
-
- if parent.analysis_paramsgui.blnkfltr:
- filteredsetsize = len(iondict[iondict['pass_blnkfil']].index)
- fltrcnt['Blank'] = current - filteredsetsize
- current = filteredsetsize
- color.append('#00aaaa')
-
- if parent.analysis_paramsgui.CVfil:
- fltrcnt['Nonreproducible'] = len(parent.ionfilters['cv'].ions)
- current = current - fltrcnt['Nonreproducible']
- color.append('#ff0000')
-
- if parent.analysis_paramsgui.decon:
- fltrcnt['Insource'] = len(parent.ionfilters['insource'].ions)
- color.append('#00aa00')
-
- fltrcnt['High Quality'] = len(msdata_filtered.index)
- color.append('#000000')
-
- sizes = list(fltrcnt.values())
- total_size = sum(sizes)
- labels = [f"{label}\n{size}\n{round(100 * size / total_size, 1)}%" for label, size in fltrcnt.items()]
-
- ax = parent.ax[self.currplt]
- ax.clear()
- squarify.plot(sizes=sizes, label=labels, color=color, alpha=0.3, text_kwargs={'fontsize': 10}, ax=ax)
- ax.axis('off')
- parent.canvas[self.currplt].draw()
+ Generate an upset plot to visualize sets of compounds in groups. This function also handles groups with names that are substrings of other group names.
+ Parameters:
+ parent (object): The parent object that the generated plot will be a child of.
-class plot_upset:
- """Upset plot of how filtered features distribute across groupsets.
-
- Drawn directly onto a persistent Figure -- ``upsetplot.plot()`` accepts
- an existing ``fig=`` instead of always creating its own -- rather than
- the previous ``upsetplot.plot()`` -> ``savefig('test_upsetplt.png')`` ->
- ``QPixmap`` round trip into the Designer-placed ``label_upset``.
-
- Doesn't subclass ``ui_plot``, the same as ``plot_heatmap`` and for the
- same reason: ``upsetplot`` lays out several axes (matrix, totals,
- intersections, shading) on the figure itself via its own gridspec --
- there's no single "ax" to hand callers the way every scatter/line plot
- here has, so ``ui_plot.__init__``'s single pre-made ``ax`` would just be
- an unused, overlapping blank axes.
+ Returns:
+ None
"""
+ iondict = pd.read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=0, index_col=None)
+
+ # Apply filters if required
+ if parent.analysis_paramsgui.relfil:
+ iondict = iondict[iondict['pass_relfil']]
+ if parent.analysis_paramsgui.decon:
+ iondict = iondict[iondict['pass_insource']]
+ if parent.analysis_paramsgui.blnkfltr:
+ iondict = iondict[iondict['pass_blnkfil']]
+ if parent.analysis_paramsgui.CVfil:
+ iondict = iondict[iondict['pass_cvfil']]
+
+ # Prepare data for upset plot
+ iongroups = iondict['groups'].tolist()
+ freq = {}
+ biolgroups = []
+ for item in iongroups:
+ if item not in freq:
+ freq[item] = 0
+ freq[item] += 1
+
+ header = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=None, index_col=[0, 1, 2]).iloc[0, :]
+ for elem in header:
+ if elem not in biolgroups:
+ biolgroups.append(elem)
+
+ sets = [' ' + elem for elem in list(freq.keys())]
+ size = list(freq.values())
+ setdf = pd.DataFrame({'groups': sets})
+ for elem in biolgroups: #have to do this if one group is a substring of another, add space
+ setdf[elem] = setdf['groups'].str.contains(' ' + elem)
+ setdf['size'] = size
+ setdf = setdf.iloc[:, 1:]
+ setdf = setdf.set_index(biolgroups)['size']
+
+ # Plot and display the upset plot
+ with plt.rc_context({"font.size": 8}):
+ upsetplt = upsetplot.plot(setdf, show_counts='%d', show_percentages=True, sort_categories_by=None)
+
+ figup = upsetplt['matrix'].figure
+ figup.set_size_inches(5, 4)
+ figup.set_facecolor((0, 0, 0, 0))
+ upsetplt['intersections'].set_facecolor((1, 1, 1, .25))
+ figup.savefig('test_upsetplt.png', dpi=150, bbox_inches='tight')
+ pixmap = QPixmap('test_upsetplt.png')
+ parent.ui.label_upset.setPixmap(pixmap)
+
+def gen_treemap(parent):
+ #generate treemap for visualization of filtering levels
+ #needed to refilter data and see how df row lengths change to avoid issues with one feature being in multiple filter lists
+ plt.clf()
+ msdata_filtered = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
+ fltrcnt, color = {}, []
+ iondict = pd.read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=[0])
+ total = len(iondict.index)
+ current = total
+
+ if parent.analysis_paramsgui.relfil:
+ filteredsetsize = len(iondict[iondict['pass_relfil']].index)
+ fltrcnt['Mispicked'] = current - filteredsetsize
+ current = filteredsetsize
+ color.append('#0000ff')
+
+ if parent.analysis_paramsgui.blnkfltr:
+ filteredsetsize = len(iondict[iondict['pass_blnkfil']].index)
+ fltrcnt['Blank'] = current - filteredsetsize
+ current = filteredsetsize
+ color.append('#00aaaa')
+
+ if parent.analysis_paramsgui.CVfil:
+ fltrcnt['Nonreproducible'] = len(parent.ionfilters['cv'].ions)
+ current = current - fltrcnt['Nonreproducible']
+ color.append('#ff0000')
+
+ if parent.analysis_paramsgui.decon:
+ fltrcnt['Insource'] = len(parent.ionfilters['insource'].ions)
+ color.append('#00aa00')
+
+ fltrcnt['High Quality'] = len(msdata_filtered.index)
+ color.append('#000000')
+
+ sizes = list(fltrcnt.values())
+ total_size = sum(fltrcnt.values())
+ labels = [f"{label}\n{size}\n{round(100*size/total_size,1)}%" for label, size in fltrcnt.items()]
+
+ squarify.plot(sizes=sizes, label=labels, color=color, alpha=0.3, text_kwargs={'fontsize': 10})
+ plt.axis('off')
+ plt.savefig('treemap.png', dpi=150, bbox_inches='tight')
+ pixmap = QPixmap('treemap.png')
+ parent.ui.label_treemap.setPixmap(pixmap)
+
+
+
+ iondict = pd.read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=0, index_col=None)
+
+ # Apply filters if required
+ if parent.analysis_paramsgui.relfil:
+ iondict = iondict[iondict['pass_relfil']]
+ if parent.analysis_paramsgui.decon:
+ iondict = iondict[iondict['pass_insource']]
+ if parent.analysis_paramsgui.blnkfltr:
+ iondict = iondict[iondict['pass_blnkfil']]
+ if parent.analysis_paramsgui.CVfil:
+ iondict = iondict[iondict['pass_cvfil']]
+
+ # Prepare data for upset plot
+ iongroups = iondict['groups'].tolist()
+ freq = {}
+ biolgroups = []
+ for item in iongroups:
+ if item not in freq:
+ freq[item] = 0
+ freq[item] += 1
+
+ header = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=None, index_col=[0, 1, 2]).iloc[0, :]
+ for elem in header:
+ if elem not in biolgroups:
+ biolgroups.append(elem)
+
+ sets = [' ' + elem for elem in list(freq.keys())]
+ size = list(freq.values())
+ setdf = pd.DataFrame({'groups': sets})
+ for elem in biolgroups: #have to do this if one group is a substring of another, add space
+ setdf[elem] = setdf['groups'].str.contains(' ' + elem)
+ setdf['size'] = size
+ setdf = setdf.iloc[:, 1:]
+ setdf = setdf.set_index(biolgroups)['size']
+
+ # Plot and display the upset plot
+ with plt.rc_context({"font.size": 8}):
+ upsetplt = upsetplot.plot(setdf, show_counts='%d', show_percentages=True, sort_categories_by=None)
+
+ figup = upsetplt['matrix'].figure
+ figup.set_size_inches(5, 4)
+ figup.set_facecolor((0, 0, 0, 0))
+ upsetplt['intersections'].set_facecolor((1, 1, 1, .25))
+ figup.savefig('test_upsetplt.png', dpi=150, bbox_inches='tight')
+ pixmap = QPixmap('test_upsetplt.png')
+ parent.ui.label_upset.setPixmap(pixmap)
+
+
+def gen_treemap(parent):
+ #generate treemap for visualization of filtering levels
+ #needed to refilter data and see how df row lengths change to avoid issues with one feature being in multiple filter lists
+ """
+ The gen_treemap function generates a treemap for visualizing filtering levels. The function reads a CSV file containing the
+ filtered data and another CSV file containing information about the ions. The function then filters the ion data based on
+ various filter options and calculates the number of ions filtered by each filter. Finally, the function generates a treemap
+ to display the number of ions that passed each filter and saves it as a PNG file. The treemap is then displayed in a QLabel in the GUI.
- def __init__(self, parent, currplt, frame, file, filtereddfs, groupsets):
- _detach_placeholder_widget(frame, parent.ui.label_upset)
- self.parent = parent
- self.currplt = currplt
-
- parent.fig[currplt] = Figure()
- parent.pltlayout[currplt] = QtWidgets.QVBoxLayout()
- parent.canvas[currplt] = FigureCanvas(parent.fig[currplt])
- parent.pltlayout[currplt].addWidget(parent.canvas[currplt])
- parent.toolbar[currplt] = NavigationToolbar(parent.canvas[currplt], parent)
- parent.toolbar[currplt].setStyleSheet("background-color:rgba(225,225,225,0);")
- parent.pltlayout[currplt].addWidget(parent.toolbar[currplt])
- frame.setLayout(parent.pltlayout[currplt])
-
- self.plotbackground = (.89, .89, .89, 0)
- self.plot(parent, file, filtereddfs, groupsets)
-
- def plot(self, parent, file, filtereddfs, groupsets):
- # upsetplot.plot() lays out fresh axes via its own gridspec on
- # whatever figure it's given -- clear the figure first so repeated
- # calls (regenerate/Apply) don't pile up axes on top of each other.
- parent.fig[self.currplt].clf()
-
- iondict = cached_read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=0, index_col=None)
- if parent.analysis_paramsgui.relfil:
- iondict = iondict[iondict['pass_relfil']]
- if parent.analysis_paramsgui.decon:
- iondict = iondict[iondict['pass_insource']]
- if parent.analysis_paramsgui.blnkfltr:
- iondict = iondict[iondict['pass_blnkfil']]
- if parent.analysis_paramsgui.CVfil:
- iondict = iondict[iondict['pass_cvfil']]
-
- iongroups = iondict['groups'].tolist()
- freq = {}
- for item in iongroups:
- freq[item] = freq.get(item, 0) + 1
-
- header = cached_read_csv(
- parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'),
- sep=',', header=None, index_col=[0, 1, 2]).iloc[0, :]
- biolgroups = []
- for elem in header:
- if elem not in biolgroups:
- biolgroups.append(elem)
-
- sets = [' ' + elem for elem in freq.keys()]
- setdf = pd.DataFrame({'groups': sets})
- for elem in biolgroups: # space-prefix handles one group name being a substring of another
- setdf[elem] = setdf['groups'].str.contains(' ' + elem)
- setdf['size'] = list(freq.values())
- setdf = setdf.iloc[:, 1:].set_index(biolgroups)['size']
-
- with plt.rc_context({"font.size": 8}):
- upsetplt = upsetplot.plot(setdf, fig=parent.fig[self.currplt], show_counts='%d', show_percentages=True, sort_categories_by=None)
-
- parent.fig[self.currplt].set_facecolor(self.plotbackground)
- upsetplt['intersections'].set_facecolor((1, 1, 1, .25))
- parent.canvas[self.currplt].draw()
+ Args:
+
+ parent: the parent widget where the treemap will be displayed
- def reset(self, file, filtereddfs, groupsets):
- self.plot(self.parent, file, filtereddfs, groupsets)
\ No newline at end of file
+ """
+ plt.clf()
+ msdata_filtered = pd.read_csv(parent.analysis_paramsgui.outputdir / (parent.analysis_paramsgui.filename.stem + '_filtered.csv'), sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
+ fltrcnt, color = {}, []
+ iondict = pd.read_csv(parent.analysis_paramsgui.outputdir / 'iondict.csv', sep=',', header=[0], index_col=[0])
+ total = len(iondict.index)
+ current = total
+
+ if parent.analysis_paramsgui.relfil:
+ filteredsetsize = len(iondict[iondict['pass_relfil']].index)
+ fltrcnt['Mispicked'] = current - filteredsetsize
+ current = filteredsetsize
+ color.append('#0000ff')
+
+ if parent.analysis_paramsgui.blnkfltr:
+ filteredsetsize = len(iondict[iondict['pass_blnkfil']].index)
+ fltrcnt['Blank'] = current - filteredsetsize
+ current = filteredsetsize
+ color.append('#00aaaa')
+
+ if parent.analysis_paramsgui.CVfil:
+ fltrcnt['Nonreproducible'] = len(parent.ionfilters['cv'].ions)
+ current = current - fltrcnt['Nonreproducible']
+ color.append('#ff0000')
+
+ if parent.analysis_paramsgui.decon:
+ fltrcnt['Insource'] = len(parent.ionfilters['insource'].ions)
+ color.append('#00aa00')
+
+ fltrcnt['High Quality'] = len(msdata_filtered.index)
+ color.append('#000000')
+
+ sizes = list(fltrcnt.values())
+ total_size = sum(fltrcnt.values())
+ labels = [f"{label}\n{size}\n{round(100*size/total_size,1)}%" for label, size in fltrcnt.items()]
+
+ squarify.plot(sizes=sizes, label=labels, color=color, alpha=0.3, text_kwargs={'fontsize': 10})
+ plt.axis('off')
+ plt.savefig('treemap.png', dpi=150, bbox_inches='tight')
+ pixmap = QPixmap('treemap.png')
+ parent.ui.label_treemap.setPixmap(pixmap)
\ No newline at end of file
diff --git a/code/pvclust.py b/code/pvclust.py
index 6943b83..dd3f47a 100644
--- a/code/pvclust.py
+++ b/code/pvclust.py
@@ -17,14 +17,7 @@
from scipy.stats import norm, chi2
from scipy.cluster.hierarchy import (dendrogram, set_link_color_palette,
- leaves_list, to_tree)
-# fastcluster.linkage is a drop-in for scipy's linkage that produces identical
-# results much faster -- a big win here because bootstrap clustering calls it
-# thousands of times. Fall back to scipy when fastcluster isn't installed.
-try:
- from fastcluster import linkage
-except ImportError:
- from scipy.cluster.hierarchy import linkage
+ leaves_list, to_tree, linkage)
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
@@ -187,11 +180,10 @@ def _result(self):
columns=['AU', 'BP', 'SE.AU', 'SE.BP', 'pchi', 'v', 'c'])
return result
- def plot(self, ax, labels=None, link_color_func=None): #added axis input
+ def plot(self, ax, labels=None): #added axis input
"""Plot dendrogram with AU BP values for each node"""
plot_dendrogram(self.linkage_matrix,
- np.array(self.result[['AU', 'BP']]), ax, labels,
- link_color_func)
+ np.array(self.result[['AU', 'BP']]), ax, labels)
def seplot(self, pvalue='AU', annotate=False):
"""p-values vs Standard error plot"""
@@ -272,7 +264,7 @@ def find_clusters(self):
return clusters
-def plot_dendrogram(linkage_matrix, pvalues, axis, labels=None, link_color_func=None): #added axis input
+def plot_dendrogram(linkage_matrix, pvalues, axis, labels=None): #added axis input
""" Plot dendrogram with AU BP values for each node"""
d = dendrogram(linkage_matrix, no_plot=True)
xcoord = d["icoord"]
@@ -281,57 +273,34 @@ def plot_dendrogram(linkage_matrix, pvalues, axis, labels=None, link_color_func=
x = {i: (j[1]+j[2])/2 for i, j in enumerate(xcoord)}
y = {i: j[1] for i, j in enumerate(ycoord)}
pos = node_positions(y, x)
+
+ plt.figure(figsize=(12, 8))
+ plt.tight_layout()
set_link_color_palette(['c', 'g'])
- # link_color_func, when given, takes priority over color_threshold/
- # above_threshold_color (scipy's own precedence rule) -- that's how the
- # dendrogram tab's purity coloring (clusterpurity.py) reaches the
- # bootstrap dendrogram too.
d = dendrogram(linkage_matrix, labels=labels, above_threshold_color='black',
- color_threshold=0, leaf_rotation=90, ax=axis,
- link_color_func=link_color_func)
+ color_threshold=0, leaf_rotation=90, ax = axis)
maxval = max(y.values())
ax = axis
-
- # AU/BP labels used to be positioned with a fixed x-shift in icoord
- # units (e.g. "x-7"). icoord spacing is always 10 units per leaf
- # regardless of leaf count, but the AXES' actual pixel width is not --
- # with more leaves squeezed into the same plot width, each icoord unit
- # maps to fewer pixels, so a fixed icoord offset shrinks to a fixed
- # *fraction* of leaf spacing but an ever-shrinking number of *pixels*,
- # eventually overlapping (e.g. "AU"/"BP" merging into "AUBP" once there
- # are enough leaves). Anchoring with ha='right'/'left' plus a constant
- # offset in POINTS (not data units) keeps a fixed pixel gap regardless
- # of leaf count or icoord scale -- no more digit-width-dependent x-shift
- # hack for AU values of 100 vs not. Per-node fontsize is similarly
- # scaled down as leaf count grows, so neighbouring nodes' labels (which
- # do have a fixed minimum icoord-and-therefore-pixel separation) don't
- # run into each other either.
- n_leaves = len(d['ivl'])
- value_fontsize = max(5, min(8, 140 / n_leaves))
- header_fontsize = value_fontsize + 3
- gap_points = 2
-
- for node, (nx, ny) in pos.items(): #modifications added to scale y axis label shifts
- y_offset = ny + maxval / 200
+ for node, (x, y) in pos.items(): #modifications added to scale y axis label shifts
if node == (len(pos.items())-1):
- ax.annotate('AU', xy=(nx, y_offset), xytext=(-gap_points, 0),
- textcoords='offset points', ha='right', va='bottom',
- fontsize=header_fontsize, fontweight='bold', color='purple')
- ax.annotate('BP', xy=(nx, y_offset), xytext=(gap_points, 0),
- textcoords='offset points', ha='left', va='bottom',
- fontsize=header_fontsize, fontweight='bold', color='black')
+ ax.text(x-6, y+maxval/200, 'AU', fontsize=11, fontweight='bold',
+ color='purple')
+ ax.text(x+1, y+maxval/200, 'BP', fontsize=11, fontweight='bold',
+ color='black')
else:
- au_significant = pvalues[node][0] * 100 == 100
- ax.annotate(f'{pvalues[node][0]*100:.0f}', xy=(nx, y_offset), xytext=(-gap_points, 0),
- textcoords='offset points', ha='right', va='bottom',
- fontsize=value_fontsize, color='purple',
- fontweight='bold' if au_significant else 'normal')
- ax.annotate(f'{pvalues[node][1]*100:.0f}', xy=(nx, y_offset), xytext=(gap_points, 0),
- textcoords='offset points', ha='left', va='bottom',
- fontsize=value_fontsize, color='black',
- fontweight='bold' if au_significant else 'normal')
+ if pvalues[node][0]*100 == 100:
+ ax.text(x-10, y+maxval/200, f' {pvalues[node][0]*100:.0f}', fontsize=8,
+ color='purple', fontweight='bold')
+ ax.text(x+1, y+maxval/200, f'{pvalues[node][1]*100:.0f}', fontsize=8,
+ color='black', fontweight='bold')
+ else:
+ ax.text(x-7, y+maxval/200, f' {pvalues[node][0]*100:.0f}', fontsize=8,
+ color='purple')
+ ax.text(x+1, y+maxval/200, f'{pvalues[node][1]*100:.0f}', fontsize=8,
+ color='black')
+# plt.savefig('dendrogram.pdf')
def node_positions(x, y):
diff --git a/code/stats.py b/code/stats.py
index 8dd6ee3..07bca9c 100644
--- a/code/stats.py
+++ b/code/stats.py
@@ -1,7 +1,6 @@
"""
MPACT
Copyright 2022, Robert M. Samples, Sara P. Puckett, and Marcy J. Balunas
-Modifications Copyright 2026, Robert M. Samples
"""
import pandas as pd
@@ -65,19 +64,15 @@ def groupave(analysis_params):
print('Averaging groups')
# Calculate total number of rows and set chunk size
- formatted_path = analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv')
- # Use a context manager so the file handle is closed promptly (the bare
- # ``sum(1 for _ in open(...))`` left the handle open until GC -- a
- # ResourceWarning that surfaced in the test suite).
- with open(formatted_path) as row_counter:
- total_rows = sum(1 for _ in row_counter) - 1
- header = pd.read_csv(formatted_path, nrows=0, header=[0, 1, 2])
+ total_rows = sum(1 for _ in open(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'))) - 1
+ header = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'), nrows=0, header=[0, 1, 2])
total_columns = header.shape[1]
cells_per_chunk = 100_000
chunk_size = max(1, cells_per_chunk // total_columns) # Rows per chunk
# Initialize lists to collect results from each chunk
sum_values_list = []
+ sum_squares_list = []
counts_list = []
# Process data in chunks
@@ -95,29 +90,33 @@ def groupave(analysis_params):
# Set index names according to your data structure
chunk_stacked.index.names = ['Compound', 'm/z', 'Retention time', 'Group', 'Sample', 'Injection']
- # Compute sum and counts per group
+ # Compute sum, sum of squares, and counts per group
group_levels = ['Compound', 'm/z', 'Retention time', 'Group', 'Sample', 'Injection']
sum_values_chunk = chunk_stacked.groupby(level=group_levels).sum()
+ sum_squares_chunk = (chunk_stacked ** 2).groupby(level=group_levels).sum()
count_chunk = chunk_stacked.groupby(level=group_levels).count()
# Append results to lists
sum_values_list.append(sum_values_chunk)
+ sum_squares_list.append(sum_squares_chunk)
counts_list.append(count_chunk)
pbar.update(1)
# Concatenate all results
all_sum_values = pd.concat(sum_values_list)
+ all_sum_squares = pd.concat(sum_squares_list)
all_counts = pd.concat(counts_list)
# Aggregate over the entire dataset
sum_values_df = all_sum_values.groupby(level=group_levels).sum()
+ sum_squares_df = all_sum_squares.groupby(level=group_levels).sum()
counts_df = all_counts.groupby(level=group_levels).sum()
- # Calculate mean per injection. (A per-injection variance/stddev was
- # computed here previously but never used -- the technical/biological
- # RSDs below are derived from the grouped means, not from it.)
+ # Calculate mean and variance per injection
mean_values = sum_values_df / counts_df
+ variance_values = (sum_squares_df / counts_df) - (mean_values ** 2)
+ stddev_values = variance_values ** 0.5
# Calculate technical RSDs and counts
# Group over technical replicates within each sample
@@ -212,10 +211,8 @@ def runfc(analysis_params, statstgrps):
maxvals = msdata_errprop.max(axis=1) #the max stuff is used to base point opacity based on abundance, have to put in a better location than this
msdata_errprop = msdata_errprop.loc[:, msdata_errprop.columns.intersection(statstgrps)]
msdata_errprop['FC']=msdata_errprop[statstgrps[0]]/msdata_errprop[statstgrps[1]]
- # Use .loc (single-step assignment) instead of chained assignment, which is
- # deprecated and will stop updating the frame in pandas 3.0.
- msdata_errprop.loc[msdata_errprop['FC'] >= maxval, 'FC'] = maxval
- msdata_errprop.loc[msdata_errprop['FC'] <= minval, 'FC'] = minval
+ msdata_errprop['FC'][msdata_errprop['FC'] >= maxval] = maxval
+ msdata_errprop['FC'][msdata_errprop['FC'] <= minval] = minval
msdata_errprop['max'] = maxvals # this has to be done before resetting the index or else tuple/string expectation error thrown
msdata_errprop = msdata_errprop.reset_index([1,2])
iondict['fc'] = msdata_errprop['FC']
@@ -249,17 +246,12 @@ def runttest(analysis_params, statstgrps, groupsets):
msdata_teststats['T'] = tstat(msdata_teststats[('average', statstgrps[0])], msdata_teststats[('combASD', statstgrps[0])], msdata_teststats[('neff', statstgrps[0])], msdata_teststats[('average', statstgrps[1])], msdata_teststats[('combASD', statstgrps[1])], msdata_teststats[('neff', statstgrps[1])])
msdata_teststats['deg'] = msdata_teststats[('neff', statstgrps[0])] + msdata_teststats[('neff', statstgrps[1])] - 2
msdata_teststats['p'] = (1 - stats.t.cdf(msdata_teststats['T'], msdata_teststats['deg'])) * 2
- msdata_teststats.loc[msdata_teststats['p'] <= minval, 'p'] = minval
+ msdata_teststats['p'][msdata_teststats['p'] <= minval] = minval
msdata_teststats['logp'] = np.log10(msdata_teststats['p'])
- # Save msdata_teststats. Previously written to the current working
- # directory as 'msdata_teststats_test.csv' (a debug-named file that
- # littered code/ and was never read back); now written into the run's
- # output directory under a descriptive name alongside the other outputs.
+ # Save msdata_teststats
msdata_teststats = msdata_teststats.reset_index([1, 2])
- msdata_teststats.to_csv(
- analysis_params.outputdir / (analysis_params.filename.stem + '_teststats.csv'),
- header=True, index=True)
+ msdata_teststats.to_csv('msdata_teststats_test.csv', header=True, index=True)
# Update iondict with -logp
iondict['-logp'] = -msdata_teststats['logp']
@@ -307,12 +299,7 @@ def runttest(analysis_params, statstgrps, groupsets):
# Save results to CSV files
iondict = iondict.set_index('Compound')
- # Written into the run's output directory rather than the current working
- # directory (was a bare 'qdata.csv' that landed in code/ and was never
- # read back); the canonical -logq still goes into iondict.csv below.
- iondict.to_csv(
- analysis_params.outputdir / (analysis_params.filename.stem + '_qvalues.csv'),
- index=True, header=True)
+ iondict.to_csv('qdata.csv', index=True, header=True)
iondict2 = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=[0])
iondict2['-logq'] = np.nan
iondict2.loc[iondict.index.tolist(), '-logq'] = iondict['-logq']
diff --git a/code/ui_functions.py b/code/ui_functions.py
index 014da24..420ae5b 100644
--- a/code/ui_functions.py
+++ b/code/ui_functions.py
@@ -4,24 +4,31 @@
"""
## ==> GUI FILE
-from main import MainWindow, start_functime, stop_functime, reset_runtime
-import webbrowser # used by masst() to open the GNPS single-spectrum search
+from main import MainWindow, query, start_functime, stop_functime, reset_runtime, ftrdialog, dialog
+#import masstdriver #from old version of masst search push
+import webbrowser #may not be needed now
from mzmineimport import format_check
-from paramfields import restore_checkbox_fields
+import sys
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
+import time
-from PyQt5 import QtCore
-from PyQt5.QtWidgets import QSizeGrip, QGraphicsDropShadowEffect, QFileDialog, QListWidgetItem, QColorDialog
-from PyQt5.QtGui import QColor
+import platform
+from PyQt5 import QtCore, QtWidgets
+from PyQt5.QtWidgets import QMainWindow, QSizeGrip, QGraphicsDropShadowEffect, QFileDialog, QListWidgetItem, QColorDialog
+from PyQt5.QtCore import (QCoreApplication, QPropertyAnimation, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent)
+from PyQt5.QtGui import QBrush, QColor, QIcon, QPalette, QPainter, QPixmap
from pathlib import Path
-# Imported for its side effect only (registers the Qt resource blobs used by
-# the stylesheets/icons); do not remove even though it looks unused.
+# IMPORT FUNCTIONS AND RESOURCES
import files
+from MSFaST import analysis_parameters
+
+import os
+
@@ -29,48 +36,6 @@
GLOBAL_STATE = 0
-# Tab-switch tables. Each nav button maps to the stacked-widget page(s) it
-# selects (plus, for plot tabs, any dialog-frame show/hide deltas to apply
-# after the bar reset). goto_maintab()/goto_plottab() are the single
-# data-driven dispatchers that replace the ~15 near-identical goto_* methods;
-# the buttons are wired to them by key in uiDefinitions(). Module-level (not
-# self/class attributes) because the dispatchers run with a MainWindow `self`,
-# not a UIFunctions instance.
-#
-# _MAINBAR_TABS: key -> (stackedWidget index, active-button attr on self.ui)
-_MAINBAR_TABS = {
- 'import': (0, 'btn_import'),
- 'filter': (1, 'btn_filter'),
- 'params': (2, 'btn_parameters'),
- 'plot': (3, 'btn_plots'),
- 'info': (4, 'btn_info'),
- 'search': (5, 'btn_search'),
-}
-# _PLOTBAR_TABS: key -> (infobar index, plot index, active-button attr,
-# [(action, dialog.ui widget attr), ...] applied after reset)
-_PLOTBAR_TABS = {
- 'review': (0, 1, 'btn_review', []),
- 'upset': (1, 9, 'btn_upset', []),
- 'dend': (1, 2, 'btn_dend', []),
- 'pca': (1, 3, 'btn_pca', [('show', 'frame_2')]),
- 'mzrt': (0, 4, 'btn_mzrt', []),
- 'kmd': (0, 5, 'btn_kmd', []),
- '3dfc': (0, 6, 'btn_3dfc', []),
- 'volcano': (0, 7, 'btn_volcano', []),
- 'heatmap': (0, 8, 'btn_heatmap', []),
-}
-
-# Nav-button stylesheets. Defined once here instead of being rebuilt on
-# every reset_*bar() call (and read back off self.ui, where they were
-# only ever used internally). The plot tab bar and the feature-info dialog
-# bar shared a visually identical light style (the two former copies
-# differed only by insignificant CSS whitespace), so they now share one
-# pair. The left main-nav bar has its own (dark/transparent) theme.
-_MAINBAR_ACTIVE_STYLE = 'QPushButton {\tborder: none; background-color: transparent;}QPushButton:hover {background-color: transparent}QPushButton:pressed {\tbackground-color: rgb(75, 75, 75);}'
-_MAINBAR_INACTIVE_STYLE = 'QPushButton {\tborder: none; background-color: rgb(35, 35, 35);}QPushButton:hover {background-color: transparent}QPushButton:pressed {\tbackground-color: rgb(75, 75, 75);}'
-_LIGHT_ACTIVE_STYLE = 'QPushButton {\tborder: none;background-color: rgba(225,225,225, 255);\tcolor: rgba(75,75,75,255)} QPushButton:hover {background-color: rgba(225,225,225, 255);\tcolor: rgba(75,75,75,255)} QPushButton:pressed {\t background-color: rgba(225,225,225, 255);\tcolor: rgba(75,75,75,255)}'
-_LIGHT_INACTIVE_STYLE = 'QPushButton {\tborder: none;background-color: rgba(0,0,0, 0)} QPushButton:hover {background-color: rgba(225,225,225, 50)} QPushButton:pressed {\t background-color: rgba(225,225,225, 255);\tcolor: rgba(75,75,75,255)}'
-
class UIFunctions(MainWindow):
## ==> MAXIMIZE RESTORE FUNCTION
@@ -117,25 +82,7 @@ def uiDefinitions(self):
self.ui.frame_plts.hide()
self.ui.checkBox_fc.hide()
self.ui.checkBox_ttest.hide()
- # The per-feature-set "Use" checkbox (and its label) next to the colour
- # picker is inert -- nothing in the hand-written code ever connects or
- # reads checkBox_use1, so it does nothing. Hide both at runtime rather
- # than editing the generated ui_main.py.
- self.ui.checkBox_use1.hide()
- self.ui.lbl_use.hide()
- # "Bootstrap Analysis" and "Collapse Technical Replicates" moved
- # from this global plot-config dialog onto their one relevant
- # plot's own switcher bar (plot_dendrogram's "Bootstrap" checkbox,
- # plot_ordination's "Collapse Replicates" checkbox) -- hide the
- # now-orphaned dialog widgets rather than editing the generated
- # ui_plotparam.py.
- self.dialog.ui.frame_bootstrap.hide()
- self.dialog.ui.frame_2.hide()
- # "Apply Data Filtering" is inert (its checked state is never read and
- # it has no signal connection), so hide it permanently rather than
- # leaving a no-op control on the config dialog. Hidden once here; the
- # per-tab show() that used to reveal it in reset_plotbar() is removed.
- self.dialog.ui.checkBox_applyfilter.hide()
+ self.dialog.ui.checkBox_bootstrap.setChecked(True)
# Top bar functions
self.ui.btn_maximize.clicked.connect(lambda: UIFunctions.maximize_restore(self))
@@ -144,20 +91,24 @@ def uiDefinitions(self):
#mainbar functions
self.ui.stackedWidget.setCurrentIndex(6)
- # Simple tab buttons go through the table-driven dispatcher (keyed by
- # _MAINBAR_TABS); 'search' additionally kicks off the db search, so it
- # keeps its own handler. (*_a absorbs the clicked(bool) arg; k=key binds
- # per-iteration so the closure doesn't capture the final loop value.)
- for key in ('import', 'filter', 'params', 'plot', 'info'):
- getattr(self.ui, _MAINBAR_TABS[key][1]).clicked.connect(
- lambda *_a, k=key: UIFunctions.goto_maintab(self, k))
+ self.ui.btn_import.clicked.connect(lambda: UIFunctions.goto_import(self))
+ self.ui.btn_filter.clicked.connect(lambda: UIFunctions.goto_filter(self))
+ self.ui.btn_parameters.clicked.connect(lambda: UIFunctions.goto_params(self))
+ self.ui.btn_plots.clicked.connect(lambda: UIFunctions.goto_plot(self))
+ self.ui.btn_info.clicked.connect(lambda: UIFunctions.goto_info(self))
self.ui.btn_search.clicked.connect(lambda: UIFunctions.goto_search(self))
#plotbar functions
self.ui.stackedWidget_plot.setCurrentIndex(0)
- for key in _PLOTBAR_TABS:
- getattr(self.ui, _PLOTBAR_TABS[key][2]).clicked.connect(
- lambda *_a, k=key: UIFunctions.goto_plottab(self, k))
+ self.ui.btn_review.clicked.connect(lambda: UIFunctions.goto_review(self))
+ self.ui.btn_upset.clicked.connect(lambda: UIFunctions.goto_upset(self))
+ self.ui.btn_dend.clicked.connect(lambda: UIFunctions.goto_dend(self))
+ self.ui.btn_pca.clicked.connect(lambda: UIFunctions.goto_pca(self))
+ self.ui.btn_mzrt.clicked.connect(lambda: UIFunctions.goto_mzrt(self))
+ self.ui.btn_kmd.clicked.connect(lambda: UIFunctions.goto_kmd(self))
+ self.ui.btn_3dfc.clicked.connect(lambda: UIFunctions.goto_3dfc(self))
+ self.ui.btn_volcano.clicked.connect(lambda: UIFunctions.goto_volcano(self))
+ self.ui.btn_heatmap.clicked.connect(lambda: UIFunctions.goto_heatmap(self))
self.ui.stackedWidget_review.setCurrentIndex(3)
self.ui.btn_ftrplt.clicked.connect(lambda: self.ui.stackedWidget_review.setCurrentIndex(0))
@@ -165,8 +116,8 @@ def uiDefinitions(self):
self.ui.btn_cvplt.clicked.connect(lambda: self.ui.stackedWidget_review.setCurrentIndex(2))
self.ui.btn_datasummary.clicked.connect(lambda: self.ui.stackedWidget_review.setCurrentIndex(3))
- self.ui.btn_upsetplt.clicked.connect(lambda: UIFunctions.switch_grpanalysis_tab(self, 0))
- self.ui.btn_samplecorr.clicked.connect(lambda: UIFunctions.switch_grpanalysis_tab(self, 1))
+ self.ui.btn_upsetplt.clicked.connect(lambda: self.ui.stackedWidget_grpanalysis.setCurrentIndex(0))
+ self.ui.btn_samplecorr.clicked.connect(lambda: self.ui.stackedWidget_grpanalysis.setCurrentIndex(1))
#feature info bar functions
self.ftrdialog.ui.btn_close.clicked.connect(lambda: self.ftrdialog.hide())
@@ -205,7 +156,7 @@ def uiDefinitions(self):
self.ftrdialog.setWindowFlag(QtCore.Qt.FramelessWindowHint)
self.ftrdialog.setWindowFlag(QtCore.Qt.WindowStaysOnTopHint)
self.ftrdialog.ui.treeWidget.hideColumn(5)
- self.searchtree.view.hideColumn(5) #hide sets column for now
+ self.ui.treeWidget.hideColumn(5) #hide sets column for now
self.ftrdialog.hide()
self.ftrdialog.ui.btn_related.hide()
@@ -222,19 +173,35 @@ def returnStatus():
#ui buttons
- def goto_maintab(self, key):
- """Switch the main left-nav stacked widget to the page for ``key`` and
- highlight its button. Data-driven via ``_MAINBAR_TABS``; replaces the
- former one-method-per-tab goto_import/filter/params/plot/info."""
- index, button_attr = _MAINBAR_TABS[key]
- self.ui.stackedWidget.setCurrentIndex(index)
+ def goto_import(self):
+ self.ui.stackedWidget.setCurrentIndex(0)
+ UIFunctions.reset_mainbar(self)
+ self.ui.btn_import.setStyleSheet(self.ui.mainbar_activebtn)
+
+ def goto_filter(self):
+ self.ui.stackedWidget.setCurrentIndex(1)
+ UIFunctions.reset_mainbar(self)
+ self.ui.btn_filter.setStyleSheet(self.ui.mainbar_activebtn)
+
+ def goto_params(self):
+ self.ui.stackedWidget.setCurrentIndex(2)
UIFunctions.reset_mainbar(self)
- getattr(self.ui, button_attr).setStyleSheet(_MAINBAR_ACTIVE_STYLE)
+ self.ui.btn_parameters.setStyleSheet(self.ui.mainbar_activebtn)
+ def goto_plot(self):
+ self.ui.stackedWidget.setCurrentIndex(3)
+ UIFunctions.reset_mainbar(self)
+ self.ui.btn_plots.setStyleSheet(self.ui.mainbar_activebtn)
+
+ def goto_info(self):
+ self.ui.stackedWidget.setCurrentIndex(4)
+ UIFunctions.reset_mainbar(self)
+ self.ui.btn_info.setStyleSheet(self.ui.mainbar_activebtn)
+
def goto_search(self):
- """Main-nav 'Search' tab: switch like any other main tab, then run the
- one-time NPAtlas db search + feature-tree fill once an analysis exists."""
- UIFunctions.goto_maintab(self, 'search')
+ self.ui.stackedWidget.setCurrentIndex(5)
+ UIFunctions.reset_mainbar(self)
+ self.ui.btn_search.setStyleSheet(self.ui.mainbar_activebtn)
#self.ftrdialog.show()
if self.dbsearchdone == False and self.analysisrun:
start_functime()
@@ -243,58 +210,96 @@ def goto_search(self):
self.dbsearchdone = True
stop_functime('dbsearch complete')
reset_runtime()
- elif not self.analysisrun:
- self.error('Run an analysis before searching.')
-
- def switch_grpanalysis_tab(self, idx):
- """Switch the Group Analysis sub-tab (UpSet Plot=0, Sample
- Correlations=1) and grey out plot_samplecorr's Method/View/Use-Names
- controls -- shared with btn_upsetplt/btn_samplecorr in frame_12 --
- whenever the UpSet Plot tab is active, since they don't apply there."""
- self.ui.stackedWidget_grpanalysis.setCurrentIndex(idx)
- if getattr(self, 'samplecorr', None) is not None:
- self.samplecorr.set_controls_enabled(idx == 1)
-
+
#plotbar functions
- def goto_plottab(self, key):
- """Switch the plots area (infobar + plot stacked widgets) to the page
- for ``key``, highlight its button, and apply that tab's dialog-frame
- show/hide deltas. Data-driven via ``_PLOTBAR_TABS``; replaces the former
- one-method-per-tab goto_review/upset/dend/pca/mzrt/kmd/3dfc/volcano/
- heatmap. Order matches the originals: set pages -> reset bar (which
- hides every per-tab frame) -> mark the active button -> apply this
- tab's frame deltas on top."""
- infobar_index, plot_index, button_attr, frame_ops = _PLOTBAR_TABS[key]
- self.ui.stackedWidget_infobar.setCurrentIndex(infobar_index)
- self.ui.stackedWidget_plot.setCurrentIndex(plot_index)
+ def goto_review(self):
+ self.ui.stackedWidget_infobar.setCurrentIndex(0)
+ self.ui.stackedWidget_plot.setCurrentIndex(1)
+ UIFunctions.reset_plotbar(self)
+ self.ui.btn_review.setStyleSheet(self.ui.plotbar_activebtn)
+
+ self.dialog.ui.checkBox_applyfilter.hide()
+
+ def goto_upset(self):
+ self.ui.stackedWidget_infobar.setCurrentIndex(1)
+ self.ui.stackedWidget_plot.setCurrentIndex(9)
+ UIFunctions.reset_plotbar(self)
+ self.ui.btn_upset.setStyleSheet(self.ui.plotbar_activebtn)
+
+ self.dialog.ui.checkBox_applyfilter.hide()
+ self.dialog.ui.frame_colorscheme.show()
+
+ def goto_dend(self):
+ self.ui.stackedWidget_infobar.setCurrentIndex(1)
+ self.ui.stackedWidget_plot.setCurrentIndex(2)
+ UIFunctions.reset_plotbar(self)
+ self.ui.btn_dend.setStyleSheet(self.ui.plotbar_activebtn)
+
+ def goto_pca(self):
+ self.ui.stackedWidget_infobar.setCurrentIndex(1)
+ self.ui.stackedWidget_plot.setCurrentIndex(3)
UIFunctions.reset_plotbar(self)
- getattr(self.ui, button_attr).setStyleSheet(_LIGHT_ACTIVE_STYLE)
- for action, widget_attr in frame_ops:
- getattr(getattr(self.dialog.ui, widget_attr), action)()
+ self.ui.btn_pca.setStyleSheet(self.ui.plotbar_activebtn)
+
+ self.dialog.ui.frame_2.show()
+ def goto_mzrt(self):
+ self.ui.stackedWidget_infobar.setCurrentIndex(0)
+ self.ui.stackedWidget_plot.setCurrentIndex(4)
+ UIFunctions.reset_plotbar(self)
+ self.ui.btn_mzrt.setStyleSheet(self.ui.plotbar_activebtn)
+
+ def goto_kmd(self):
+ self.ui.stackedWidget_infobar.setCurrentIndex(0)
+ self.ui.stackedWidget_plot.setCurrentIndex(5)
+ UIFunctions.reset_plotbar(self)
+ self.ui.btn_kmd.setStyleSheet(self.ui.plotbar_activebtn)
+
+ self.dialog.ui.frame_mdguide.show()
+
+ def goto_3dfc(self):
+ self.ui.stackedWidget_infobar.setCurrentIndex(0)
+ self.ui.stackedWidget_plot.setCurrentIndex(6)
+ UIFunctions.reset_plotbar(self)
+ self.ui.btn_3dfc.setStyleSheet(self.ui.plotbar_activebtn)
+
+ def goto_volcano(self):
+ self.ui.stackedWidget_infobar.setCurrentIndex(0)
+ self.ui.stackedWidget_plot.setCurrentIndex(7)
+ UIFunctions.reset_plotbar(self)
+ self.ui.btn_volcano.setStyleSheet(self.ui.plotbar_activebtn)
+
+ self.dialog.ui.frame_volcanoparams.show()
+
+ def goto_heatmap(self):
+ self.ui.stackedWidget_infobar.setCurrentIndex(0)
+ self.ui.stackedWidget_plot.setCurrentIndex(8)
+ UIFunctions.reset_plotbar(self)
+ self.ui.btn_heatmap.setStyleSheet(self.ui.plotbar_activebtn)
+
+ self.dialog.ui.frame_colorscheme.show()
+
#ftinfobar functions
def goto_abund(self):
self.ftrdialog.ui.btn_masst.hide()
self.ftrdialog.ui.stackedWidget.setCurrentIndex(2)
- # Refresh (not re-select/toggle) the current feature's display now
- # that the abundance tab is active.
- self._refresh_highlight()
+ self.highlight_feature(self.pickedfeature)
UIFunctions.reset_ftrdialogbar(self)
- self.ftrdialog.ui.btn_abund.setStyleSheet(_LIGHT_ACTIVE_STYLE)
-
+ self.ftrdialog.ui.btn_abund.setStyleSheet(self.ui.ftbar_activebtn)
+
def goto_hits(self):
self.ftrdialog.ui.btn_masst.hide()
self.ftrdialog.ui.stackedWidget.setCurrentIndex(0)
-
- self._refresh_highlight()
+
+ self.highlight_feature(self.pickedfeature)
UIFunctions.reset_ftrdialogbar(self)
- self.ftrdialog.ui.btn_hits.setStyleSheet(_LIGHT_ACTIVE_STYLE)
+ self.ftrdialog.ui.btn_hits.setStyleSheet(self.ui.ftbar_activebtn)
def goto_spectrum(self):
self.ftrdialog.ui.btn_masst.show()
self.ftrdialog.ui.stackedWidget.setCurrentIndex(1)
UIFunctions.reset_ftrdialogbar(self)
- self.ftrdialog.ui.btn_spectrum.setStyleSheet(_LIGHT_ACTIVE_STYLE)
+ self.ftrdialog.ui.btn_spectrum.setStyleSheet(self.ui.ftbar_activebtn)
def masst(self):
"""
@@ -325,228 +330,171 @@ def masst(self):
#colour buttons
def colour_picker1(self):
"""
- Allows user to pick a color from color dialog and sets the selected
- groupset's colour attribute.
+ Allows user to pick a color from color dialog and sets the selected color to the selected query set's color attribute.
+
"""
color = QColorDialog.getColor()
- self.groupsetmodel.update(self.groupsetmodel.selected_index, colour=color.name())
- self.ui.btn_col1.setStyleSheet("QPushButton {border: 2px solid lightgrey; background-color: " + str(self.groupsetmodel.selected.colour) +";}")
-
+ self.querys[self.selset].colour = color.name()
+ self.ui.btn_col1.setStyleSheet("QPushButton {border: 2px solid lightgrey; background-color: " + str(self.querys[self.selset].colour) +";}")
+
def updatesets(self):
"""
- Rebuilds the groupset list widget from the model and restores selection.
+ Updates the list of query sets in the GUI and sets the selected query set.
+
"""
- list_widget = self.ui.listWidget_pltgrps
-
- # Block signals while rebuilding: clear()/addItem()/setCurrentRow()
- # below all fire currentItemChanged, which is wired to writegroups()
- # (ui_functions.py:148) -- a GUI-to-model sync that would otherwise
- # run mid-rebuild, before the drag-list boxes are refreshed for the
- # new selection, and clobber the model with stale leftover box
- # contents from whatever groupset was selected a moment earlier.
- list_widget.blockSignals(True)
- list_widget.clear()
- for groupset in self.groupsetmodel:
- item = QListWidgetItem(groupset.name)
+ selitem = self.ui.listWidget_pltgrps.currentRow() - 1
+ selitem = max(selitem, 0)
+
+ self.ui.listWidget_pltgrps.clear()
+ for query in self.querys:
+ item = QListWidgetItem(query.name)
item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
- list_widget.addItem(item)
-
- # Trust the model's own selected_index (already correctly maintained
- # by add()/remove()/from_legacy_list()) rather than re-deriving a
- # guess from the widget's currentRow() before it's cleared above --
- # that previously read the stale pre-rebuild row and shifted it by
- # one, so live selection drifted toward row 0 on every remove/load.
- list_widget.setCurrentRow(self.groupsetmodel.selected_index)
- list_widget.blockSignals(False)
-
+ self.ui.listWidget_pltgrps.addItem(item)
+
+ self.ui.listWidget_pltgrps.setCurrentRow(selitem)
UIFunctions.updategroups(self)
-
-
+
+
def updategroups(self):
"""
- Syncs the three group-membership lists (and colour swatch) in the GUI
- to the currently-selected groupset in the model.
+ Updates the lists of groups for the selected query set in the GUI.
"""
- # select() also sets the model's selected_index (side effect we rely on);
- # its return value is unused here.
- self.groupsetmodel.select(self.ui.listWidget_pltgrps.currentRow())
-
+ selgroup = self.ui.listWidget_pltgrps.currentRow()
+ self.selset = selgroup
+
self.ui.listWidget_allgrps.clear()
self.ui.listWidget_orgrps.clear()
self.ui.listWidget_andgrps.clear()
-
- groupset = self.groupsetmodel.selected
- if groupset is None:
- return
-
- for group in groupset.excl:
+
+ for group in self.querys[selgroup].excl:
self.ui.listWidget_allgrps.addItem(QListWidgetItem(group))
- for group in groupset.src:
+ for group in self.querys[selgroup].src:
self.ui.listWidget_orgrps.addItem(QListWidgetItem(group))
- for group in groupset.incl:
+ for group in self.querys[selgroup].incl:
self.ui.listWidget_andgrps.addItem(QListWidgetItem(group))
-
+
self.ui.btn_col1.setStyleSheet(
- "QPushButton {border: 2px solid lightgrey; background-color: " +
- str(groupset.colour) +";}"
+ "QPushButton {border: 2px solid lightgrey; background-color: " +
+ str(self.querys[self.selset].colour) +";}"
)
-
+
def writegroups(self):
"""
- Writes the GUI's groupset name/included/excluded/source-group widgets
- back into the model for the currently-selected groupset.
+ Writes the changes made to the query set's name, included groups, excluded groups, and source groups in the GUI to the query object.
"""
- selset = self.groupsetmodel.selected_index
- if 0 <= selset < self.ui.listWidget_pltgrps.count():
+ if 0 <= self.selset < self.ui.listWidget_pltgrps.count():
try:
- name = self.ui.listWidget_pltgrps.item(selset).text()
+ self.querys[self.selset].name = self.ui.listWidget_pltgrps.item(self.selset).text()
except Exception:
- name = None
-
- self.groupsetmodel.update(
- selset,
- name=name,
- excl=[self.ui.listWidget_allgrps.item(x).text() for x in range(self.ui.listWidget_allgrps.count())],
- src=[self.ui.listWidget_orgrps.item(x).text() for x in range(self.ui.listWidget_orgrps.count())],
- incl=[self.ui.listWidget_andgrps.item(x).text() for x in range(self.ui.listWidget_andgrps.count())],
- )
-
+ pass
+
+ self.querys[self.selset].excl = [self.ui.listWidget_allgrps.item(x).text() for x in range(self.ui.listWidget_allgrps.count())]
+ self.querys[self.selset].src = [self.ui.listWidget_orgrps.item(x).text() for x in range(self.ui.listWidget_orgrps.count())]
+ self.querys[self.selset].incl = [self.ui.listWidget_andgrps.item(x).text() for x in range(self.ui.listWidget_andgrps.count())]
+
UIFunctions.updategroups(self)
-
-
+
+
def addgroup(self, name = 'New Feature Set'):
"""
- Adds a new groupset (excluding every known biological group by
- default) to the model and the GUI list.
+ Adds a new query set to the list of query sets in the GUI and to the querys list.
"""
item = QListWidgetItem(name)
item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
+
+ self.ui.listWidget_pltgrps.addItem(item)
+ item.setSelected(True)
+
+ currquery = query()
+ currquery.name = item.text()
+ currquery.src = []
+ currquery.incl = []
+ currquery.excl = []
+ currquery.color = '#000000'
+
+ for group in self.groups:
+ currquery.excl.append(group)
+
+ self.querys.append(currquery)
+ self.ui.listWidget_pltgrps.setCurrentItem(item)
- list_widget = self.ui.listWidget_pltgrps
-
- # Block signals for the same reason as updatesets(): setCurrentItem()
- # below fires currentItemChanged -> writegroups(), which would write
- # whatever's currently in the (stale, belonging to the previously
- # selected groupset) drag-list boxes into this brand-new groupset's
- # slot instead of leaving its real (exclude-everything) default data
- # in place. Update the model first, then sync the GUI from it
- # ourselves via updategroups(), rather than relying on the signal.
- list_widget.blockSignals(True)
- list_widget.addItem(item)
- self.groupsetmodel.add(item.text(), all_groups=self.groups)
- list_widget.setCurrentItem(item)
- list_widget.blockSignals(False)
-
- UIFunctions.updategroups(self)
-
-
+
def removegroup(self):
"""
- Removes the selected groupset from the model and the GUI list.
+ Removes the selected query set from the list of query sets in the GUI and from the querys list.
"""
- self.groupsetmodel.remove(self.ui.listWidget_pltgrps.currentRow())
+ selitem = self.ui.listWidget_pltgrps.currentRow()
+ self.querys.remove(self.querys[selitem])
UIFunctions.updatesets(self)
#import buttons
def loadsession(self):
- """Open a saved ``.mpct`` session and restore every input/parameter widget.
-
- Opening the file is fatal if it fails, but each parameter is then
- restored independently so a single missing/renamed field (e.g. from an
- older save file) cannot silently abort restoration of the rest. The
- previous implementation wrapped the whole body in ``try/except: pass``,
- so the first failing widget (notably ``combo_maxisoshift``, which was
- being given a float index that raises ``TypeError`` in PyQt5) left every
- later parameter un-restored.
- """
- savefile, _ = QFileDialog.getOpenFileName(self, 'Open file', self.recentdir, "*.mpct")
- if not savefile:
- return
- self.savefile = Path(savefile)
- self.recentdir = str(self.savefile.parent)
- try:
- self.read_save(self.savefile)
- except Exception:
- import traceback
- traceback.print_exc()
- self.error('Could not open session file (see console)')
- return
-
- p = self.analysis_paramsgui
-
- def restore(what, action):
+ """
+ Displays a file dialog to get the saved session file, calls the `read_save` method in `main.py` to read the saved
+ data and updates the UI elements with the saved parameters.
+ """
try:
- action()
- except Exception as exc:
- print('Warning: could not restore ' + what + ': ' + str(exc))
-
- def set_maxiso():
- # maxisowin is stored as a float (e.g. 3.0); map it to the matching
- # combo item by text rather than passing a float as an index.
- combo = self.ui.combo_maxisoshift
- for cand in (str(int(p.maxisowin)), str(p.maxisowin)):
- idx = combo.findText(cand)
- if idx >= 0:
- combo.setCurrentIndex(idx)
- return
-
- def set_blankfil():
- if 'absolute' in p.blankfilparam:
- self.ui.lineEdit_blankfilter_absthresh.setText(str(p.blankfilthresh))
- self.ui.radioButton_blankfilter_abs.setChecked(True)
- else:
- self.ui.lineEdit_blankfilter_relthresh.setText(str(p.blankfilthresh))
- self.ui.radioButton_blankfilter_rel.setChecked(True)
-
- # ----- input file path labels -----
- restore('peak table label', lambda: self.ui.lbl_pktbl.setText(self.filename.name))
- restore('sample list label', lambda: self.ui.lbl_spllist.setText(self.samplelistfilename.name))
- restore('metadata label', lambda: self.ui.lbl_splmdt.setText(self.extractmetadatafilename.name))
- restore('fragment file label', lambda: self.ui.lbl_msp.setText(Path(self.fragfilename).name if self.fragfilename else ''))
- restore('output dir label', lambda: self.ui.lbl_outdir.setText(
- str(self.outputdir) if len(str(self.outputdir)) < 40 else '...' + str(self.outputdir)[-40:]))
-
- # ----- filtering parameters -----
- restore('CV filter', lambda: self.ui.checkBox_cv.setChecked('cv' in p.graphfilters))
- restore('mean CV radio', lambda: self.ui.radioButton_meancv.setChecked('average' in p.cvparam))
- restore('median CV radio', lambda: self.ui.radioButton_medcv.setChecked('median' in p.cvparam))
- restore('CV threshold', lambda: self.ui.lineEdit_cvthresh.setText(str(p.cvthresh)))
- restore('mispick filter', lambda: self.ui.checkBox_mp.setChecked('rel' in p.graphfilters))
- restore('merge ions', lambda: self.ui.checkBox_merge.setChecked(getattr(p, 'merge', False)))
- restore('RT window', lambda: self.ui.lineEdit_rtwin.setText(str(p.RTwin)))
- restore('ringing window', lambda: self.ui.lineEdit_ringwin.setText(str(getattr(p, 'ringingwin', ''))))
- restore('isotope window', lambda: self.ui.lineEdit_isowin.setText(str(p.isopeakwin)))
- restore('max isotope shift', set_maxiso)
- restore('deconvolution filter', lambda: self.ui.checkBox_decon.setChecked('insource' in p.graphfilters))
- restore('deconvolution threshold', lambda: self.ui.lineEdit_insourcethresh.setText(str(getattr(p, 'deconthresh', ''))))
-
- # ----- blank filter -----
- restore('blank filter', lambda: self.ui.checkBox_blankfilter.setChecked(p.blnkfltr))
- restore('blank group', lambda: self.ui.combo_blankfil_name.setCurrentText(str(p.blnkgrp)))
- restore('blank filter mode', set_blankfil)
-
- # ----- database search -----
- restore('kingdom', lambda: self.ui.combo_kingdom.setCurrentText(str(getattr(p, 'kingdom', ''))))
- restore('genus', lambda: self.ui.lineEdit_genus.setText(str(getattr(p, 'genus', ''))))
- restore('ppm threshold', lambda: self.ui.lineEdit_ppmthresh.setText(str(getattr(p, 'ppmthresh', ''))))
-
- # ----- plot toggles -----
- # Plain 1:1 checkbox fields (no branching/derived values) -- see
- # paramfields.py for the shared save/restore schema; the matching
- # save side is enumerate_inputs()'s save_checkbox_fields() call.
- restore_checkbox_fields(self, p, restore)
-
- # ----- statistics / plot params -----
- restore('experimental group', lambda: self.ui.combo_expgrp.setCurrentText(str(p.statstgrps[0])))
- restore('control group', lambda: self.ui.combo_ctrgrp.setCurrentText(str(p.statstgrps[1])))
- # colour scheme / p/q threshold / fold-change threshold are no longer
- # restored here -- they moved to the heatmap & volcano plots' own live
- # control bars and are intentionally not persisted (same as the
- # dendrogram's per-plot controls). Old .mpct files that still carry these
- # values simply ignore them on load.
+ self.savefile, _ = QFileDialog.getOpenFileName(self, 'Open file', self.recentdir ,
+ "*.mpct")
+ self.savefile = Path(self.savefile)
+ self.recentdir = str(self.savefile.parent)
+ self.read_save(self.savefile)
+
+ self.ui.lbl_pktbl.setText(self.filename.name)
+ self.ui.lbl_spllist.setText(self.samplelistfilename.name)
+ self.ui.lbl_splmdt.setText(self.extractmetadatafilename.name)
+ self.ui.lbl_msp.setText(self.fragfilename.name)
+ if len(str(self.outputdir)) <40:
+ self.ui.lbl_outdir.setText(self.outputdir)
+ else:
+ self.ui.lbl_outdir.setText('...' + str(self.outputdir)[-40:])
+
+ self.ui.checkBox_cv.setChecked('cv' in self.analysis_paramsgui.graphfilters) # may be good to add seperate parameters for each filter instead of using str?
+ self.ui.radioButton_meancv.setChecked('average' in self.analysis_paramsgui.cvparam)
+ self.ui.radioButton_medcv.setChecked('median' in self.analysis_paramsgui.cvparam)
+ self.ui.lineEdit_cvthresh.setText(str(self.analysis_paramsgui.cvthresh))
+ self.ui.checkBox_mp.setChecked('rel' in self.analysis_paramsgui.graphfilters)
+ self.ui.lineEdit_rtwin.setText(str(self.analysis_paramsgui.RTwin))
+ self.ui.lineEdit_isowin.setText(str(self.analysis_paramsgui.isopeakwin))
+ self.ui.combo_maxisoshift.setCurrentIndex(self.analysis_paramsgui.maxisowin)
+ self.ui.checkBox_decon.setChecked('insource' in self.analysis_paramsgui.graphfilters)
+ self.ui.lineEdit_insourcethresh.setText(str(self.analysis_paramsgui.deconthresh))
+ self.ui.checkBox_blankfilter.setChecked(self.analysis_paramsgui.blnkfltr)
+ self.ui.combo_blankfil_name.setCurrentText(str(self.analysis_paramsgui.blnkgrp))
+ self.ui.radioButton_meancv.setChecked('average' in self.analysis_paramsgui.cvparam)
+ if 'absolute' in self.analysis_paramsgui.blankfilparam:
+ self.ui.lineEdit_blankfilter_absthresh.setText(str(self.analysis_paramsgui.blankfilthresh))
+ self.ui.radioButton_blankfilter_abs.setChecked(True)
+ else:
+ self.ui.lineEdit_blankfilter_relthresh.setText(str(self.analysis_paramsgui.blankfilthresh))
+ self.ui.radioButton_blankfilter_rel.setChecked(True)
+
+ self.ui.checkBox_pca.setChecked(self.analysis_paramsgui.PCA)
+ self.ui.checkBox_dend.setChecked(self.analysis_paramsgui.Dendrogram)
+ self.ui.checkBox_mzrt.setChecked(self.analysis_paramsgui.MZRTplt)
+ self.ui.checkBox_kmd.setChecked(self.analysis_paramsgui.KMD)
+ self.ui.checkBox_fc.setChecked(self.analysis_paramsgui.FC)
+ self.ui.checkBox_3dfc.setChecked(self.analysis_paramsgui.FC3Dplt)
+ self.ui.checkBox_ttest.setChecked(self.analysis_paramsgui.Ttest)
+ self.ui.checkBox_volcano.setChecked(self.analysis_paramsgui.Volcanoplt)
+
+ self.ui.checkBox_FDR.setChecked(self.analysis_paramsgui.FDR)
+ self.dialog.ui.checkBox_bootstrap.setChecked(self.analysis_paramsgui.bootstrap)
+ self.ui.combo_expgrp.setCurrentText(str(self.analysis_paramsgui.statstgrps[0]))
+ self.ui.combo_ctrgrp.setCurrentText(str(self.analysis_paramsgui.statstgrps[1]))
+
+ self.dialog.ui.combo_colorscheme.setCurrentText(self.analysis_paramsgui.colorscheme)
+ self.dialog.ui.lineEdit_pqthresh.setText(str(self.analysis_paramsgui.pqthresh))
+ self.dialog.ui.lineEdit_fcthresh.setText(str(self.analysis_paramsgui.fcthresh))
+ self.dialog.ui.checkBox_mdguide.setChecked(self.analysis_paramsgui.mdguide)
+ except Exception:
+ #self.error('Files in use, Close before analysis')
+ pass
+ return()
+
def getfilename(self):
self.filename, _ = QFileDialog.getOpenFileName(self, 'Open file', self.recentdir ,
"*.csv *.txt")
@@ -576,19 +524,17 @@ def getextractmetadatafilename(self):
self.getgroups()
def getoutputdir(self):
- selected = QFileDialog.getExistingDirectory(self, 'Select Directory', self.recentdir)
- if not selected:
- # Dialog cancelled -- leave the previously-selected output dir
- # (and recentdir) untouched rather than clobbering them.
- self.error('No directory selected')
- return
- self.outputdir = Path(selected)
+ self.outputdir = Path(str(QFileDialog.getExistingDirectory(self, 'Select Directory', self.recentdir)))
self.recentdir = str(self.outputdir)
- # setText needs a str (passing a Path raises); show the full path
- # when short, otherwise truncate from the left so the informative
- # tail stays visible.
- shown = str(self.outputdir)
- self.ui.lbl_outdir.setText(shown if len(shown) < 40 else '...' + shown[-40:])
+ if len(str(self.outputdir)) <40:
+ try:
+ self.ui.lbl_outdir.setText(self.outputdir)
+ except Exception:
+ self.error('No directory selected')
+ pass
+ return()
+ else:
+ self.ui.lbl_outdir.setText('...' + str(self.outputdir)[-40:])
def getfragfilename(self):
self.fragfilename, _ = QFileDialog.getOpenFileName(self, 'Open file', self.recentdir,
@@ -607,40 +553,47 @@ def getgnpsfilename(self):
#reset uibar buttons
def reset_mainbar(self):
- self.ui.btn_import.setStyleSheet(_MAINBAR_INACTIVE_STYLE)
- self.ui.btn_filter.setStyleSheet(_MAINBAR_INACTIVE_STYLE)
- self.ui.btn_parameters.setStyleSheet(_MAINBAR_INACTIVE_STYLE)
- self.ui.btn_plots.setStyleSheet(_MAINBAR_INACTIVE_STYLE)
- self.ui.btn_info.setStyleSheet(_MAINBAR_INACTIVE_STYLE)
- self.ui.btn_search.setStyleSheet(_MAINBAR_INACTIVE_STYLE)
+ self.ui.mainbar_activebtn = "QPushButton { border: none; background-color: transparent;}QPushButton:hover {background-color: transparent}QPushButton:pressed { background-color: rgb(75, 75, 75);}"
+ self.ui.mainbar_inactivebtn ="QPushButton { border: none; background-color: rgb(35, 35, 35);}QPushButton:hover {background-color: transparent}QPushButton:pressed { background-color: rgb(75, 75, 75);}"
+ self.ui.btn_import.setStyleSheet(self.ui.mainbar_inactivebtn)
+ self.ui.btn_filter.setStyleSheet(self.ui.mainbar_inactivebtn)
+ self.ui.btn_parameters.setStyleSheet(self.ui.mainbar_inactivebtn)
+ self.ui.btn_plots.setStyleSheet(self.ui.mainbar_inactivebtn)
+ self.ui.btn_info.setStyleSheet(self.ui.mainbar_inactivebtn)
+ self.ui.btn_search.setStyleSheet(self.ui.mainbar_inactivebtn)
self.ui.label_status.setText('') #to reset analysis status after tabs are switched. eventually use a second thread to dynamically update status
self.ui.label_status.setStyleSheet('color: rgb(150,150,150);')
def reset_plotbar(self):
- self.ui.btn_review.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ui.btn_dend.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ui.btn_upset.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ui.btn_pca.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ui.btn_mzrt.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ui.btn_kmd.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ui.btn_3dfc.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ui.btn_volcano.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ui.btn_heatmap.setStyleSheet(_LIGHT_INACTIVE_STYLE)
+ self.ui.plotbar_activebtn = "QPushButton { border: none;background-color: rgba(225,225,225, 255); color: rgba(75,75,75,255)} QPushButton:hover {background-color: rgba(225,225,225, 255); color: rgba(75,75,75,255)} QPushButton:pressed { background-color: rgba(225,225,225, 255); color: rgba(75,75,75,255)}"
+ self.ui.plotbar_inactivebtn ="QPushButton { border: none;background-color: rgba(0,0,0, 0)} QPushButton:hover {background-color: rgba(225,225,225, 50)} QPushButton:pressed { background-color: rgba(225,225,225, 255); color: rgba(75,75,75,255)}"
+ self.ui.btn_review.setStyleSheet(self.ui.plotbar_inactivebtn)
+ self.ui.btn_dend.setStyleSheet(self.ui.plotbar_inactivebtn)
+ self.ui.btn_upset.setStyleSheet(self.ui.plotbar_inactivebtn)
+ self.ui.btn_pca.setStyleSheet(self.ui.plotbar_inactivebtn)
+ self.ui.btn_mzrt.setStyleSheet(self.ui.plotbar_inactivebtn)
+ self.ui.btn_kmd.setStyleSheet(self.ui.plotbar_inactivebtn)
+ self.ui.btn_3dfc.setStyleSheet(self.ui.plotbar_inactivebtn)
+ self.ui.btn_volcano.setStyleSheet(self.ui.plotbar_inactivebtn)
+ self.ui.btn_heatmap.setStyleSheet(self.ui.plotbar_inactivebtn)
self.dialog.ui.frame_2.hide()
self.dialog.ui.frame.hide() #hide apply button, button doesnt work right now, use run button
self.dialog.ui.frame_mdguide.hide()
self.dialog.ui.frame_volcanoparams.hide()
self.dialog.ui.frame_colorscheme.hide()
+ self.dialog.ui.checkBox_applyfilter.show()
self.ui.label_status.setText('')
def reset_ftrdialogbar(self):
- self.ftrdialog.ui.btn_hits.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ftrdialog.ui.btn_spectrum.setStyleSheet(_LIGHT_INACTIVE_STYLE)
- self.ftrdialog.ui.btn_abund.setStyleSheet(_LIGHT_INACTIVE_STYLE)
+ self.ui.ftbar_activebtn = "QPushButton {border: none;background-color: rgba(225,225,225, 255); color: rgba(75,75,75,255)} QPushButton:hover {background-color: rgba(225,225,225, 255); color: rgba(75,75,75,255)} QPushButton:pressed { background-color: rgba(225,225,225, 255); color: rgba(75,75,75,255)}"
+ self.ui.ftbar_inactivebtn ="QPushButton {border: none;background-color: rgba(0,0,0,0)} QPushButton:hover {background-color: rgba(225,225,225, 50)} QPushButton:pressed { background-color: rgba(225,225,225, 255); color: rgba(75,75,75,255)}"
+ self.ftrdialog.ui.btn_hits.setStyleSheet(self.ui.ftbar_inactivebtn)
+ self.ftrdialog.ui.btn_spectrum.setStyleSheet(self.ui.ftbar_inactivebtn)
+ self.ftrdialog.ui.btn_abund.setStyleSheet(self.ui.ftbar_inactivebtn)
def show_ftrdialog(self):
self.ftrdialog.show()
if self.pickedfeature != '':
- self._refresh_highlight()
+ self.highlight_feature(self.pickedfeature)
diff --git a/code/ui_plotter.py b/code/ui_plotter.py
new file mode 100644
index 0000000..3c156fa
--- /dev/null
+++ b/code/ui_plotter.py
@@ -0,0 +1,20 @@
+"""
+MPACT
+Copyright 2022, Robert M. Samples, Sara P. Puckett, and Marcy J. Balunas
+"""
+
+
+class genfeatureplot:
+
+ def __init__(self, name, groupionlists, iondictloc):
+
+ def onpick(self, self.main, event):
+ ind = event.ind
+ coord = event.artist.get_offsets()[ind,:]
+ self.main.pickedfeature = iondict.loc[abs(iondict[self.xvar] - coord[0,0]) <= 0.001, :].loc[abs(iondict[self.yvar] - coord[0,1]) <= 0.001, :].reset_index()
+ self.main.pickedfeature = str(self.pickedfeature.iloc[0,0])
+ self.main.ui.lbl_featurename.setText('Compound: ' + self.main.pickedfeature)
+ self.main.ui.lbl_featurert.setText('Retention time: ' + str(round(self.main.pickedfeature, 4)))
+ self.main.ui.lbl_featuremz.setText('m/z: ' + str(round(self.main.pickedfeature, 4)))
+
+ self.main.highlight_feature()
\ No newline at end of file
diff --git a/run.bat b/run.bat
index 1dee2aa..118dafb 100644
--- a/run.bat
+++ b/run.bat
@@ -1,24 +1,3 @@
-@echo off
-setlocal
-
-rem Resolve every path relative to this script's own location (not a
-rem hardcoded folder), so this keeps working if/when the repo is moved or
-rem re-cloned somewhere else. %~dp0 is this .bat file's directory.
-set "REPO_DIR=%~dp0"
-set "CODE_DIR=%REPO_DIR%code"
-
-call "%USERPROFILE%\anaconda3\Scripts\activate.bat"
-if errorlevel 1 (
- echo Could not activate Anaconda at "%USERPROFILE%\anaconda3".
- echo Edit run.bat if Anaconda is installed somewhere else.
- pause
- exit /b 1
-)
-
-rem main.py uses paths (npatlas.tsv, compoundimages\, etc.) relative to the
-rem code directory, matching how Spyder's runfile() sets the working
-rem directory -- so cd into code\ before launching, not the repo root.
-cd /d "%CODE_DIR%"
+cd /d "F:\metabolomics\metabolomic\Robert methodology\MPACT\mpact-main\mpact-main\code"
python main.py
-
-pause
+pause
\ No newline at end of file