diff --git "a/data/dataset_Pharmacogenomics.csv" "b/data/dataset_Pharmacogenomics.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Pharmacogenomics.csv" @@ -0,0 +1,16422 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Pharmacogenomics","PharmGKB/ITPC","src/Parser.java",".java","4978","164","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +import org.apache.commons.io.IOUtils; +import org.apache.log4j.Logger; +import org.pharmgkb.ItpcSheet; +import org.pharmgkb.Subject; +import summary.AbstractSummary; +import summary.GenotypeSummary; +import summary.InclusionSummary; +import summary.MetabStatusSummary; +import util.CliHelper; + +import java.io.File; +import java.io.FileWriter; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Jul 27, 2010 + * Time: 7:56:34 AM + */ +public class Parser { + private static final Logger sf_logger = Logger.getLogger(Parser.class); + private File m_fileInput; + private boolean m_doHighlight = false; + protected ItpcSheet dataSheet; + + public static void main(String[] args) { + try { + System.out.println(""ITPC Parser run: "" + new Date()); + + Parser parser = new Parser(); + parser.parseArgs(args); + parser.parseFile(); + } + catch (Exception ex) { + sf_logger.error(""Error running parser"", ex); + } + } + + protected void parseFile() throws Exception { + if (getFileInput() == null || !getFileInput().exists()) { + throw new Exception(""Input file doesn't exist""); + } + + File sqlFile = new File(getFileInput().getAbsolutePath().replaceAll(""\\.xls"", "".sql"")); + FileWriter fw = new FileWriter(sqlFile); + + dataSheet = new ItpcSheet(getFileInput(), m_doHighlight); + List summaries = Arrays.asList( + new GenotypeSummary(), + new MetabStatusSummary(), + new InclusionSummary() + ); + + int sampleCount = 0; + while (dataSheet.hasNext()) { + try { + Subject subject = dataSheet.next(); + dataSheet.writeSubjectCalculatedColumns(subject); + + fw.write(subject.makeSqlInsert()); + fw.write(""\n""); + + for (AbstractSummary summ : summaries) { + summ.addSubject(subject); + } + + sampleCount++; + } + catch (Exception ex) { + throw new Exception(""Exception on line ""+dataSheet.getCurrentRowIndex(), ex); + } + } + sf_logger.info(""Parsed "" + sampleCount + "" samples""); + + fw.write(""commit;\n""); + IOUtils.closeQuietly(fw); + + for (AbstractSummary summ : summaries) { + summ.writeToWorkbook(dataSheet.getWorkbook()); + } + + dataSheet.saveOutput(); + } + + protected void parseArgs(String[] args) throws Exception { + CliHelper cli = new CliHelper(getClass(), false); + cli.addOption(""f"", ""file"", ""ITPC excel file to read"", ""pathToFile""); + cli.addOption(""hi"", ""highlight"", ""Highlight changed values""); + + try { + cli.parse(args); + if (cli.isHelpRequested()) { + cli.printHelp(); + System.exit(1); + } + } + catch (Exception ex) { + throw new Exception(""Errror parsing params"", ex); + } + + if (cli.hasOption(""-f"")) { + File fileInput = new File(cli.getValue(""-f"")); + if (fileInput.exists()) { + this.setFileInput(fileInput); + } + else { + throw new Exception(""File doesn't exist: "" + fileInput); + } + } + + if (cli.hasOption(""-hi"")) { + m_doHighlight = true; + } + + } + + public File getFileInput() { + return m_fileInput; + } + + public void setFileInput(File fileInput) { + m_fileInput = fileInput; + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/org/pharmgkb/Genotype.java",".java","10335","330","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package org.pharmgkb; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import util.ItpcUtils; +import util.StringPair; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Created by IntelliJ IDEA. + * User: Ryan Whaley + * Date: Jul 13, 2010 + * Time: 11:16:54 PM + */ +public class Genotype extends StringPair { + public enum Metabolizer {Unknown, PM, IM, EM, UM} + public static final String EXTENSIVE = ""Extensive""; + public static final String INTERMEDIATE = ""Intermediate""; + public static final String POOR = ""Poor""; + public static final String UNKNOWN = ""Unknown""; + + private static final Pattern sf_numberPattern = Pattern.compile(""\\D*(\\d+)\\D*""); + private static final Logger sf_logger = Logger.getLogger(Genotype.class); + + private static final Map metabMap = new HashMap(); + static { + metabMap.put(""*3"",Metabolizer.PM); + metabMap.put(""*4"",Metabolizer.PM); + metabMap.put(""*5"",Metabolizer.PM); + metabMap.put(""*6"",Metabolizer.PM); + metabMap.put(""*7"",Metabolizer.PM); + metabMap.put(""*8"",Metabolizer.PM); + metabMap.put(""*11"",Metabolizer.PM); + metabMap.put(""*12"",Metabolizer.PM); + metabMap.put(""*13"",Metabolizer.PM); + metabMap.put(""*14"",Metabolizer.PM); + metabMap.put(""*15"",Metabolizer.PM); + metabMap.put(""*16"",Metabolizer.PM); + metabMap.put(""*18"",Metabolizer.PM); + metabMap.put(""*19"",Metabolizer.PM); + metabMap.put(""*20"",Metabolizer.PM); + metabMap.put(""*40"",Metabolizer.PM); + metabMap.put(""*42"",Metabolizer.PM); + metabMap.put(""*44"",Metabolizer.PM); + metabMap.put(""*56"",Metabolizer.PM); + metabMap.put(""*38"",Metabolizer.PM); + metabMap.put(""*4XN"",Metabolizer.PM); + + metabMap.put(""*9"",Metabolizer.IM); + metabMap.put(""*9XN"",Metabolizer.IM); + metabMap.put(""*10"",Metabolizer.IM); + metabMap.put(""*10XN"",Metabolizer.IM); + metabMap.put(""*17"",Metabolizer.IM); + metabMap.put(""*29"",Metabolizer.IM); + metabMap.put(""*37"",Metabolizer.IM); + metabMap.put(""*41"",Metabolizer.IM); + metabMap.put(""*41XN"",Metabolizer.IM); + metabMap.put(""*45"",Metabolizer.IM); + metabMap.put(""*46"",Metabolizer.IM); + + metabMap.put(""*1"",Metabolizer.EM); + metabMap.put(""*2"",Metabolizer.EM); + metabMap.put(""*2A"",Metabolizer.EM); + metabMap.put(""*33"",Metabolizer.EM); + metabMap.put(""*35"",Metabolizer.EM); + metabMap.put(""*39"",Metabolizer.EM); + metabMap.put(""*43"",Metabolizer.EM); + + metabMap.put(""*1XN"",Metabolizer.UM); + metabMap.put(""*2XN"",Metabolizer.UM); + metabMap.put(""*35XN"",Metabolizer.UM); + metabMap.put(""*39XN"",Metabolizer.UM); + + metabMap.put(""Unknown"", Metabolizer.Unknown); + } + + private static final Map scoreMap = new HashMap(); + static { + scoreMap.put(Metabolizer.PM, 0f); + scoreMap.put(Metabolizer.IM, 0.5f); + scoreMap.put(Metabolizer.EM, 1f); + scoreMap.put(Metabolizer.UM, 2f); + } + + private static final Map priorityMap = new HashMap(); + static { + priorityMap.put(Metabolizer.PM,1); // top priority + priorityMap.put(Metabolizer.IM,2); + priorityMap.put(Metabolizer.EM,3); + priorityMap.put(Metabolizer.UM,4); + priorityMap.put(Metabolizer.Unknown, 5); // bottom priority + } + + public Genotype() {} + + public Genotype(String string) { + if (string != null && string.contains(""/"")) { + String[] tokens = string.split(""/""); + for (String token : tokens) { + addString(token); + } + } + } + + public Genotype(String s1, String s2) { + addString(s1); + addString(s2); + } + + public boolean isValid(String string) { + return metabMap.keySet().contains(ItpcUtils.alleleStrip(string)) || string.equals(""Unknown""); + } + + public Float getScore() { + Float score = null; + + if (!this.isUncertain()) { + score = 0f; + for (String allele : this.getStrings()) { + score += scoreMap.get(metabMap.get(ItpcUtils.alleleStrip(allele))); + } + } + + return score; + } + + /** + * Adds an allele to the List of alleles, taking into consideration the prioritization found + * in the genoPriority Map for this class + * @param string a new String allele to add to the List + */ + public void addString(String string) { + if (!isValid(string)) { + return; + } + + if (this.getStrings().isEmpty() || this.getStrings().size()==1) { + super.addString(string); + } + else { + String removeAllele = null; + for (String existingAllele : this.getStrings()) { + // if the new allele has a higher priority (lower number) than an existing one, replace it + if ((priority(string) < priority(existingAllele)) + || (existingAllele.equals(""*1"") && priority(existingAllele)==(priority(string))) + ) { + removeAllele = existingAllele; + } + } + if (!StringUtils.isBlank(removeAllele)) { + removeString(removeAllele); + super.addString(string); + } + } + reorder(); + } + + protected void reorder() { + if (getStrings().size()==2) { + + try { + Integer int0, int1; + Matcher matcher = sf_numberPattern.matcher(getStrings().get(0)); + if (matcher.find()) { + int0 = Integer.parseInt(matcher.group(1)); + } + else { + return; + } + + matcher.reset(getStrings().get(1)); + if (matcher.find()) { + int1 = Integer.parseInt(matcher.group(1)); + } + else { + return; + } + + if (int0>int1) { + Collections.reverse(getStrings()); + } + } + catch (Exception ex) { + if (sf_logger.isDebugEnabled()) { + sf_logger.debug(""Error reordering: "" + getStrings()); + } + } + + } + } + + protected static String getText(Metabolizer value) { + if (value == null) { + return ""Unknown""; + } + else { + switch (value) { + case IM: return ""IM""; + case PM: return ""PM""; + case EM: return ""EM""; + case UM: return ""UM""; + default: return ""Unknown""; + } + } + } + + public String getMetabolizerStatus() { + if (this.getStrings().isEmpty()) { + return getText(Metabolizer.Unknown); + } + + List genotypes = new ArrayList(); + for (String allele : this.getStrings()) { + if (allele != null && !allele.equals(""Unknown"") && !metabMap.keySet().contains(ItpcUtils.alleleStrip(allele))) { + sf_logger.warn(""Can't find map for allele: "" + ItpcUtils.alleleStrip(allele)); + } + genotypes.add(getText(metabMap.get(ItpcUtils.alleleStrip(allele)))); + } + + StringBuilder genoBuilder = new StringBuilder(); + Collections.sort(genotypes, String.CASE_INSENSITIVE_ORDER); + for (int x = 0; x < genotypes.size(); x++) { + genoBuilder.append(genotypes.get(x)); + if (x != genotypes.size() - 1) { + genoBuilder.append(""/""); + } + } + return genoBuilder.toString(); + } + + public String getMetabolizerGroup() { + String group = ""Unknown""; + + // modify genoMetabStatusIdx description field if this changes + if (getMetabolizerStatus().equals(""EM/EM"") + || getMetabolizerStatus().equals(""EM/UM"") + || getMetabolizerStatus().equals(""IM/UM"") + || getMetabolizerStatus().equals(""UM/UM"")) { + group = ""Extensive""; + } + else if (getMetabolizerStatus().equals(""EM/PM"") + || getMetabolizerStatus().equals(""IM/IM"") + || getMetabolizerStatus().equals(""IM/PM"") + || getMetabolizerStatus().equals(""PM/UM"") + || getMetabolizerStatus().equals(""EM/IM"")) { + group = ""Intermediate""; + } + else if (getMetabolizerStatus().equals(""PM/PM"")) { + group = ""Poor""; + } + + return group; + } + + public boolean isHeteroDeletion() { + return this.getStrings().contains(""*5""); + } + + public boolean isHomoDeletion() { + return this.is(""*5"",""*5""); + } + + private float priority(String allele) { + return priorityMap.get(metabMap.get(ItpcUtils.alleleStrip(allele))); + } + + public boolean is(Metabolizer status1, Metabolizer status2) { + if (status1 != null && status2 != null) { + if (status1 == status2) { + return count(status1)==2; + } + else { + return (count(status1) == 1 && count(status2)==1); + } + } + return false; + } + + protected int count(Metabolizer status) { + int count = 0; + for (String element : getStrings()) { + if (metabMap.get(ItpcUtils.alleleStrip(element)) == status) count++; + } + return count; + } + + public boolean isUnknown() { + return contains(""Unknown""); + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/org/pharmgkb/Subject.java",".java","44762","1590","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package org.pharmgkb; + +import com.google.common.base.Joiner; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import util.ItpcUtils; +import util.Med; +import util.Value; + +import java.util.*; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Jul 14, 2010 + * Time: 8:16:01 AM + */ +public class Subject { + private static final Logger logger = Logger.getLogger(Subject.class); + + private String m_subjectId = null; + private String m_projectSite = null; + private String m_age = null; + private String m_gender = null; + private String m_race = null; + private String m_menoStatus = null; + private String m_metastatic = null; + private String m_erStatus = null; + private String m_duration = null; + private String m_tamoxDose = null; + private String m_tumorSource = null; + private String m_bloodSource = null; + private String m_priorHistory = null; + private String m_priorDcis = null; + private String m_chemotherapy = null; + private String m_hormoneTherapy = null; + private String m_systemicTher = null; + private String m_followup = null; + private String m_timeBtwSurgTamox = null; + private String m_firstAdjEndoTher = null; + private String m_tumorDimension = null; + private String m_numPositiveNodes = null; + private String m_tumorGrading = null; + private String progesteroneReceptor = null; + private String radiotherapy = null; + private Deletion m_deletion = Deletion.Unknown; + private Value m_additionalCancer = null; + private String m_addCxIpsilateral = null; + private String m_addCxDistantRecur = null; + private String m_addCxContralateral = null; + private String m_addCxSecondInvasive = null; + private String m_addCxLastEval = null; + private String m_daysDiagtoDeath = null; + private Value m_patientDied = null; + private String m_diseaseFreeSurvivalTime = null; + private String m_survivalNotDied = null; + private String m_causeOfDeath = null; + private Value m_dcisStatus = Value.Unknown; + + private Genotype m_genotypePgkb = new Genotype(); + private Genotype m_genotypeAmplichip = new Genotype(); + private Genotype m_genotypeLimited = new Genotype(); + private Genotype m_genotypeOther = new Genotype(); + + private VariantAlleles m_rs1065852 = new VariantAlleles(); + private VariantAlleles m_rs4986774 = new VariantAlleles(); + private VariantAlleles m_rs3892097 = new VariantAlleles(); + private VariantAlleles m_rs5030655 = new VariantAlleles(); + private VariantAlleles m_rs16947 = new VariantAlleles(); + private VariantAlleles m_rs28371706 = new VariantAlleles(); + private VariantAlleles m_rs28371725 = new VariantAlleles(); + private Set m_sampleSources = Sets.newHashSet(); + + private Map m_medStatus = Maps.newHashMap(); + + public Subject() { + this.calculateGenotypePgkb(); + } + + public Genotype getGenotypePgkb() { + return m_genotypePgkb; + } + + protected void setGenotypePgkb(Genotype genotypePgkb) { + m_genotypePgkb = genotypePgkb; + } + + public Genotype getGenotypeAmplichip() { + return m_genotypeAmplichip; + } + + public void setGenotypeAmplichip(Genotype genotypeAmplichip) { + m_genotypeAmplichip = genotypeAmplichip; + } + + public void setGenotypeAmplichip(String alleles) { + try { + this.setGenotypeAmplichip(processGenotype(alleles)); + } + catch (Exception ex) { + logger.warn(""Cannot parse amplichip genotype: "" + alleles); + } + } + + public Genotype getGenotypeAllFinal() { + if (m_genotypeAmplichip != null && m_genotypeAmplichip.hasData()) { + return m_genotypeAmplichip; + } + else { + return m_genotypePgkb; + } + } + + public Genotype getGenotypeFinal() { + if (getGenotypeAllFinal().isUncertain() && !getGenotypeLimited().isUncertain()) { + return getGenotypeLimited(); + } + else { + return getGenotypeAllFinal(); + } + } + + public Value getWeak() { + if (hasMed(Med.Cimetidine) == Value.Yes + || hasMed(Med.Sertraline) == Value.Yes + || hasMed(Med.Citalopram) == Value.Yes) { + return Value.Yes; + } + else if (hasMed(Med.Cimetidine) == Value.No + && hasMed(Med.Sertraline) == Value.No + && hasMed(Med.Citalopram) == Value.No) { + return Value.No; + } + else { + return Value.Unknown; + } + } + + public Value getPotent() { + if (hasMed(Med.Paroxetine) == Value.Yes + || hasMed(Med.Fluoxetine) == Value.Yes + || hasMed(Med.Quinidine) == Value.Yes + || hasMed(Med.Buproprion) == Value.Yes + || hasMed(Med.Duloxetine) == Value.Yes) { + return Value.Yes; + } + else if (hasMed(Med.Paroxetine) == Value.No + && hasMed(Med.Fluoxetine) == Value.No + && hasMed(Med.Quinidine) == Value.No + && hasMed(Med.Buproprion) == Value.No + && hasMed(Med.Duloxetine) == Value.No) { + return Value.No; + } + else { + return Value.Unknown; + } + } + + public VariantAlleles getRs1065852() { + return m_rs1065852; + } + + public void setRs1065852(VariantAlleles rs1065852) { + m_rs1065852 = rs1065852; + this.calculateGenotypePgkb(); + } + + public VariantAlleles getRs4986774() { + return m_rs4986774; + } + + public void setRs4986774(VariantAlleles rs4986774) { + m_rs4986774 = rs4986774; + this.calculateGenotypePgkb(); + } + + public VariantAlleles getRs3892097() { + return m_rs3892097; + } + + public void setRs3892097(VariantAlleles rs3892097) { + m_rs3892097 = rs3892097; + this.calculateGenotypePgkb(); + } + + public VariantAlleles getRs5030655() { + return m_rs5030655; + } + + public void setRs5030655(VariantAlleles rs5030655) { + m_rs5030655 = rs5030655; + this.calculateGenotypePgkb(); + } + + public VariantAlleles getRs16947() { + return m_rs16947; + } + + public void setRs16947(VariantAlleles rs16947) { + m_rs16947 = rs16947; + this.calculateGenotypePgkb(); + } + + public VariantAlleles getRs28371706() { + return m_rs28371706; + } + + public void setRs28371706(VariantAlleles rs28371706) { + m_rs28371706 = rs28371706; + this.calculateGenotypePgkb(); + } + + public VariantAlleles getRs28371725() { + return m_rs28371725; + } + + public void setRs28371725(VariantAlleles rs28371725) { + m_rs28371725 = rs28371725; + this.calculateGenotypePgkb(); + } + + public Float getScore() { + return getGenotypeFinal().getScore(); + } + + public String getMetabolizerGroup() { + Float score = this.getScore(); + if (score == null) { + return ""Uncategorized""; + } + else if (score>=4.0) { + return ""Ultrarapid one""; + } + else if (score>=3.5) { + return ""Ultrarapid two""; + } + else if (score>=3.0) { + return ""Ultrarapid three""; + } + else if (score>=2.5) { + return ""Extensive one""; + } + else if (score>=2.0) { + return ""Extensive two""; + } + else if (score>=1.5) { + return ""Intermediate one""; + } + else if (score>=1.0) { + return ""Intermediate two""; + } + else if (score>=0.5) { + return ""Intermediate three""; + } + else if (score==0.0) { + return ""Poor""; + } + else { + return ""Uncategorized""; + } + } + + public boolean deletionDetectable() { + return this.getDeletion()!=Deletion.Unknown + || this.getRs4986774().is(""-"",""a"") + || this.getRs1065852().is(""c"",""t"") + || this.getRs3892097().is(""a"",""g"") + || this.getRs5030655().is(""-"",""t"") + || this.getRs16947().is(""c"",""t"") + || this.getRs28371706().is(""c"",""t"") + || this.getRs28371725().is(""g"",""a""); + } + + public void calculateGenotypePgkb() { + Genotype geno = new Genotype(); + + switch (this.getDeletion()) { + case Hetero: geno.addString(""*5""); break; + case Homo: geno = new Genotype(""*5/*5""); break; + } + + if (!geno.isHomoDeletion()) { + // *3 + if (this.getRs4986774().hasData()) { + if (geno.isHeteroDeletion() && this.getRs4986774().count(""-"")==2) { + geno.addString(""*3""); + } + else if (!geno.isHeteroDeletion()) { + for (int i=0; i getRs28371706().count(""t"") + && getRs16947().count(""t"") > getRs28371725().count(""a"") + && !(getRs16947().count(""t"") <= getRs1065852().count(""t"") && getRs16947().count(""t"") <= getRs3892097().count(""a""))) { + geno.addString(""*2""); + if (!geno.isHeteroDeletion() && + (getRs16947().is(""t"",""t"") && getRs28371706().is(""c"",""c"") && getRs28371725().is(""g"",""g""))) { + geno.addString(""*2""); + } + } + + // *10 + if (this.getRs1065852().hasData()) { + if (this.getRs1065852().contains(""t"") && this.getRs3892097().count(""a"")==0) { + geno.addString(""*10""); + } + if (!geno.isHeteroDeletion() && this.getRs1065852().is(""t"",""t"") && this.getRs3892097().contains(""g"")) { + geno.addString(""*10""); + } + } + + // *17 + if (this.getRs28371706().hasData() && this.getRs16947().hasData()) { + if (this.getRs28371706().contains(""t"") && this.getRs16947().contains(""t"")) { + geno.addString(""*17""); + } + if (this.getRs28371706().count(""t"")==2 && this.getRs16947().count(""t"")==2 + && deletionDetectable() && !geno.isHeteroDeletion()) { + geno.addString(""*17""); + } + } + } + else if (!deletionDetectable()) { //what to do if we don't have complete *5 knowledge + if (this.getRs4986774().hasData() && + this.getRs1065852().hasData() && + this.getRs3892097().hasData() && + this.getRs5030655().hasData() && + this.getRs16947().is(""t"",""t"") && + this.getRs28371725().is(""g"",""g"") && + this.getRs28371706().is(""c"",""c"")) { + geno.addString(""*2""); + } + else if (this.getRs4986774().hasData() && + this.getRs1065852().hasData() && + this.getRs3892097().hasData() && + this.getRs5030655().hasData() && + this.getRs16947().hasData() && + this.getRs28371725().hasData() && + this.getRs28371706().hasData() && + geno.isEmpty()) { + geno.addString(""*1""); + geno.addString(""Unknown""); + } + } + } + + if (this.getRs4986774().hasData() && // special case for partial unknown info., from Joan + this.getRs1065852().hasData() && + this.getRs3892097().hasData() && + this.getRs5030655().hasData() && + this.getRs16947().is(""c"",""t"") && + (!this.getRs28371706().hasData() || !this.getRs28371725().hasData()) && + deletionDetectable() && + geno.isEmpty()) { + geno.addString(""*1""); + geno.addString(""Unknown""); + } + + + while (geno.size() < 2) { + if (this.getRs4986774().hasData() && + this.getRs1065852().hasData() && + this.getRs3892097().hasData() && + this.getRs5030655().hasData() && + this.getRs16947().hasData() && + deletionDetectable() && + (this.getRs28371725().hasData() || (!this.getRs28371725().hasData() && (this.getRs16947().is(""C"",""C"") || this.getRs16947().is(""C"",""-"")))) && + (!geno.isHeteroDeletion() || (geno.isHeteroDeletion() && (this.getRs28371725().hasData() || this.getRs28371706().hasData())))) // we can use rs16947 to exclude *41 calls so it doesn't always have to be available + { + geno.addString(""*1""); + } + else { + geno.addString(""Unknown""); + } + } + + this.setGenotypePgkb(geno); + } + + public void calculateGenotypeLimited() { + Genotype geno = new Genotype(); + + applyStarFiveLogic(geno); + applyStarThreeLogic(geno); + boolean starFourAble = applyStarFourLogic(geno); + applyStarTenLogic(geno); + applyStarFortyOneLogic(geno); + applyStarTwoLogic(geno); + applyStarSixLogic(geno); + applyStarSeventeenLogic(geno); + + while (geno.size() < 2) { + if (starFourAble) { + geno.addString(""*1""); + } + else { + geno.addString(""Unknown""); + } + } + + setGenotypeLimited(geno); + } + + protected boolean applyStarFiveLogic(Genotype geno) { + if (getDeletion() == Deletion.Unknown) { + return false; + } + + if (getDeletion() == Deletion.Hetero || getDeletion() == Deletion.Homo) { + geno.addString(""*5""); + } + if (getDeletion() == Deletion.Homo) { + geno.addString(""*5""); + } + return true; + } + + protected boolean applyStarTwoLogic(Genotype geno) { + if (getRs16947().hasData() && getRs28371706().hasData() && getRs28371725().hasData() + && getRs16947().count(""t"") > getRs28371706().count(""t"") + && getRs16947().count(""t"") > getRs28371725().count(""a"") + && !(getRs16947().count(""t"") <= getRs1065852().count(""t"") && getRs16947().count(""t"") <= getRs3892097().count(""a""))) { + + geno.addString(""*2""); + + if (!geno.isHeteroDeletion() + && (getRs16947().is(""t"",""t"") + && getRs28371706().is(""c"",""c"") + && getRs28371725().is(""g"",""g""))) { + geno.addString(""*2""); + } + return !getRs16947().isUncertain() && !getRs28371706().isUncertain() && !getRs28371725().isUncertain(); + } + else { + return false; + } + } + + protected boolean applyStarSixLogic(Genotype geno) { + if (this.getRs5030655().hasData()) { + if (geno.isHeteroDeletion() && this.getRs5030655().count(""-"")==2) { + geno.addString(""*6""); + } + else if (!geno.isHeteroDeletion()) { + for (int i=0; i=50f) { + return Value.Yes; + } + else { + return Value.No; + } + } catch (NumberFormatException ex) { + return Value.Unknown; + } + } + else { + return Value.Unknown; + } + } + } + + public Value passInclusion2a() { + if ((StringUtils.equals(getMetastatic(), ""0"") && isValidTumorDimension()) && getDcisStatus()!=Value.Yes) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value passInclusion2b() { + if ((ItpcUtils.isBlank(getPriorHistory()) || this.getPriorHistory().equals(""0"")) + && (ItpcUtils.isBlank(getPriorDcis()) || !this.getPriorDcis().equals(""1""))) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value passInclusion3() { + if (this.getErStatus() != null && this.getErStatus().equals(""1"")) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value passInclusion4() { + if (ItpcUtils.isBlank(getSystemicTher()) || !getSystemicTher().equals(""1"")) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value passInclusion4a() { + try { + Integer daysBetween = Integer.parseInt(this.getTimeBtwSurgTamox()); + if (daysBetween<182 && this.getFirstAdjEndoTher().equals(""1"")) { + return Value.Yes; + } + else { + return Value.No; + } + } + catch (NumberFormatException ex) { + if (!ItpcUtils.isBlank(this.getFirstAdjEndoTher()) && !ItpcUtils.isBlank(this.getTimeBtwSurgTamox())) { + if (this.getFirstAdjEndoTher().equals(""1"") + && (this.getTimeBtwSurgTamox().equalsIgnoreCase(""< 6 weeks"") + || this.getTimeBtwSurgTamox().equalsIgnoreCase(""< 6 months"") + || this.getTimeBtwSurgTamox().equalsIgnoreCase(""< 90 days"") + || this.getTimeBtwSurgTamox().equalsIgnoreCase(""28-42""))) { + return Value.Yes; + } + else { + return Value.No; + } + } + else { + return Value.No; + } + } + } + + public Value passInclusion4b() { + if (this.getDuration() != null && this.getDuration().equals(""0"")) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value passInclusion4c() { + if (this.getTamoxDose() != null && this.getTamoxDose().equals(""0"")) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value passInclusion5() { + if (getChemotherapy() != null && getChemotherapy().equals(""0"")) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value passInclusion6() { + if (this.getHormoneTherapy() == null || !this.getHormoneTherapy().equals(""1"")) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value passInclusion7() { + Value inclusion = Value.No; + + List passingBloodTimings = Arrays.asList(""1"",""2"",""7""); + List passingTumorTimings = Arrays.asList(""1""); + + if (getSampleSources().isEmpty() || (getSampleSources().size()==1 && getSampleSources().contains(SampleSource.UNKNOWN))) { + return inclusion; + } + + if (isSampleSourceTumor() && isSampleSourceBlood()) { + logger.warn(""Sample is marked as both blood and tumor for ""+getSubjectId()); + } + + if (isSampleSourceBlood()) { + if (passingBloodTimings.contains(getBloodSource())) { + inclusion = Value.Yes; + } + } + if (isSampleSourceTumor()) { + if (passingTumorTimings.contains(getTumorSource())) { + inclusion = Value.Yes; + } + } + return inclusion; + } + + public Value passInclusion8() { + if (this.getFollowup() == null || !this.getFollowup().equals(""2"")) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value passInclusion9() { + if (!this.getGenotypeFinal().isUncertain()) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value include() { + if (passInclusion1() == Value.Yes + && passInclusion2a() == Value.Yes + && passInclusion2b() == Value.Yes + && passInclusion3() == Value.Yes + && passInclusion4() == Value.Yes + && passInclusion4a() == Value.Yes + && passInclusion4b() == Value.Yes + && passInclusion4c() == Value.Yes + && passInclusion5() == Value.Yes + && passInclusion6() == Value.Yes + && passInclusion7() == Value.Yes + && passInclusion8() == Value.Yes + && passInclusion9() == Value.Yes) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value includeCrit1() { + if (passInclusion1() == Value.Yes + && passInclusion2a() == Value.Yes + && passInclusion3() == Value.Yes + && passInclusion4b() == Value.Yes + && passInclusion4c() == Value.Yes + && passInclusion5() == Value.Yes + && passInclusion6() == Value.Yes + && passInclusion8() == Value.Yes + && passInclusion9() == Value.Yes + && excludeSummary()==Value.No) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value includeCrit2() { + if (passInclusion2a() == Value.Yes + && passInclusion3() == Value.Yes + && passInclusion4c() == Value.Yes + && passInclusion5() == Value.Yes + && passInclusion6() == Value.Yes + && passInclusion9() == Value.Yes + && excludeSummary()==Value.No) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value includeCrit3() { + if (excludeSummary()==Value.No) { + return Value.Yes; + } + else { + return Value.No; + } + } + + /** + * Same as include() but disregards inclusion 4a. This is used for analysis to see if 4a is causing many records to + * be removed. + * @return Value of whether the subject should be included + */ + public Value includeWo4a() { + if (passInclusion1() == Value.Yes + && passInclusion2a() == Value.Yes + && passInclusion2b() == Value.Yes + && passInclusion3() == Value.Yes + && passInclusion4() == Value.Yes + && passInclusion4b() == Value.Yes + && passInclusion4c() == Value.Yes + && passInclusion5() == Value.Yes + && passInclusion6() == Value.Yes + && passInclusion7() == Value.Yes + && passInclusion8() == Value.Yes + && passInclusion9() == Value.Yes) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public Value exclude1() { + if (getAdditionalCancer() == Value.Yes + && (ItpcUtils.isBlank(getAddCxIpsilateral()) || getAddCxIpsilateral().equals(""0"")) + && (ItpcUtils.isBlank(getAddCxDistantRecur()) || getAddCxDistantRecur().equals(""0"")) + && (ItpcUtils.isBlank(getAddCxContralateral()) || getAddCxContralateral().equals(""0"")) + && (ItpcUtils.isBlank(getAddCxSecondInvasive()) || getAddCxSecondInvasive().equals(""0"")) + ) { + return Value.Yes; + } + else if ((getAdditionalCancer() == Value.No || getAdditionalCancer() == Value.Unknown) + && (!(ItpcUtils.isBlank(getAddCxIpsilateral()) || getAddCxIpsilateral().equals(""0"")) + || !(ItpcUtils.isBlank(getAddCxDistantRecur()) || getAddCxDistantRecur().equals(""0"")) + || !(ItpcUtils.isBlank(getAddCxContralateral()) || getAddCxContralateral().equals(""0"")) + || !(ItpcUtils.isBlank(getAddCxSecondInvasive()) || getAddCxSecondInvasive().equals(""0""))) + ) { + return Value.Yes; + } + else { + return Value.No; + } + } + + // joan suggestion 1 + public Value exclude4() { + if ((getAdditionalCancer()==Value.Yes || getPatientDied()==Value.Yes) && !ItpcUtils.isBlank(getDiseaseFreeSurvivalTime())) { + return Value.Yes; + } + return Value.No; + } + + // joan suggestion 3 + public Value exclude5() { + if (getPatientDied()==Value.Yes && !ItpcUtils.isBlank(getSurvivalNotDied())) { + return Value.Yes; + } + return Value.No; + } + + // joan suggestion 5 + public Value exclude6() { + Integer dfst = parseDays(getDiseaseFreeSurvivalTime()); + Integer lde = parseDays(getAddCxLastEval()); + Integer snd = parseDays(getSurvivalNotDied()); + + if (dfst != null && lde != null && dfstsnd) { + return Value.Yes; + } + + return Value.No; + } + + public Value excludeSummary() { + if (exclude1() == Value.Yes + || exclude4() == Value.Yes + || exclude6() == Value.Yes + || exclude5() == Value.Yes) { + return Value.Yes; + } + else { + return Value.No; + } + } + + public String getMenoStatus() { + return m_menoStatus; + } + + public void setMenoStatus(String menoStatus) { + m_menoStatus = menoStatus; + } + + public String getSubjectId() { + return m_subjectId; + } + + public void setSubjectId(String subjectId) { + m_subjectId = subjectId; + } + + public String getProjectSite() { + return m_projectSite; + } + + public void setProjectSite(String projectSite) { + m_projectSite = projectSite; + } + + public String getAge() { + return m_age; + } + + public void setAge(String age) { + m_age = age; + } + + public String getGender() { + return m_gender; + } + + public void setGender(String gender) { + m_gender = gender; + } + + public String getMetastatic() { + return m_metastatic; + } + + public void setMetastatic(String metastatic) { + m_metastatic = metastatic; + } + + public String getPriorHistory() { + return m_priorHistory; + } + + public void setPriorHistory(String priorHistory) { + m_priorHistory = priorHistory; + } + + public String getPriorDcis() { + return m_priorDcis; + } + + public void setPriorDcis(String priorDcis) { + m_priorDcis = priorDcis; + } + + public String getErStatus() { + return m_erStatus; + } + + public void setErStatus(String erStatus) { + m_erStatus = erStatus; + } + + public String getSystemicTher() { + return m_systemicTher; + } + + public void setSystemicTher(String systemicTher) { + m_systemicTher = systemicTher; + } + + public String getTimeBtwSurgTamox() { + return m_timeBtwSurgTamox; + } + + public void setTimeBtwSurgTamox(String timeBtwSurgTamox) { + m_timeBtwSurgTamox = timeBtwSurgTamox; + } + + public String getFirstAdjEndoTher() { + return m_firstAdjEndoTher; + } + + public void setFirstAdjEndoTher(String firstAdjEndoTher) { + m_firstAdjEndoTher = firstAdjEndoTher; + } + + public String getDuration() { + return m_duration; + } + + public void setDuration(String duration) { + m_duration = duration; + } + + public String getTamoxDose() { + return m_tamoxDose; + } + + public void setTamoxDose(String tamoxDose) { + m_tamoxDose = tamoxDose; + } + + public String getChemotherapy() { + return m_chemotherapy; + } + + public void setChemotherapy(String chemotherapy) { + m_chemotherapy = chemotherapy; + } + + public String getHormoneTherapy() { + return m_hormoneTherapy; + } + + public void setHormoneTherapy(String hormoneTherapy) { + m_hormoneTherapy = hormoneTherapy; + } + + public String getTumorSource() { + return m_tumorSource; + } + + public void setTumorSource(String tumorSource) { + m_tumorSource = tumorSource; + } + + public String getBloodSource() { + return m_bloodSource; + } + + public void setBloodSource(String bloodSource) { + m_bloodSource = StringUtils.replace(bloodSource,""*"",""""); + } + + public String getFollowup() { + return m_followup; + } + + public void setFollowup(String followup) { + m_followup = followup; + } + + public Genotype getGenotypeLimited() { + return m_genotypeLimited; + } + + public void setGenotypeLimited(Genotype genotypeLimited) { + m_genotypeLimited = genotypeLimited; + } + + public String getRace() { + return m_race; + } + + public void setRace(String race) { + m_race = race; + } + + public String getTumorDimension() { + return m_tumorDimension; + } + + public void setTumorDimension(String tumorDimension) { + m_tumorDimension = tumorDimension; + } + + protected boolean isValidTumorDimension() { + boolean valid = true; + + if (StringUtils.trimToNull(getTumorDimension()) != null) { + String tumorDimension = getTumorDimension().toLowerCase(); + + valid = !(tumorDimension.contains(""dcis"") + || tumorDimension.contains(""lcis"") + || tumorDimension.contains(""atypical lobular hyperplasia"") + || tumorDimension.contains(""taking for high risk"")); + } + + return valid; + } + + public Value getAdditionalCancer() { + return m_additionalCancer; + } + + public void setAdditionalCancer(Value additionalCancer) { + m_additionalCancer = additionalCancer; + } + + public void setAdditionalCancer(String additionalCancer) { + if (additionalCancer == null) { + m_additionalCancer = Value.Unknown; + } + else if (additionalCancer.equals(""1"")) { + m_additionalCancer = Value.Yes; + } + else if (additionalCancer.equals(""2"")) { + m_additionalCancer = Value.No; + } + else { + m_additionalCancer = Value.Unknown; + } + } + + public String getAddCxIpsilateral() { + return m_addCxIpsilateral; + } + + public void setAddCxIpsilateral(String addCxIpsilateral) { + m_addCxIpsilateral = addCxIpsilateral; + } + + public String getAddCxDistantRecur() { + return m_addCxDistantRecur; + } + + public void setAddCxDistantRecur(String addCxDistantRecur) { + m_addCxDistantRecur = addCxDistantRecur; + } + + public String getAddCxContralateral() { + return m_addCxContralateral; + } + + public void setAddCxContralateral(String addCxContralateral) { + m_addCxContralateral = addCxContralateral; + } + + public String getAddCxSecondInvasive() { + return m_addCxSecondInvasive; + } + + public void setAddCxSecondInvasive(String addCxSecondInvasive) { + m_addCxSecondInvasive = addCxSecondInvasive; + } + + public String getAddCxLastEval() { + return m_addCxLastEval; + } + + public void setAddCxLastEval(String addCxLastEval) { + m_addCxLastEval = addCxLastEval; + } + + public String getFirstDiseaseEventCalc() { + return getFirstEventData()[0]; + } + + public String getDiagToEventDaysCalc() { + return getFirstEventData()[1]; + } + + /** + * Returns information ont eh first disease event in a String array + * @return String array: element 0: code of the first disease event, element 1: days to first disease event + */ + public String[] getFirstEventData() { + String code = ""0""; + + if (getAdditionalCancer()==Value.Yes) { + List eventCodes = Lists.newArrayList(); + + int days = 999999; + if (!isInvasive(getAddCxContralateral()) || !(ItpcUtils.isBlank(getAddCxContralateral()) || getAddCxContralateral().equals(""0""))) { + eventCodes.add(""3""); + Integer contraDays = parseDays(getAddCxContralateral()); + if (contraDays != null && contraDays0) { + return new String[]{code, Integer.toString(days)}; + } + else { + String events = eventCodes.isEmpty() ? Value.Unknown.toString() : Joiner.on(""; "").join(eventCodes); + return new String[]{events, Value.Unknown.toString()}; + } + } + else if (getAdditionalCancer()==Value.No && getPatientDied()==Value.Yes) { + Integer deathDays = parseDays(getDaysDiagtoDeath()); + if (deathDays != null && deathDays>0) { + return new String[]{""5"", String.valueOf(deathDays)}; + } + } + else if (getAdditionalCancer()==Value.No && getPatientDied()==Value.No) { + Integer days = parseDays(getAddCxLastEval()); + if (days != null && days>0) { + return new String[]{""0"", String.valueOf(days)}; + } + else { + return new String[]{""0"", Value.Unknown.toString()}; + } + } + return new String[]{Value.Unknown.toString(), Value.Unknown.toString()}; + } + + private Integer parseDays(String daysString) { + Integer daysInt = null; + + if (!ItpcUtils.isBlank(daysString)) { + String workingString = daysString; + workingString = workingString.replaceAll("";"",""""); + workingString = workingString.replaceAll(""NI"",""""); + workingString = StringUtils.trim(workingString); + + try { + daysInt = Integer.valueOf(workingString); + } catch (NumberFormatException ex) { + return -1; + } + } + + return daysInt; + } + + public String getDaysDiagtoDeath() { + return m_daysDiagtoDeath; + } + + public void setDaysDiagtoDeath(String daysDiagtoDeath) { + m_daysDiagtoDeath = daysDiagtoDeath; + } + + public Value getPatientDied() { + return m_patientDied; + } + + public void setPatientDied(Value patientDied) { + m_patientDied = patientDied; + } + + public void setPatientDied(String died) { + String patientDied = died.trim(); + if (patientDied == null) { + m_patientDied = Value.Unknown; + } + else if (patientDied.equals(""2"")) { + m_patientDied = Value.Yes; + } + else if (patientDied.equals(""1"")) { + m_patientDied = Value.No; + } + else { + m_patientDied = Value.Unknown; + } + } + + public String getDiseaseFreeSurvivalTime() { + return m_diseaseFreeSurvivalTime; + } + + public void setDiseaseFreeSurvivalTime(String diseaseFreeSurvivalTime) { + m_diseaseFreeSurvivalTime = diseaseFreeSurvivalTime; + } + + public String getSurvivalNotDied() { + return m_survivalNotDied; + } + + public void setSurvivalNotDied(String survivalNotDied) { + m_survivalNotDied = survivalNotDied; + } + + public void addMedStatus(Med med, Value value) { + m_medStatus.put(med, value); + } + + public Value hasMed(Med med) { + if (med != null && m_medStatus.keySet().contains(med)) { + return m_medStatus.get(med); + } + else { + return Value.Unknown; + } + } + + public boolean isInvasive(String days) { + return days != null && !days.contains(""NI""); + } + + public String getBreastCancerFreeInterval() { + SortedSet freeIntervals = Sets.newTreeSet(); + + if (getCauseOfDeath()!=null && getCauseOfDeath().equals(""1"")) { + freeIntervals.add(parseDays(getDaysDiagtoDeath())); + } + + if (!ItpcUtils.isBlank(getAddCxIpsilateral())) { + Integer ipsiDays = parseDays(getAddCxIpsilateral()); + if (ipsiDays>0) { + freeIntervals.add(ipsiDays); + } + } + if (!ItpcUtils.isBlank(getAddCxDistantRecur())) { + Integer days = parseDays(getAddCxDistantRecur()); + if (days>0) { + freeIntervals.add(days); + } + } + if (!ItpcUtils.isBlank(getAddCxContralateral())) { + Integer days = parseDays(getAddCxContralateral()); + if (days>0) { + freeIntervals.add(days); + } + } + + if (!freeIntervals.isEmpty()) { + return Integer.toString(freeIntervals.first()); + } + else { + return """"; + } + } + + public String getCauseOfDeath() { + return m_causeOfDeath; + } + + public void setCauseOfDeath(String causeOfDeath) { + m_causeOfDeath = causeOfDeath; + } + + public Value getDcisStatus() { + return m_dcisStatus; + } + + public void setDcisStatus(Value dcisStatus) { + m_dcisStatus = dcisStatus; + } + + public String makeSqlInsert() { + String insertStmt = ""insert into tamoxdata(subjectid,"" + + ""projectid,"" + + ""ageatdiagnosis,"" + + ""menostatusatdx,"" + + ""maxtumordim,"" + + ""numposnodes,"" + + ""grading,"" + + ""erstatus,"" + + ""pgrstatus,"" + + ""radiotherapy,"" + + ""cyp2d6_1,"" + + ""cyp2d6_2,"" + + ""crit1,"" + + ""crit2,"" + + ""crit3,"" + + ""genosource) values (%s);""; + List fields = Lists.newArrayList(); + + fields.add(""'""+getSubjectId()+""'""); + fields.add(""'""+getProjectSite()+""'""); + fields.add(""'""+getAge()+""'""); + fields.add(""'""+getMenoStatus()+""'""); + fields.add(""'""+getTumorDimension()+""'""); + fields.add(""'""+getNumPositiveNodes()+""'""); + fields.add(""'""+getTumorGrading()+""'""); + fields.add(""'""+getErStatus()+""'""); + fields.add(""'""+getProgesteroneReceptor()+""'""); + fields.add(""'""+getRadiotherapy()+""'""); + fields.add(""'""+getGenotypeFinal().get(0)+""'""); + fields.add(""'""+getGenotypeFinal().get(1)+""'""); + fields.add(""'""+includeCrit1()+""'""); + fields.add(""'""+includeCrit2()+""'""); + fields.add(""'""+includeCrit3()+""'""); + fields.add(""'""+Joiner.on("","").join(getSampleSources())+""'""); + + return String.format(insertStmt, Joiner.on("","").join(fields)); + } + + public String getNumPositiveNodes() { + return m_numPositiveNodes; + } + + public void setNumPositiveNodes(String m_numPositiveNodes) { + this.m_numPositiveNodes = m_numPositiveNodes; + } + + public String getTumorGrading() { + return m_tumorGrading; + } + + public void setTumorGrading(String m_tumorGrading) { + this.m_tumorGrading = m_tumorGrading; + } + + public String getProgesteroneReceptor() { + return progesteroneReceptor; + } + + public void setProgesteroneReceptor(String progesteroneReceptor) { + this.progesteroneReceptor = progesteroneReceptor; + } + + public String getRadiotherapy() { + return radiotherapy; + } + + public void setRadiotherapy(String radiotherapy) { + this.radiotherapy = radiotherapy; + } + + public Set getSampleSources() { + return m_sampleSources; + } + + public void addSampleSource(SampleSource sampleSource) { + m_sampleSources.add(sampleSource); + } + + public boolean isSampleSourceBlood() { + return getSampleSources()!=null && ( + getSampleSources().contains(SampleSource.BLOOD) + || getSampleSources().contains(SampleSource.BUCCAL)); + } + + public boolean isSampleSourceTumor() { + return getSampleSources()!=null && ( + getSampleSources().contains(SampleSource.TUMOR_FFP) + || getSampleSources().contains(SampleSource.TUMOR_FROZEN) + || getSampleSources().contains(SampleSource.NORMAL_PARAFFIN)); + } + + public Genotype getGenotypeOther() { + return m_genotypeOther; + } + + public void setGenotypeOther(Genotype genotype) { + m_genotypeOther = genotype; + } + + public void setGenotypeOther(String alleles) { + try { + this.setGenotypeOther(processGenotype(alleles)); + } + catch (Exception ex) { + logger.warn(""Cannot parse amplichip genotype: "" + alleles); + } + } + + enum Deletion {Unknown, None, Hetero, Homo} + + public enum SampleSource {TUMOR_FFP, BLOOD, BUCCAL, TUMOR_FROZEN, NORMAL_PARAFFIN, UNKNOWN} +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/org/pharmgkb/ItpcSheet.java",".java","35612","794","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package org.pharmgkb; + +import com.google.common.base.Joiner; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.*; +import util.*; + +import java.io.*; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + + +/** + * Created by IntelliJ IDEA. User: whaleyr Date: Jun 18, 2010 Time: 10:07:11 AM To change this template use File | + * Settings | File Templates. + */ +public class ItpcSheet implements Iterator { + public static final String SHEET_NAME = ""Combined_Data""; + private static final Logger sf_logger = Logger.getLogger(ItpcSheet.class); + + private File inputFile = null; + + private Sheet m_dataSheet = null; + private int m_rowIndex = -1; + private List m_currentDataRow = null; + + private CellStyle styleHighlight = null; + + protected int subjectId = -1; + protected int projectSiteIdx = -1; + protected int ageIdx = -1; + protected int genderIdx = -1; + protected int raceIdx = -1; + protected int menoStatusIdx = -1; + protected int metastaticIdx = -1; + protected int erStatusIdx = -1; + protected int durationIdx = -1; + protected int tamoxDoseIdx = -1; + protected int tumorSourceIdx = -1; + protected int bloodSourceIdx = -1; + protected int priorHistoryIdx = -1; + protected int priorSitesIdx = -1; + protected int priorDcisIdx = -1; + protected int chemoIdx = -1; + protected int hormoneIdx = -1; + protected int systemicTherIdx = -1; + protected int followupIdx = -1; + protected int timeBtwSurgTamoxIdx = -1; + protected int firstAdjEndoTherIdx = -1; + protected int projectNotesIdx = -1; + protected int tumorDimensionIdx = -1; + protected int numPositiveNodesIdx = -1; + protected int tumorGradingIdx = -1; + protected int pgrStatusIdx = -1; + protected int radioIdx = -1; + protected int additionalCancerIdx = -1; + protected int addCxIpsilateralIdx = -1; + protected int addCxDistantRecurIdx = -1; + protected int addCxContralateralIdx = -1; + protected int addCxSecondInvasiveIdx = -1; + protected int addCxLastEvalIdx = -1; + protected int daysDiagToDeathIdx = -1; + protected int patientDiedIdx = -1; + protected int diseaseFreeSurvivalTimeIdx = -1; + protected int survivalNotDiedIdx = -1; + protected int causeOfDeathIdx = -1; + + protected int fluoxetineCol = -1; + protected int paroxetineCol = -1; + protected int quinidienCol = -1; + protected int buproprionCol = -1; + protected int duloxetineCol = -1; + protected int cimetidineCol = -1; + protected int sertralineCol = -1; + protected int citalopramCol = -1; + + protected int rs4986774idx = -1; + protected int rs1065852idx = -1; + protected int rs3892097idx = -1; + protected int star5idx = -1; + protected int rs5030655idx = -1; + protected int rs16947idx = -1; + protected int rs28371706idx = -1; + protected int rs28371725idx = -1; + protected Set sampleSourceIdxs = Sets.newHashSet(); + protected static final Set genotypeSourceHeaderTitles = Sets.newHashSet(); + static { + genotypeSourceHeaderTitles.add(""rs4986774 genotyping source""); + genotypeSourceHeaderTitles.add(""rs1065852 genotyping source""); + genotypeSourceHeaderTitles.add(""rs3892097 genotyping source""); + genotypeSourceHeaderTitles.add(""CYP2D6*5 genotyping source""); + genotypeSourceHeaderTitles.add(""rs5030655 genotyping source""); + genotypeSourceHeaderTitles.add(""rs16947 genotyping source""); + genotypeSourceHeaderTitles.add(""rs28371706 genotyping source""); + genotypeSourceHeaderTitles.add(""rs28371725 genotyping source""); + } + + protected int amplichipidx = -1; + protected int otherGenoIdx = -1; + + protected int allele1finalIdx = -1; + protected int allele2finalIdx = -1; + protected int genotypeIdx = -1; + protected int genoMetabStatusIdx = -1; + protected int weakIdx = -1; + protected int potentIdx = -1; + protected int metabStatusIdx = -1; + protected int includeCrit1Idx = -1; + protected int includeCrit2Idx = -1; + protected int includeCrit3Idx = -1; + protected int scoreIdx = -1; + protected int exclude1Idx = -1; + protected int exclude2Idx = -1; + protected int exclude3Idx = -1; + protected int exclude4Idx = -1; + protected int newFirstDiseaseEventIdx = -1; + protected int diagToEventCalcIdx = -1; + + protected int incAgeIdx = -1; + protected int incNonmetaIdx = -1; + protected int incPriorHistIdx = -1; + protected int incErPosIdx = -1; + protected int incSysTherIdx = -1; + protected int incAdjTamoxIdx = -1; + protected int incDurationIdx = -1; + protected int incTamoxDoseIdx = -1; + protected int incChemoIdx = -1; + protected int incHormoneIdx = -1; + protected int incDnaCollectionIdx = -1; + protected int incFollowupIdx = -1; + protected int incGenoDataAvailIdx = -1; + protected int bfciIdx = -1; + protected int genoSourceIdx = -1; + + private PoiWorksheetIterator m_sampleIterator = null; + + protected static final Map sf_medPatterns = Maps.newHashMap(); + static { + sf_medPatterns.put(Pattern.compile(""Fluoxetine""), Med.Fluoxetine); + sf_medPatterns.put(Pattern.compile(""Paroxetine""), Med.Paroxetine); + sf_medPatterns.put(Pattern.compile(""Quinidine""), Med.Quinidine); + sf_medPatterns.put(Pattern.compile(""Buproprion""), Med.Buproprion); + sf_medPatterns.put(Pattern.compile(""Duloxetine""), Med.Duloxetine); + sf_medPatterns.put(Pattern.compile(""Sertraline""), Med.Sertraline); + sf_medPatterns.put(Pattern.compile(""Diphenhydramine""), Med.Diphenhydramine); + sf_medPatterns.put(Pattern.compile(""Thioridazine""), Med.Thioridazine); + sf_medPatterns.put(Pattern.compile(""Amiodarone""), Med.Amiodarone); + sf_medPatterns.put(Pattern.compile(""Trazodone""), Med.Trazodone); + sf_medPatterns.put(Pattern.compile(""Cimetidine""), Med.Cimetidine); + sf_medPatterns.put(Pattern.compile(""Venlafaxine""), Med.Venlafaxine); + sf_medPatterns.put(Pattern.compile(""Citalopram""), Med.Citalopram); + sf_medPatterns.put(Pattern.compile(""Escitalopram""), Med.Escitalopram); + } + protected Map medIdx = Maps.newHashMap(); + + /** + * Constructor for an ITPC data file + *
+ * Expectations for file parameter: + *
    + *
  1. file is an Excel .XLS formatted spreadsheet
  2. + *
  3. there is a sheet in the file called ""Combined_Data""
  4. + *
  5. the sheet has the first row as column headers
  6. + *
  7. the sheet has the second row as column legends
  8. + *
+ * After this has been initialized, samples can be gathered by using the getSampleIterator method + * @param file an Excel .XLS file + * @param doHighlighting highlight changed cells in the output file + * @throws Exception can occur from file I/O + */ + public ItpcSheet(File file, boolean doHighlighting) throws Exception { + if (file == null || !(file.getName().endsWith("".xls"") || file.getName().endsWith("".xlsx""))) { + throw new Exception(""File not in right format: "" + file); + } + + inputFile = file; + InputStream inputFileStream = null; + sf_logger.info(""Using input file: "" + inputFile); + + try { + inputFileStream = new FileInputStream(inputFile); + Workbook inputWorkbook = WorkbookFactory.create(inputFileStream); + Sheet inputSheet = inputWorkbook.getSheet(SHEET_NAME); + if (inputSheet == null) { + throw new Exception(""Cannot find worksheet named "" + SHEET_NAME); + } + + m_dataSheet = inputSheet; + if (doHighlighting) { + doHighlighting(); + } + + parseColumnIndexes(); + + PoiWorksheetIterator sampleIterator = new PoiWorksheetIterator(m_dataSheet); + setSampleIterator(sampleIterator); + skipNext(); // skip header row + skipNext(); // skip legend row + } + catch (Exception ex) { + throw new Exception(""Error initializing ITPC Sheet"", ex); + } + finally { + if (inputFileStream != null) { + IOUtils.closeQuietly(inputFileStream); + } + } + } + + protected void parseColumnIndexes() throws Exception { + if (sf_logger.isDebugEnabled()) { + sf_logger.debug(""Parsing column indexes and headings""); + } + + Row headerRow = m_dataSheet.getRow(0); + Iterator headerCells = headerRow.cellIterator(); + + while(headerCells.hasNext()) { + Cell headerCell = headerCells.next(); + String header = headerCell.getStringCellValue(); + int idx = headerCell.getColumnIndex(); + + for (Pattern pattern : sf_medPatterns.keySet()) { + if (pattern.matcher(header).matches()) { + medIdx.put(sf_medPatterns.get(pattern), idx); + } + } + + if (StringUtils.isNotEmpty(header)) { + header = header.trim().toLowerCase(); + } + if (header.contains(""subject id"")) { + subjectId = idx; + } else if (header.equalsIgnoreCase(""project site"")) { + projectSiteIdx = idx; + } else if (header.contains(""gender"")) { + genderIdx = idx; + } else if (header.contains(""age at diagnosis"")) { + ageIdx = idx; + } else if (header.contains(""race"") && header.contains(""omb"")) { + raceIdx = idx; + } else if (header.equalsIgnoreCase(""Metastatic Disease at Primary Disease"")) { + metastaticIdx = idx; + } else if (header.contains(""maximum dimension of tumor"")) { + tumorDimensionIdx = idx; + } else if (header.equalsIgnoreCase(""Number of Positive Nodes"")) { + numPositiveNodesIdx = idx; + } else if (header.equalsIgnoreCase(""Nottingham Grade"")) { + tumorGradingIdx = idx; + } else if (header.equalsIgnoreCase(""Progesterone Receptor"")) { + pgrStatusIdx = idx; + } else if (header.equalsIgnoreCase(""Radiation Treatment"")) { + radioIdx = idx; + } else if (header.contains(""menopause status at diagnosis"")) { + menoStatusIdx = idx; + } else if (header.equals(""estrogen receptor"")) { + erStatusIdx = idx; + } else if (header.contains(""intended tamoxifen duration"")) { + durationIdx = idx; + } else if (header.contains(""intended tamoxifen dose"")) { + tamoxDoseIdx = idx; + } else if (header.contains(""if tumor or tissue was dna source"")) { + tumorSourceIdx = idx; + } else if (header.contains(""blood or buccal cells"")) { + bloodSourceIdx = idx; + } else if (header.contains(""prior history of cancer"")) { + priorHistoryIdx = idx; + } else if (header.contains(""sites of prior cancer"")) { + priorSitesIdx = idx; + } else if (header.contains(""prior invasive breast cancer or dcis"")) { + priorDcisIdx = idx; + } else if (header.equalsIgnoreCase(""chemotherapy"")) { + chemoIdx = idx; + } else if (header.contains(""additional hormone or other treatment after breast surgery?"")) { + hormoneIdx = idx; + } else if (header.contains(""systemic therapy prior to surgery?"")) { + systemicTherIdx = idx; + } else if (header.contains(""annual physical exam after breast cancer surgery"")) { + followupIdx = idx; + } else if (header.contains(""time between definitive breast cancer surgery"")) { + timeBtwSurgTamoxIdx = idx; + } else if (header.contains(""first adjuvant endocrine therapy"")) { + firstAdjEndoTherIdx = idx; + } else if (header.contains(""project notes"")) { + projectNotesIdx = idx; + } else if (header.equalsIgnoreCase(""other cyp2d6 genotyping"")) { + otherGenoIdx = idx; + } else if (header.contains(""rs4986774"") && !header.contains(""source"")) { + rs4986774idx = idx; + } else if (header.contains(""rs1065852"") && !header.contains(""source"")) { + rs1065852idx = idx; + } else if (header.contains(""rs3892097"") && !header.contains(""source"")) { + rs3892097idx = idx; + } else if (header.contains(""rs5030655"") && !header.contains(""source"")) { + rs5030655idx = idx; + } else if (header.contains(""rs16947"") && !header.contains(""source"")) { + rs16947idx = idx; + } else if (header.contains(""rs28371706"") && !header.contains(""source"")) { + rs28371706idx = idx; + } else if (header.contains(""rs28371725"") && !header.contains(""source"")) { + rs28371725idx = idx; + } else if (genotypeSourceHeaderTitles.contains(header)) { + sampleSourceIdxs.add(idx); + } else if (header.contains(""cyp2d6 *5"") && !header.contains(""source"")) { + star5idx = idx; + } else if (header.contains(""fluoxetine"")) { + fluoxetineCol = idx; + } else if (header.contains(""paroxetine"")) { + paroxetineCol = idx; + } else if (header.contains(""quinidine"")) { + quinidienCol = idx; + } else if (header.contains(""buproprion"")) { + buproprionCol = idx; + } else if (header.contains(""duloxetine"")) { + duloxetineCol = idx; + } else if (header.contains(""cimetidine"")) { + cimetidineCol = idx; + } else if (header.contains(""sertraline"")) { + sertralineCol = idx; + } else if(header.equals(""citalopram"")) { + citalopramCol = idx; + } else if (header.contains(""amplichip call"")) { + amplichipidx = idx; + } else if (header.equalsIgnoreCase(""Additional cancer?"")) { // column BP + additionalCancerIdx = idx; + } else if (header.contains(""time from diagnosis to ipsilateral local or regional recurrence"")) { // column BR + addCxIpsilateralIdx = idx; + } else if (header.contains(""time from diagnosis to distant recurrence"")) { // column BS + addCxDistantRecurIdx = idx; + } else if (header.contains(""time from diagnosis to contralateral breast cancer"")) { // column BT + addCxContralateralIdx = idx; + } else if (header.contains(""time from diagnosis to second primary invasive cancer"")) { // column BU + addCxSecondInvasiveIdx = idx; + } else if (header.contains(""time from diagnosis to date of last disease evaluation"")) { // column BX + addCxLastEvalIdx = idx; + } else if (header.equalsIgnoreCase(""Time from diagnosis until death if the patient has died"")) { // column CE + daysDiagToDeathIdx = idx; + } else if (header.equalsIgnoreCase(""Has the patient died?"")) { // column CD + patientDiedIdx = idx; + } else if (header.contains(""enter disease-free survival time"")) { // column BO + diseaseFreeSurvivalTimeIdx = idx; + } else if (header.contains(""survival time if patient has not died"")) { // column CI + survivalNotDiedIdx = idx; + } else if (header.equalsIgnoreCase(""Cause of death if the patient has died"")) { + causeOfDeathIdx = idx; + } + } + + // new columns to add to the end of the template + int startPgkbColsIdx = projectNotesIdx+1; + + newFirstDiseaseEventIdx = startPgkbColsIdx; + diagToEventCalcIdx = startPgkbColsIdx + 1; + allele1finalIdx = startPgkbColsIdx + 2; + allele2finalIdx = startPgkbColsIdx + 3; + genotypeIdx = startPgkbColsIdx + 4; + genoMetabStatusIdx = startPgkbColsIdx + 5; + weakIdx = startPgkbColsIdx + 6; + potentIdx = startPgkbColsIdx + 7; + scoreIdx = startPgkbColsIdx + 8; + metabStatusIdx = startPgkbColsIdx + 9; + + incAgeIdx = startPgkbColsIdx + 10; + incNonmetaIdx = startPgkbColsIdx + 11; + incPriorHistIdx = startPgkbColsIdx + 12; + incErPosIdx = startPgkbColsIdx + 13; + incSysTherIdx = startPgkbColsIdx + 14; + incAdjTamoxIdx = startPgkbColsIdx + 15; + incDurationIdx = startPgkbColsIdx + 16; + incTamoxDoseIdx = startPgkbColsIdx + 17; + incChemoIdx = startPgkbColsIdx + 18; + incHormoneIdx = startPgkbColsIdx + 19; + incDnaCollectionIdx = startPgkbColsIdx + 20; + incFollowupIdx = startPgkbColsIdx + 21; + incGenoDataAvailIdx = startPgkbColsIdx + 22; + + exclude1Idx = startPgkbColsIdx + 23; + exclude2Idx = startPgkbColsIdx + 24; + exclude3Idx = startPgkbColsIdx + 25; + exclude4Idx = startPgkbColsIdx + 26; + + includeCrit1Idx = startPgkbColsIdx + 27; + includeCrit2Idx = startPgkbColsIdx + 28; + includeCrit3Idx = startPgkbColsIdx + 29; + + bfciIdx = startPgkbColsIdx + 30; + genoSourceIdx = startPgkbColsIdx + 31; + + writeCellTitles(headerRow); + styleCells(headerRow, startPgkbColsIdx, headerRow.getCell(0).getCellStyle()); + + // write the description row + Row descrRow = m_dataSheet.getRow(1); + writeCellDescr(descrRow); + styleCells(descrRow, startPgkbColsIdx, descrRow.getCell(0).getCellStyle()); + } + + private void writeCellTitles(Row headerRow) { + ExcelUtils.writeCell(headerRow, newFirstDiseaseEventIdx, ""First Disease Event (calculated)""); + ExcelUtils.writeCell(headerRow, diagToEventCalcIdx, ""Time from Primary Diagnosis to First Disease Event (calculated)""); + + ExcelUtils.writeCell(headerRow, allele1finalIdx, ""CYP2D6 Allele 1 (Final)""); + ExcelUtils.writeCell(headerRow, allele2finalIdx, ""CYP2D6 Allele 2 (Final)""); + ExcelUtils.writeCell(headerRow, genotypeIdx, ""CYP2D6 Genotype (Final)""); + ExcelUtils.writeCell(headerRow, genoMetabStatusIdx, ""Metabolizer Status based on Genotypes only (Final)""); + ExcelUtils.writeCell(headerRow, weakIdx, ""Weak Drug (PharmGKB)""); + ExcelUtils.writeCell(headerRow, potentIdx, ""Potent Drug (PharmGKB)""); + ExcelUtils.writeCell(headerRow, scoreIdx, ""CYP2D6 Genotype Score (Final)""); + ExcelUtils.writeCell(headerRow, metabStatusIdx, ""Metabolizer Status based on CYP2D6 Genotype Score (Final)""); + + ExcelUtils.writeCell(headerRow, incAgeIdx, ""Inc 1\nPostmenopausal""); + ExcelUtils.writeCell(headerRow, incNonmetaIdx, ""Inc 2a\nNon-metastatic invasive cancer""); + ExcelUtils.writeCell(headerRow, incPriorHistIdx, ""Inc 2b\nNo prior history of contralateral breast cancer""); + ExcelUtils.writeCell(headerRow, incErPosIdx, ""Inc 3\nER Positive""); + ExcelUtils.writeCell(headerRow, incSysTherIdx, ""Inc 4\nSystemic therapy prior to surgery""); + ExcelUtils.writeCell(headerRow, incAdjTamoxIdx, ""Inc 4a\nAdjuvant tamoxifen initiated within 6 months""); + ExcelUtils.writeCell(headerRow, incDurationIdx, ""Inc 4b\nTamoxifen duration intended 5 years""); + ExcelUtils.writeCell(headerRow, incTamoxDoseIdx, ""Inc 4c\nTamoxifen dose intended 20mg/day""); + ExcelUtils.writeCell(headerRow, incChemoIdx, ""Inc 5\nNo adjuvant chemotherapy""); + ExcelUtils.writeCell(headerRow, incHormoneIdx, ""Inc 6\nNo additional adjuvant hormonal therapy""); + ExcelUtils.writeCell(headerRow, incDnaCollectionIdx, ""Inc 7\nTiming of DNA Collection""); + ExcelUtils.writeCell(headerRow, incFollowupIdx, ""Inc 8\nAdequate follow-up""); + ExcelUtils.writeCell(headerRow, incGenoDataAvailIdx, ""Inc 9\nCYP2D6 *4 genotype data available for assessment""); + + ExcelUtils.writeCell(headerRow, exclude1Idx, ""Exclusion 1:\ntime of event unknown""); + ExcelUtils.writeCell(headerRow, exclude2Idx, ""Exclusion 2:\nDFST agrees with Additional Cancer and Patient Death""); + ExcelUtils.writeCell(headerRow, exclude3Idx, ""Exclusion 3:\nCheck survival time against Patient Death""); + ExcelUtils.writeCell(headerRow, exclude4Idx, ""Exclusion 4:\nDFST agrees with Additional Cancer and survival time""); + + ExcelUtils.writeCell(headerRow, includeCrit1Idx, ""Criterion 1""); + ExcelUtils.writeCell(headerRow, includeCrit2Idx, ""Criterion 2""); + ExcelUtils.writeCell(headerRow, includeCrit3Idx, ""Criterion 3""); + ExcelUtils.writeCell(headerRow, bfciIdx, ""BCFI(Breast-Cancer Free Interval)""); + ExcelUtils.writeCell(headerRow, genoSourceIdx, ""Genotyping Source""); + } + + private void writeCellDescr(Row descrRow) { + ExcelUtils.writeCell(descrRow, newFirstDiseaseEventIdx, ""none = 0, local/regional recurrence = 1, distant recurrence = 2, contralateral breast cancer = 3, other second non-breast primary = 4, death without recurrence, contralateral breast cancer or second non-breast primary cancer = 5, based on columns BR-BU and CD""); + ExcelUtils.writeCell(descrRow, diagToEventCalcIdx, ""time to the first of a local/regional/distant recurrence, contralateral breast disease or a second primary cancer, death without recurrence, or, if none of these, then time to last disease evaluation (days)""); + + ExcelUtils.writeCell(descrRow, allele1finalIdx, """"); + ExcelUtils.writeCell(descrRow, allele2finalIdx, """"); + ExcelUtils.writeCell(descrRow, genotypeIdx, """"); + ExcelUtils.writeCell(descrRow, genoMetabStatusIdx, ""Extensive (EM/EM, EM/UM, IM/UM, UM/UM); Intermediate (EM/PM, EM/IM, IM/IM, IM/PM, PM/UM); Poor (PM/PM); anything else is categorized as unknown""); + ExcelUtils.writeCell(descrRow, weakIdx, """"); + ExcelUtils.writeCell(descrRow, potentIdx, """"); + ExcelUtils.writeCell(descrRow, scoreIdx, ""The score of each allele added together""); + ExcelUtils.writeCell(descrRow, metabStatusIdx, ""Extensive, Intermediate, Poor, or Unknown""); + + ExcelUtils.writeCell(descrRow, incAgeIdx, """"); + ExcelUtils.writeCell(descrRow, incNonmetaIdx, """"); + ExcelUtils.writeCell(descrRow, incPriorHistIdx, """"); + ExcelUtils.writeCell(descrRow, incErPosIdx, """"); + ExcelUtils.writeCell(descrRow, incSysTherIdx, """"); + ExcelUtils.writeCell(descrRow, incAdjTamoxIdx, """"); + ExcelUtils.writeCell(descrRow, incDurationIdx, """"); + ExcelUtils.writeCell(descrRow, incTamoxDoseIdx, """"); + ExcelUtils.writeCell(descrRow, incChemoIdx, """"); + ExcelUtils.writeCell(descrRow, incHormoneIdx, """"); + ExcelUtils.writeCell(descrRow, incDnaCollectionIdx, """"); + ExcelUtils.writeCell(descrRow, incFollowupIdx, """"); + ExcelUtils.writeCell(descrRow, incGenoDataAvailIdx, """"); + + ExcelUtils.writeCell(descrRow, exclude1Idx, ""Column BP is Yes and all of BR-BU has no data or Column BP is No and one of BR-BU has data""); + ExcelUtils.writeCell(descrRow, exclude2Idx, ""Column BO has days and either Column BP is yes or Column CD is yes""); + ExcelUtils.writeCell(descrRow, exclude3Idx, ""Column CD is yes and Column CI has days""); + ExcelUtils.writeCell(descrRow, exclude4Idx, ""Column BO is less than Column BX, or Column BX is greater than Column CI""); + + ExcelUtils.writeCell(descrRow, includeCrit1Idx, ""based on Inc 1, 2a, 3, 4b, 4c, 5, 6, 8, 9\nnot otherwise excluded""); + ExcelUtils.writeCell(descrRow, includeCrit2Idx, ""based on Inc 2a, 3, 4c, 5, 6, 9\nnot otherwise excluded""); + ExcelUtils.writeCell(descrRow, includeCrit3Idx, ""all subjects\nnot otherwise excluded""); + ExcelUtils.writeCell(descrRow, bfciIdx, ""as per Hudis et al. 2000 (based on CE,CG,BR,BS,BT)""); + } + + private PoiWorksheetIterator getSampleIterator() { + return m_sampleIterator; + } + + private void setSampleIterator(PoiWorksheetIterator sampleIterator) { + m_sampleIterator = sampleIterator; + + if (getSampleIterator().hasNext()) { + setCurrentDataRow(getSampleIterator().next()); + } + } + + public boolean hasNext() { + return getCurrentDataRow()!=null + && !getCurrentDataRow().isEmpty() + && StringUtils.isNotBlank(getCurrentDataRow().get(0)); + } + + public Subject next() { + rowIndexPlus(); + Subject subject = parseSubject(getCurrentDataRow()); + if (getSampleIterator().hasNext()) { + setCurrentDataRow(getSampleIterator().next()); + } + else { + setCurrentDataRow(null); + } + return subject; + } + + public void skipNext() { + rowIndexPlus(); + if (getSampleIterator().hasNext()) { + setCurrentDataRow(getSampleIterator().next()); + } + else { + setCurrentDataRow(null); + } + } + + public void remove() { + throw new UnsupportedOperationException(""org.pharmgkb.ItpcSheet does not support removing Subjects""); + } + + protected Subject parseSubject(List fields) { + Subject subject = new Subject(); + + subject.setSubjectId(fields.get(subjectId)); + subject.setProjectSite(fields.get(projectSiteIdx)); + subject.setAge(fields.get(ageIdx)); + subject.setGender(fields.get(genderIdx)); + subject.setRace(fields.get(raceIdx)); + subject.setMetastatic(fields.get(metastaticIdx)); + subject.setMenoStatus(fields.get(menoStatusIdx)); + subject.setErStatus(fields.get(erStatusIdx)); + subject.setDuration(fields.get(durationIdx)); + subject.setTamoxDose(fields.get(tamoxDoseIdx)); + subject.setTumorSource(fields.get(tumorSourceIdx)); + subject.setBloodSource(fields.get(bloodSourceIdx)); + subject.setPriorHistory(fields.get(priorHistoryIdx)); + subject.setPriorDcis(fields.get(priorDcisIdx)); + subject.setChemotherapy(fields.get(chemoIdx)); + subject.setHormoneTherapy(fields.get(hormoneIdx)); + subject.setSystemicTher(fields.get(systemicTherIdx)); + subject.setFollowup(fields.get(followupIdx)); + subject.setTimeBtwSurgTamox(fields.get(timeBtwSurgTamoxIdx)); + subject.setFirstAdjEndoTher(fields.get(firstAdjEndoTherIdx)); + subject.setTumorDimension(fields.get(tumorDimensionIdx)); + subject.setNumPositiveNodes(fields.get(numPositiveNodesIdx)); + subject.setTumorGrading(fields.get(tumorGradingIdx)); + subject.setProgesteroneReceptor(fields.get(pgrStatusIdx)); + subject.setRadiotherapy(fields.get(radioIdx)); + subject.setAdditionalCancer(fields.get(additionalCancerIdx)); + subject.setAddCxIpsilateral(fields.get(addCxIpsilateralIdx)); + subject.setAddCxDistantRecur(fields.get(addCxDistantRecurIdx)); + subject.setAddCxContralateral(fields.get(addCxContralateralIdx)); + subject.setAddCxSecondInvasive(fields.get(addCxSecondInvasiveIdx)); + subject.setAddCxLastEval(fields.get(addCxLastEvalIdx)); + subject.setDaysDiagtoDeath(fields.get(daysDiagToDeathIdx)); + subject.setPatientDied(fields.get(patientDiedIdx)); + subject.setDiseaseFreeSurvivalTime(fields.get(diseaseFreeSurvivalTimeIdx)); + subject.setSurvivalNotDied(fields.get(survivalNotDiedIdx)); + subject.setCauseOfDeath(fields.get(causeOfDeathIdx)); + + subject.setRs4986774(new VariantAlleles(fields.get(rs4986774idx))); + subject.setRs1065852(new VariantAlleles(fields.get(rs1065852idx))); + subject.setRs3892097(new VariantAlleles(fields.get(rs3892097idx))); + subject.setRs5030655(new VariantAlleles(fields.get(rs5030655idx))); + subject.setRs16947(new VariantAlleles(fields.get(rs16947idx))); + subject.setRs28371706(new VariantAlleles(fields.get(rs28371706idx))); + subject.setRs28371725(new VariantAlleles(fields.get(rs28371725idx))); + subject.setDeletion(fields.get(star5idx)); + + for (Integer idx : sampleSourceIdxs) { + if (fields.get(idx) != null) { + if (fields.get(idx).contains(""0"")) { + subject.addSampleSource(Subject.SampleSource.TUMOR_FFP); + } + if (fields.get(idx).contains(""1"")) { + subject.addSampleSource(Subject.SampleSource.BLOOD); + } + if (fields.get(idx).contains(""2"")) { + subject.addSampleSource(Subject.SampleSource.BUCCAL); + } + if (fields.get(idx).contains(""3"")) { + subject.addSampleSource(Subject.SampleSource.TUMOR_FROZEN); + } + if (fields.get(idx).contains(""4"")) { + subject.addSampleSource(Subject.SampleSource.NORMAL_PARAFFIN); + } + } + } + if (subject.getSampleSources().isEmpty()) { + subject.addSampleSource(Subject.SampleSource.UNKNOWN); + } + + subject.setGenotypeAmplichip(fields.get(amplichipidx)); + subject.setGenotypeOther(fields.get(otherGenoIdx)); + + for (Med med : medIdx.keySet()) { + subject.addMedStatus(med, translateDrugFieldToValue(fields.get(medIdx.get(med)))); + } + + subject.setDcisStatus(isDcis(fields.get(projectNotesIdx))); + + return subject; + } + + private Value translateDrugFieldToValue(String field) { + if (ItpcUtils.isBlank(field)) { + return Value.Unknown; + } + else if (field.equals(""1"")) { + return Value.Yes; + } + else if (field.equals(""0"")) { + return Value.No; + } + else { + return Value.Unknown; + } + } + + public int getCurrentRowIndex() { + return m_rowIndex; + } + + private void rowIndexPlus() { + m_rowIndex++; + } + + public Row getCurrentRow() { + return m_dataSheet.getRow(this.getCurrentRowIndex()); + } + + public void writeSubjectCalculatedColumns(Subject subject) { + Row row = this.getCurrentRow(); + CellStyle highlight = getHighlightStyle(); + subject.calculateGenotypeLimited(); + + ExcelUtils.writeCell(row, newFirstDiseaseEventIdx, subject.getFirstDiseaseEventCalc(), highlight); + ExcelUtils.writeCell(row, diagToEventCalcIdx, subject.getDiagToEventDaysCalc(), highlight); + + ExcelUtils.writeCell(row, allele1finalIdx, subject.getGenotypeFinal().get(0), highlight); + ExcelUtils.writeCell(row, allele2finalIdx, subject.getGenotypeFinal().get(1), highlight); + ExcelUtils.writeCell(row, genotypeIdx, subject.getGenotypeFinal().getMetabolizerStatus(), highlight); + ExcelUtils.writeCell(row, genoMetabStatusIdx, subject.getGenotypeFinal().getMetabolizerGroup(), highlight); + ExcelUtils.writeCell(row, weakIdx, subject.getWeak().toString(), highlight); + ExcelUtils.writeCell(row, potentIdx, subject.getPotent().toString(), highlight); + ExcelUtils.writeCell(row, scoreIdx, ItpcUtils.floatDisplay(subject.getScore()), highlight); + ExcelUtils.writeCell(row, metabStatusIdx, subject.getMetabolizerGroup(), highlight); + + ExcelUtils.writeCell(row, incAgeIdx, ItpcUtils.valueToInclusion(subject.passInclusion1()), highlight); + ExcelUtils.writeCell(row, incNonmetaIdx, ItpcUtils.valueToInclusion(subject.passInclusion2a()), highlight); + ExcelUtils.writeCell(row, incPriorHistIdx, ItpcUtils.valueToInclusion(subject.passInclusion2b()), highlight); + ExcelUtils.writeCell(row, incErPosIdx, ItpcUtils.valueToInclusion(subject.passInclusion3()), highlight); + ExcelUtils.writeCell(row, incSysTherIdx, ItpcUtils.valueToInclusion(subject.passInclusion4()), highlight); + ExcelUtils.writeCell(row, incAdjTamoxIdx, ItpcUtils.valueToInclusion(subject.passInclusion4a()), highlight); + ExcelUtils.writeCell(row, incDurationIdx, ItpcUtils.valueToInclusion(subject.passInclusion4b()), highlight); + ExcelUtils.writeCell(row, incTamoxDoseIdx, ItpcUtils.valueToInclusion(subject.passInclusion4c()), highlight); + ExcelUtils.writeCell(row, incChemoIdx, ItpcUtils.valueToInclusion(subject.passInclusion5()), highlight); + ExcelUtils.writeCell(row, incHormoneIdx, ItpcUtils.valueToInclusion(subject.passInclusion6()), highlight); + ExcelUtils.writeCell(row, incDnaCollectionIdx, ItpcUtils.valueToInclusion(subject.passInclusion7()), highlight); + ExcelUtils.writeCell(row, incFollowupIdx, ItpcUtils.valueToInclusion(subject.passInclusion8()), highlight); + ExcelUtils.writeCell(row, incGenoDataAvailIdx, ItpcUtils.valueToInclusion(subject.passInclusion9()), highlight); + + ExcelUtils.writeCell(row, exclude1Idx, ItpcUtils.valueToExclusion(subject.exclude1()), highlight); + ExcelUtils.writeCell(row, exclude2Idx, ItpcUtils.valueToExclusion(subject.exclude4()), highlight); + ExcelUtils.writeCell(row, exclude3Idx, ItpcUtils.valueToExclusion(subject.exclude5()), highlight); + ExcelUtils.writeCell(row, exclude4Idx, ItpcUtils.valueToExclusion(subject.exclude6()), highlight); + + ExcelUtils.writeCell(row, includeCrit1Idx, ItpcUtils.valueToInclusion(subject.includeCrit1()), highlight); + ExcelUtils.writeCell(row, includeCrit2Idx, ItpcUtils.valueToInclusion(subject.includeCrit2()), highlight); + ExcelUtils.writeCell(row, includeCrit3Idx, ItpcUtils.valueToInclusion(subject.includeCrit3()), highlight); + + ExcelUtils.writeCell(row, bfciIdx, subject.getBreastCancerFreeInterval(), highlight); + ExcelUtils.writeCell(row, genoSourceIdx, Joiner.on(',').join(subject.getSampleSources()), highlight); + } + + public File saveOutput() throws IOException { + File outputFile = ItpcUtils.getOutputFile(inputFile); + sf_logger.info(""Writing output to: "" + outputFile); + + FileOutputStream statsOut = new FileOutputStream(outputFile); + m_dataSheet.getWorkbook().write(statsOut); + IOUtils.closeQuietly(statsOut); + + return outputFile; + } + + public Workbook getWorkbook() { + return m_dataSheet.getWorkbook(); + } + + public void doHighlighting() { + if (styleHighlight == null) { + styleHighlight = getWorkbook().createCellStyle(); + + styleHighlight.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); + styleHighlight.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + styleHighlight.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleHighlight.setWrapText(true); + } + } + + public CellStyle getHighlightStyle() { + return styleHighlight; + } + + /** + * Styles the given row with the Title Style specified in getTitleStyle. The startIndex + * parameter specifies which column column to start applying the style on (0 = all columns) inclusively. + * @param row an Excel Row + * @param startIndex the index of the column to start applying the style on + * @param style the CellStyle to apply + */ + public void styleCells(Row row, int startIndex, CellStyle style) { + Iterator headerCells = row.cellIterator(); + + while (headerCells.hasNext()) { + Cell headerCell=headerCells.next(); + if (headerCell.getColumnIndex()>=startIndex) { + headerCell.setCellStyle(style); + } + } + } + + /** + * Returns whether a given String contains the DCIS descriptor + * @param notes the Subject's notes field as a String + * @return a Value if the note contains DCIS test + */ + private Value isDcis(String notes) { + Value isDcis = Value.Unknown; + + if (!StringUtils.isBlank(notes)) { + if (notes.contains(""DCIS, no invasive component"")) { + isDcis = Value.Yes; + } + else { + isDcis = Value.No; + } + } + return isDcis; + } + + public List getCurrentDataRow() { + return m_currentDataRow; + } + + public void setCurrentDataRow(List m_currentDataRow) { + this.m_currentDataRow = m_currentDataRow; + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/org/pharmgkb/VariantAlleles.java",".java","2712","81","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package org.pharmgkb; + +import util.StringPair; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + + +/** + * This class doesn't allow ""Unknown"" as a value, it only accepts a,c,g,t, or - (for deletion) + * User: Ryan Whaley + */ +public class VariantAlleles extends StringPair { + + private static final Set validAlleles = new HashSet(); + static { + validAlleles.add(""a""); + validAlleles.add(""t""); + validAlleles.add(""g""); + validAlleles.add(""c""); + validAlleles.add(""-""); + } + + public VariantAlleles() {} + + public VariantAlleles(String alleles) { + if (alleles == null) { + return; + } + + alleles = alleles.trim().toLowerCase(); + String[] data = alleles.split(""/""); + Arrays.sort(data, String.CASE_INSENSITIVE_ORDER); + for (String base : data) { + this.addString(base.trim().toLowerCase()); + } + } + + public boolean isValid(String string) { + return validAlleles.contains(string); + } + +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/util/CliHelper.java",".java","8524","272","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package util; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.util.HelpFormatter; +import org.apache.commons.cli2.validation.EnumValidator; + +import java.io.IOException; +import java.util.List; +import java.util.Set; + + +/** + * This is a helper class for command line utilities to interact with command line arguments. + * + * @author Mark Woon + */ +public class CliHelper { + private static final String sf_verboseFlag = ""verbose""; + private static final String sf_helpFlag = ""help""; + private static final String sf_targets = ""targets""; + private final DefaultOptionBuilder m_optBuilder = new DefaultOptionBuilder(); + private final ArgumentBuilder m_argBuilder = new ArgumentBuilder(); + private GroupBuilder m_groupBuilder = new GroupBuilder(); + private String m_name; + private Group m_options; + private Option m_helpOption; + private Option m_verboseOption; + private Option m_targetsOption; + private CommandLine m_commandLine; + + + /** + * Standard constructor. + * + * @param cls the class with the main() method + * @param hasTargets true if generic arguments (i.e. non-option arguments) are expected, false + * otherwise + */ + public CliHelper(Class cls, boolean hasTargets) { + + m_name = cls.getName(); + m_groupBuilder = m_groupBuilder.withName(""options""); + m_helpOption = m_optBuilder.withDescription(""print thismessage"") + .withLongName(sf_helpFlag) + .withShortName(""h"") + .create(); + m_groupBuilder = m_groupBuilder.withOption(m_helpOption); + m_verboseOption = m_optBuilder.withDescription(""enable verbose output"") + .withLongName(sf_verboseFlag) + .withShortName(""v"") + .create(); + m_groupBuilder = m_groupBuilder.withOption(m_verboseOption); + if (hasTargets) { + m_targetsOption = m_argBuilder.withName(sf_targets).create(); + m_groupBuilder = m_groupBuilder.withOption(m_targetsOption); + } + } + + + /** + * Add an option that doesn't take an argument. + */ + public void addOption(String shortName, String longName, String description) { + + if (shortName.equals(""h"") || shortName.equals(""v"")) { + throw new IllegalArgumentException(""-h and -v are reserved arguments""); + } + m_groupBuilder = m_groupBuilder.withOption(m_optBuilder + .withDescription(description) + .withLongName(longName) + .withShortName(shortName) + .create()); + } + + /** + * Add an option that takes an argument. + */ + public void addOption(String shortName, String longName, String description, + String argName) { + + addOption(shortName, longName, description, argName, false); + } + + /** + * Add a required option that takes an argument. + */ + public void addOption(String shortName, String longName, String description, + String argName, boolean isRequired) { + + if (shortName.equals(""h"") || shortName.equals(""v"")) { + throw new IllegalArgumentException(""-h and -v are reserved arguments""); + } + m_groupBuilder = m_groupBuilder.withOption(m_optBuilder + .withDescription(description) + .withLongName(longName) + .withShortName(shortName) + .withArgument(m_argBuilder + .withName(argName) + .withMinimum(1) + .withMaximum(1) + .create()) + .withRequired(isRequired) + .create()); + } + + /** + * Add a required option that takes more than one argument. + */ + public void addOption(String shortName, String longName, String description, + String argName, int numArgs, boolean isRequired) { + + if (shortName.equals(""h"") || shortName.equals(""v"")) { + throw new IllegalArgumentException(""-h and -v are reserved arguments""); + } + m_groupBuilder = m_groupBuilder.withOption(m_optBuilder + .withDescription(description) + .withLongName(longName) + .withShortName(shortName) + .withArgument(m_argBuilder + .withName(argName) + .withMinimum(1) + .withMaximum(numArgs) + .create()) + .withRequired(isRequired) + .create()); + } + + + /** + * Add a required option that takes an enumerated argument. + */ + public void addOption(String shortName, String longName, String description, + String argName, Set arguments, boolean isRequired) { + + if (shortName.equals(""h"") || shortName.equals(""v"")) { + throw new IllegalArgumentException(""-h and -v are reserved arguments""); + } + m_groupBuilder = m_groupBuilder.withOption(m_optBuilder + .withDescription(description) + .withLongName(longName) + .withShortName(shortName) + .withArgument(m_argBuilder + .withName(argName) + .withMinimum(1) + .withMaximum(1) + .withValidator(new EnumValidator(arguments)) + .create()) + .withRequired(isRequired) + .create()); + } + + /** + * Parses arguments. + */ + public void parse(String[] args) throws OptionException { + + m_options = m_groupBuilder.create(); + Parser parser = new Parser(); + parser.setGroup(m_options); + parser.setHelpOption(m_helpOption); + m_commandLine = parser.parse(args); + } + + + /** + * Checks whether the specified option exists. + */ + public boolean hasOption(String opt) { + return m_commandLine.hasOption(opt); + } + + /** + * Gets the String value for the given option. + */ + public String getValue(String opt) { + return (String)m_commandLine.getValue(opt); + } + + /** + * Gets the String values for the given option. + */ + public List getValues(String opt) { + //noinspection unchecked + return m_commandLine.getValues(opt); + } + + /** + * Gets the int value for the given option. + */ + public int getIntValue(String opt) { + return Integer.parseInt((String)m_commandLine.getValue(opt)); + } + + /** + * Gets the targets + */ + public List getTargets() { + return m_commandLine.getValues(m_targetsOption); + } + + + /** + * Gets whether to operate in verbose mode. + */ + public boolean isVerbose() { + return m_commandLine.hasOption(m_verboseOption); + } + + + /** + * Gets whether help on command line arguments has been requested. + */ + public boolean isHelpRequested() { + return m_commandLine.hasOption(m_helpOption); + } + + + /** + * Prints the help message. + */ + public void printHelp() throws IOException { + + HelpFormatter hf = new HelpFormatter(); + hf.setShellCommand(m_name); + hf.setGroup(m_options); + hf.print(); + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/util/Value.java",".java","2080","62","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package util; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Jul 16, 2010 + * Time: 9:54:36 AM + */ +public enum Value { + Unknown, + Yes, + No; + + public String toString() { + if (this==Yes) { + return ""Yes""; + } + else if (this==No) { + return ""No""; + } + else { + return ""Unknown""; + } + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/util/ItpcUtils.java",".java","4764","149","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package util; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Jul 16, 2010 + * Time: 9:55:50 AM + */ +public class ItpcUtils { + public static final Integer SITE_COUNT = 12; + + private static final Logger logger = Logger.getLogger(ItpcUtils.class); + private static final Pattern sf_alleleRegex = Pattern.compile(""\\*\\d+""); + + public static boolean isBlank(String string) { + String trimString = StringUtils.trimToNull(string); + return StringUtils.isBlank(trimString) || trimString.equalsIgnoreCase(""na""); + } + + public static File getOutputFile(File inputFile) { + Date date = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat(""yyyyMMdd-HHmm""); + String newExtension = new StringBuilder() + .append(""."") + .append(sdf.format(date)) + .append("".xls"") + .toString(); + + return new File(inputFile.getAbsolutePath().replaceAll(""\\.xls"", newExtension)); + } + + /** + * This method takes a String allele and returns a stripped version of that allele. This way we don't have to store + * every version of each allele. For instance, *4K is stripped down to *4 for processing and mapping. + * @param allele a String allele + * @return a stripped version of allele + */ + public static String alleleStrip(String allele) { + String alleleClean = null; + + Matcher m = sf_alleleRegex.matcher(allele); + if (allele.equalsIgnoreCase(""Unknown"")) { + alleleClean = ""Unknown""; + } + else if (m.find()) { + alleleClean = allele.substring(m.start(),m.end()); + if (allele.toLowerCase().contains(""xn"")) { + alleleClean += ""XN""; + } + else if (allele.equalsIgnoreCase(""*2a"")) { + alleleClean = ""*2A""; + } + } + else { + logger.warn(""Malformed allele found: "" + allele); + } + + return alleleClean; + } + + /** + * Covert a Value enum to be displayed in an inclusion field + * @param value a Value enum + * @return a String of either ""Include"" or ""Exclude"" or ""Unknown"" + */ + public static String valueToInclusion(Value value) { + if (value == Value.Yes) { + return ""Include""; + } + else if (value == Value.No) { + return ""Exclude""; + } + else { + return ""Unknown""; + } + } + + /** + * Covert a Value enum to be displayed in an exclusion field + * @param value a Value enum + * @return a String of either ""Include"" or ""Exclude"" or ""Unknown"" + */ + public static String valueToExclusion(Value value) { + if (value == Value.Yes) { + return ""Exclude""; + } + else if (value == Value.No) { + return ""Include""; + } + else { + return ""Unknown""; + } + } + + public static String floatDisplay(Float number) { + if (number == null) { + return Value.Unknown.toString(); + } + else { + return number.toString(); + } + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/util/Med.java",".java","3490","94","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package util; + +import com.google.common.collect.Maps; + +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: 7/6/11 + */ +public enum Med { + Fluoxetine, + Paroxetine, + Quinidine, + Buproprion, + Duloxetine, + Sertraline, + Diphenhydramine, + Thioridazine, + Amiodarone, + Trazodone, + Cimetidine, + Venlafaxine, + Citalopram, + Escitalopram; + + + protected static final Map sf_medPatterns = Maps.newHashMap(); + static { + sf_medPatterns.put(Pattern.compile(""Fluoxetine""), Med.Fluoxetine); + sf_medPatterns.put(Pattern.compile(""Paroxetine""), Med.Paroxetine); + sf_medPatterns.put(Pattern.compile(""Quinidine""), Med.Quinidine); + sf_medPatterns.put(Pattern.compile(""Buproprion""), Med.Buproprion); + sf_medPatterns.put(Pattern.compile(""Duloxetine""), Med.Duloxetine); + sf_medPatterns.put(Pattern.compile(""Sertraline""), Med.Sertraline); + sf_medPatterns.put(Pattern.compile(""Diphenhydramine""), Med.Diphenhydramine); + sf_medPatterns.put(Pattern.compile(""Thioridazine""), Med.Thioridazine); + sf_medPatterns.put(Pattern.compile(""Amiodarone""), Med.Amiodarone); + sf_medPatterns.put(Pattern.compile(""Trazodone""), Med.Trazodone); + sf_medPatterns.put(Pattern.compile(""Cimetidine""), Med.Cimetidine); + sf_medPatterns.put(Pattern.compile(""Venlafaxine""), Med.Venlafaxine); + sf_medPatterns.put(Pattern.compile(""Citalopram""), Med.Citalopram); + sf_medPatterns.put(Pattern.compile(""Escitalopram""), Med.Escitalopram); + } + + public static Med matchesMed(String string) { + for (Pattern pattern : sf_medPatterns.keySet()) { + if (pattern.matcher(string).matches()) { + return sf_medPatterns.get(pattern); + } + } + return null; + } +} + +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/util/StringPair.java",".java","4085","140","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package util; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Jul 13, 2010 + * Time: 11:38:12 PM + */ +public abstract class StringPair { + public static final String UNKNOWN = ""Unknown""; + private List m_strings = new ArrayList(); + + public List getStrings() { + return m_strings; + } + + /** + * Determines whether the given String is a valid value for this StringPair + * @param string a String to possibly add to this StringPair + * @return true if string is valid, false otherwise + */ + public abstract boolean isValid(String string); + + public void addString(String string) { + if (isValid(string)) { + m_strings.add(string); + } + else { + m_strings.add(UNKNOWN); + } + Collections.sort(m_strings, String.CASE_INSENSITIVE_ORDER); + } + + public void removeString(String string) { + m_strings.remove(string); + } + + public void addAll(StringPair pair) { + for (String string : pair.getStrings()) { + this.addString(string); + } + } + + public String get(int i) { + return m_strings.get(i); + } + + public int count(String datum) { + int count = 0; + for (String element : m_strings) { + if (element.equalsIgnoreCase(datum)) count++; + } + return count; + } + + public boolean contains(String inString) { + return count(inString)>0; + } + + public boolean is(String string1, String string2) { + if (string1 != null && string2 != null) { + if (string1.equalsIgnoreCase(string2)) { + return count(string1)==2; + } + else { + return (count(string1) == 1 && count(string2)==1); + } + } + return false; + } + + public boolean isUncertain() { + return this.getStrings().contains(UNKNOWN) || this.getStrings().size()!=2; + } + + public boolean hasData() { + return !m_strings.isEmpty() && m_strings.size()==2; + } + + public boolean isEmpty() { + return m_strings.isEmpty(); + } + + public int size() { + return m_strings.size(); + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + if (this.getStrings().size()>=1) { + sb.append(this.getStrings().get(0)); + } + if (this.getStrings().size()==2) { + sb.append(""/""); + sb.append(this.getStrings().get(1)); + } + return sb.toString(); + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/util/ExcelUtils.java",".java","5709","165","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package util; + +import org.apache.log4j.Logger; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.util.CellReference; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Jul 28, 2010 + * Time: 8:35:06 AM + */ +public class ExcelUtils { + private static Logger sf_logger = Logger.getLogger(ExcelUtils.class); + + public static String getAddress(Cell cell) { + StringBuilder sb = new StringBuilder(); + sb.append(CellReference.convertNumToColString(cell.getColumnIndex())); + sb.append(cell.getRowIndex()+1); + return sb.toString(); + } + + public static void writeCell(Row row, int idx, String value) { + writeCell(row, idx, value, null); + } + + public static void writeCell(Row row, int idx, String value, CellStyle highlight) { + // first validate all the important arguments + if (value == null || row == null || idx<0) { + // don't do anything if they're missing + return; + } + + Cell cell = row.getCell(idx); + + if (cell == null) { + row.createCell(idx).setCellValue(value); + } + else { + if (cell.getCellType() == Cell.CELL_TYPE_STRING) { + if (!value.equals(cell.getStringCellValue())) { + StringBuilder sb = new StringBuilder(); + sb.append(""Changed value: "") + .append(CellReference.convertNumToColString(cell.getColumnIndex())) + .append(cell.getRowIndex()+1) + .append("" = "") + .append(cell.getStringCellValue()) + .append("" -> "") + .append(value); + sf_logger.info(sb.toString()); + if (highlight != null) { + cell.setCellStyle(highlight); + } + } + } + else { + Double existingValue = cell.getNumericCellValue(); + + StringBuilder sb = new StringBuilder(); + sb.append(""Changed value: "") + .append(CellReference.convertNumToColString(cell.getColumnIndex())) + .append(cell.getRowIndex()+1) + .append("" = "") + .append(existingValue) + .append("" -> "") + .append(value); + sf_logger.info(sb.toString()); + + row.removeCell(cell); + row.createCell(idx).setCellType(Cell.CELL_TYPE_STRING); + if (highlight != null) { + cell.setCellStyle(highlight); + } + } + cell.setCellValue(value); + } + } + + public static void writeCell(Row row, int idx, float value, CellStyle highlight) { + Cell cell = row.getCell(idx); + if (cell == null) { + row.createCell(idx).setCellValue(value); + } + else { + if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { + Double existingValue = cell.getNumericCellValue(); + if (value != existingValue.floatValue()) { + StringBuilder sb = new StringBuilder(); + sb.append(""Changed value: "") + .append(CellReference.convertNumToColString(cell.getColumnIndex())) + .append(cell.getRowIndex()+1) + .append("" = "") + .append(cell.getNumericCellValue()) + .append("" -> "") + .append(value); + sf_logger.info(sb.toString()); + if (highlight != null) { + cell.setCellStyle(highlight); + } + } + } + else { + String existingValue = cell.getStringCellValue(); + + StringBuilder sb = new StringBuilder(); + sb.append(""Changed value: "") + .append(CellReference.convertNumToColString(cell.getColumnIndex())) + .append(cell.getRowIndex()+1) + .append("" = "") + .append(existingValue) + .append("" -> "") + .append(value); + sf_logger.info(sb.toString()); + + row.removeCell(cell); + row.createCell(idx).setCellType(Cell.CELL_TYPE_NUMERIC); + if (highlight != null) { + cell.setCellStyle(highlight); + } + } + + cell.setCellValue(value); + } + } + +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/util/PoiWorksheetIterator.java",".java","6481","196","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package util; + +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; + +import java.util.Iterator; +import java.util.List; + + +/** + * This is an iterator for POI worksheets. It determines whether there are more lines by looking + * for a specific number of empty rows (the default is {@link #MAX_EMPTY_ROWS}. If will still read + * intermediary empty rows if the number of empty rows is less than the maximum number of allowed + * empty rows. + * + * + * @author Mark Woon + */ +public class PoiWorksheetIterator implements Iterator> { + public static final int MAX_EMPTY_ROWS = 3; + private Sheet m_sheet; + private int m_currentRow; + private int m_maxEmptyRows = MAX_EMPTY_ROWS; + private int m_maxColumns; + + + /** + * Standard constructor. + * + * @param sheet the worksheet to iterate through + */ + public PoiWorksheetIterator(Sheet sheet) { + + this(sheet, 0); + } + + /** + * Standard constructor. + * + * @param sheet the worksheet to iterate through + * @param startRow the row number to start iterating from, the first row being 1 + */ + public PoiWorksheetIterator(Sheet sheet, int startRow) { + + m_sheet = sheet; + m_currentRow = startRow; + m_maxColumns = -1; + } + + /** + * Standard constructor. + * + * @param sheet the worksheet to iterate through + * @param startRow the row number to start iterating from, the first row being 1 + * @param maxColumns the number of columns to read per row (from the first column) + */ + public PoiWorksheetIterator(Sheet sheet, int startRow, int maxColumns) { + + m_sheet = sheet; + m_currentRow = startRow - 1; + if (m_currentRow < 0) { + throw new IllegalArgumentException(""Start row cannot be less than 0""); + } + m_maxColumns = maxColumns - 1; + if (m_maxColumns < 0) { + throw new IllegalArgumentException(""Max columns cannot be less than 0""); + } + } + + + /** + * Gets the maximum number of empty rows before considering that there are no more rows. The + * default is {@link #MAX_EMPTY_ROWS}. + * + * @return the maximum number of empty rows before considering that there are no more rows + */ + public int getMaxEmptyRows() { + + return m_maxEmptyRows; + } + + /** + * Sets the maximum number of empty rows before considering that there are no more rows. + * + * @param maxEmptyRows the maximum number of empty rows before considering that there are no more + * rows. + */ + public void setMaxEmptyRows(int maxEmptyRows) { + + m_maxEmptyRows = maxEmptyRows; + } + + + /** + * Returns true if the iteration has more elements. (In other words, returns + * true if next would return an element rather than throwing an exception.) + * + * @return true if the iterator has more elements. + */ + public boolean hasNext() { + + int currentRow = m_currentRow; + for (int emptyRowCount = 0; emptyRowCount < m_maxEmptyRows; emptyRowCount++) { + // advance row count and grab it from sheet + Row row = m_sheet.getRow(currentRow++); + if (row != null) { + return true; + } + } + return false; + } + + + /** + * Returns the next element in the iteration. Calling this method repeatedly until the {@link + * #hasNext()} method returns false will return each element in the underlying collection exactly + * once. + * + * @return the next element in the iteration. + * @throws java.util.NoSuchElementException iteration has no more elements. + */ + public List next() { + + if (m_maxColumns == -1) { + return POIUtils.getStringCellValues(m_sheet, m_currentRow++); + } + return POIUtils.getStringCellValues(m_sheet, m_currentRow++, 0, m_maxColumns); + } + + + /** + * Gets the current row number of the worksheet that this iterator is on. This number begins at + * 0. + * + * @return the current row number of the worksheet that this iterator is on + */ + public int getRowNumber() { + + return m_currentRow; + } + + + /** + * Removes from the underlying collection the last element returned by the iterator (optional + * operation). This method can be called only once per call to next. The behavior of an + * iterator is unspecified if the underlying collection is modified while the iteration is in + * progress in any way other than by calling this method. + * + * @throws UnsupportedOperationException if the remove operation is not supported by this + * Iterator. + * @throws IllegalStateException if the next method has not yet been called, or the + * remove method has already been called after the last call to the next + * method. + */ + public void remove() { + + throw new UnsupportedOperationException(""remove() is not supported""); + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/util/POIUtils.java",".java","4798","152","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package util; + +import org.apache.commons.lang.StringUtils; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; + +import java.math.BigDecimal; +import java.math.MathContext; +import java.util.ArrayList; +import java.util.List; + + +/** + * This class provides convenience methods for dealing with POI objects. + * + * @author Ryan Whaley + */ +public class POIUtils { + + private POIUtils() { + } + + + /** + * Converts numbers that include exponents into a regular number. + * + * @param number original number + * @return reformatted number + **/ + private static String formatNumber(double number) { + + String numString = Double.toString(number); + int idx = numString.indexOf((int)'E'); + if (idx == -1) { + // lop off trailing .0 + if (numString.endsWith("".0"")) { + numString = numString.substring(0, numString.length() - 2); + } + return numString; + } + + int exponent = Integer.parseInt(numString.substring(idx + 1)); + int precision = idx - 1; + if (exponent > 0 && exponent == precision) { + precision++; + } + BigDecimal bd = new BigDecimal(number, new MathContext(precision)); + return bd.toPlainString(); + } + + /** + * Gets the string value of a cell. + * + * @param cell the cell to get the string value of + * @return the string value of the specified cell + */ + private static String getStringValue(Cell cell) { + + if (cell != null) { + switch (cell.getCellType()) { + case Cell.CELL_TYPE_NUMERIC: + cell.setCellType(Cell.CELL_TYPE_NUMERIC); + return formatNumber(cell.getNumericCellValue()); + case Cell.CELL_TYPE_BOOLEAN: + return Boolean.toString(cell.getBooleanCellValue()); + default: + return StringUtils.stripToNull(cell.getRichStringCellValue().getString()); + } + } + return null; + } + + + /** + * Returns column values in specified row. Indexes are 0-based. + * + * @param sheet Excel spreadsheet + * @param rowNum row number + * @return list of cell values in row + **/ + public static List getStringCellValues(Sheet sheet, int rowNum) { + + Row row = sheet.getRow(rowNum); + if (row != null) { + return getStringCellValues(sheet, rowNum, 0, (int)row.getLastCellNum()-1); + } + return new ArrayList(); + } + + + /** + * Returns values within specified column range in specified row. + * + * @param sheet Excel spreadsheet + * @param rowNum row number + * @param columnStart index of beginning of column range + * @param columnStop index of end of column range + * @return list of cell values in row + **/ + public static List getStringCellValues(Sheet sheet, int rowNum, int columnStart, + int columnStop) { + + List values = new ArrayList(); + Row row = sheet.getRow(rowNum); + if (row != null) { + int stop = columnStop + 1; + for (int i = columnStart; i < stop; i++) { + values.add(getStringValue(row.getCell(i))); + } + } + return values; + } + +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/util/GenotypeComparator.java",".java","2752","89","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package util; + +import org.pharmgkb.Genotype; + +import java.util.Comparator; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: 6/27/12 + */ +public class GenotypeComparator implements Comparator { + private static final Comparator sf_comparator = new GenotypeComparator(); + + public static Comparator getComparator() { + return sf_comparator; + } + + @Override + public int compare(Genotype o1, Genotype o2) { + if (o1==o2) { + return 0; + } + if (o1 == null) { + return 1; + } + if (o2 == null) { + return -1; + } + + if (o1.getScore()==null && o2.getScore()==null) { + return 0; + } + if (o1.getScore()==null) { + return 1; + } + if (o2.getScore()==null) { + return -1; + } + int rez = o1.getScore().compareTo(o2.getScore()); + if (rez != 0) { + return -1*rez; + } + + rez = o1.getMetabolizerStatus().compareTo(o2.getMetabolizerStatus()); + if (rez != 0) { + return rez; + } + + return 0; + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/summary/InclusionSummary.java",".java","15718","427","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package summary; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.pharmgkb.Subject; +import util.ItpcUtils; +import util.Value; + +import java.util.List; +import java.util.Map; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: 4/15/11 + */ +public class InclusionSummary extends AbstractSummary { + private static final String sf_sheetTitle = ""Inclusion Summary""; + private static final int inc1 = 0; + private static final int inc2a = 1; + private static final int inc2b = 2; + private static final int inc3 = 3; + private static final int inc4 = 4; + private static final int inc4a = 5; + private static final int inc4b = 6; + private static final int inc4c = 7; + private static final int inc5 = 8; + private static final int inc6 = 9; + private static final int inc7 = 10; + private static final int inc8 = 11; + private static final int inc9 = 12; + + private static final int exc1 = 0; + private static final int exc2 = 1; + private static final int exc3 = 2; + private static final int exc4 = 3; + + private static final int crit1 = 0; + private static final int crit2 = 1; + private static final int crit3 = 2; + + private static final Map inclusions = Maps.newHashMap(); + static { + inclusions.put(0, ""Inc. 1""); + inclusions.put(1, ""Inc. 2a""); + inclusions.put(2, ""Inc. 2b""); + inclusions.put(3, ""Inc. 3""); + inclusions.put(4, ""Inc. 4""); + inclusions.put(5, ""Inc. 4a""); + inclusions.put(6, ""Inc. 4b""); + inclusions.put(7, ""Inc. 4c""); + inclusions.put(8, ""Inc. 5""); + inclusions.put(9, ""Inc. 6""); + inclusions.put(10, ""Inc. 7""); + inclusions.put(11, ""Inc. 8""); + inclusions.put(12, ""Inc. 9""); + } + + private static final Map exclusions = Maps.newHashMap(); + static { + exclusions.put(0, ""Excl. 1""); + exclusions.put(1, ""Excl. 2""); + exclusions.put(2, ""Excl. 3""); + exclusions.put(3, ""Excl. 4""); + } + + private static final Map criteriaLabels = Maps.newHashMap(); + static { + criteriaLabels.put(0, ""Criteria 1""); + criteriaLabels.put(1, ""Criteria 2""); + criteriaLabels.put(2, ""Criteria 3""); + } + + // + private List>> projectMap = null; + private Map> studyMap = null; + private List>> projectExcludeMap = null; + private List>> projectCritMap = null; + private Map> studyCritMap = null; + private Map projectSubjectCount = null; + + public InclusionSummary() { + projectMap = Lists.newArrayList(); + projectExcludeMap = Lists.newArrayList(); + projectCritMap = Lists.newArrayList(); + projectSubjectCount = Maps.newHashMap(); + + studyMap = Maps.newHashMap(); + studyCritMap = Maps.newHashMap(); + + for (int i=0; i< ItpcUtils.SITE_COUNT; i++) { + projectSubjectCount.put(i, 0); + Map> inclusionMap = Maps.newHashMap(); + projectMap.add(inclusionMap); + + for (int j=0; j< inclusions.size(); j++) { + Map valueMap = Maps.newHashMap(); + inclusionMap.put(j, valueMap); + + valueMap.put(Value.Yes, 0); + valueMap.put(Value.No, 0); + valueMap.put(Value.Unknown, 0); + + valueMap = Maps.newHashMap(); + studyMap.put(j, valueMap); + + valueMap.put(Value.Yes, 0); + valueMap.put(Value.No, 0); + valueMap.put(Value.Unknown, 0); + } + + Map> exclusionMap = Maps.newHashMap(); + projectExcludeMap.add(exclusionMap); + + for (int j=0; j valueMap = Maps.newHashMap(); + exclusionMap.put(j, valueMap); + + valueMap.put(Value.Yes,0); + valueMap.put(Value.No,0); + } + + Map> criteriaMap = Maps.newHashMap(); + projectCritMap.add(criteriaMap); + + for (int j=0; j valueMap = Maps.newHashMap(); + criteriaMap.put(j, valueMap); + + valueMap.put(Value.Yes,0); + valueMap.put(Value.No,0); + + valueMap = Maps.newHashMap(); + studyCritMap.put(j, valueMap); + + valueMap.put(Value.Yes,0); + valueMap.put(Value.No,0); + } + } + } + + @Override + public String getSheetTitle() { + return sf_sheetTitle; + } + + @Override + public void addSubject(Subject subject) { + int site = Integer.valueOf(subject.getProjectSite()); + projectSubjectCount.put(site-1, projectSubjectCount.get(site-1)+1); + + addSubjectInclusion(site-1, inc1, subject.passInclusion1()); + addSubjectInclusion(site-1, inc2a, subject.passInclusion2a()); + addSubjectInclusion(site-1, inc2b, subject.passInclusion2b()); + addSubjectInclusion(site-1, inc3, subject.passInclusion3()); + addSubjectInclusion(site-1, inc4, subject.passInclusion4()); + addSubjectInclusion(site-1, inc4a, subject.passInclusion4a()); + addSubjectInclusion(site-1, inc4b, subject.passInclusion4b()); + addSubjectInclusion(site-1, inc4c, subject.passInclusion4c()); + addSubjectInclusion(site-1, inc5, subject.passInclusion5()); + addSubjectInclusion(site-1, inc6, subject.passInclusion6()); + addSubjectInclusion(site-1, inc7, subject.passInclusion7()); + addSubjectInclusion(site-1, inc8, subject.passInclusion8()); + addSubjectInclusion(site-1, inc9, subject.passInclusion9()); + + addSubjectExclusion(site - 1, exc1, subject.exclude1()); + addSubjectExclusion(site - 1, exc2, subject.exclude4()); + addSubjectExclusion(site - 1, exc3, subject.exclude5()); + addSubjectExclusion(site - 1, exc4, subject.exclude6()); + + addSubjectCriterium(site - 1, crit1, subject.includeCrit1()); + addSubjectCriterium(site - 1, crit2, subject.includeCrit2()); + addSubjectCriterium(site - 1, crit3, subject.includeCrit3()); + } + + private void addSubjectInclusion(int site, int criteria, Value value) { + // let's just count Unknowns as no for this summary + Value useValue = value; + if (value == Value.Unknown) { + useValue = Value.No; + } + + Map> inclusionMap = projectMap.get(site); + Map valueMap = inclusionMap.get(criteria); + Map studyValueMap = studyMap.get(criteria); + + valueMap.put(useValue, valueMap.get(useValue)+1); + studyValueMap.put(useValue, studyValueMap.get(useValue)+1); + } + + private void addSubjectExclusion(int site, int criteria, Value value) { + Map> exclusionMap = projectExcludeMap.get(site); + Map valueMap = exclusionMap.get(criteria); + valueMap.put(value, valueMap.get(value)+1); + } + + private void addSubjectCriterium(int site, int criteria, Value value) { + Map> criteriumMap = projectCritMap.get(site); + Map valueMap = criteriumMap.get(criteria); + Map studyValueMap = studyCritMap.get(criteria); + valueMap.put(value, valueMap.get(value)+1); + studyValueMap.put(value, studyValueMap.get(value)+1); + } + + @Override + public void writeToWorkbook(Workbook wb) { + int currentRow = 0; + Sheet sheet = getSheet(wb); + + currentRow = writeInclusionTable(sheet, currentRow, Value.Yes); + currentRow += 3; + currentRow = writeInclusionTable(sheet, currentRow, Value.No); + currentRow += 3; + currentRow = writeExclusionTable(sheet, currentRow, Value.Yes); + currentRow += 3; + currentRow = writeExclusionTable(sheet, currentRow, Value.No); + currentRow += 3; + currentRow = writeCriteriaTable(sheet, currentRow, Value.Yes); + currentRow += 3; + currentRow = writeCriteriaTable(sheet, currentRow, Value.No); + currentRow += 3; + currentRow = writeStudyInclusionTable(sheet, currentRow); + currentRow += 3; + writeStudyCriteriaTable(sheet, currentRow); + } + + private int writeStudyInclusionTable(Sheet sheet, int currentRow) { + Row title = sheet.createRow(currentRow++); + title.createCell(0).setCellValue(""Inclusion Summary""); + + Row header = sheet.createRow(currentRow++); + header.createCell(0).setCellValue(""Inclusion Criteria""); + header.createCell(1).setCellValue(""Include""); + header.createCell(2).setCellValue(""Exclude""); + + for (Integer siteIdx : inclusions.keySet()) { + Row dataRow = sheet.createRow(currentRow++); + dataRow.createCell(0).setCellValue(inclusions.get(siteIdx)); + dataRow.createCell(1).setCellValue(studyMap.get(siteIdx).get(Value.Yes)); + dataRow.createCell(2).setCellValue(studyMap.get(siteIdx).get(Value.No)); + } + + return currentRow; + } + + private int writeStudyCriteriaTable(Sheet sheet, int currentRow) { + Row title = sheet.createRow(currentRow++); + title.createCell(0).setCellValue(""Criteria Summary""); + + Row header = sheet.createRow(currentRow++); + header.createCell(0).setCellValue(""Criteria""); + header.createCell(1).setCellValue(""Include""); + header.createCell(2).setCellValue(""Exclude""); + + for (Integer siteIdx : criteriaLabels.keySet()) { + Row dataRow = sheet.createRow(currentRow++); + dataRow.createCell(0).setCellValue(criteriaLabels.get(siteIdx)); + dataRow.createCell(1).setCellValue(studyCritMap.get(siteIdx).get(Value.Yes)); + dataRow.createCell(2).setCellValue(studyCritMap.get(siteIdx).get(Value.No)); + } + + return currentRow; + } + + private int writeInclusionTable(Sheet sheet, int currentRow, Value value) { + // initialize the inclusion totals to 0 + Map useHeaders = inclusions; + + Map inclusionTotals = Maps.newHashMap(); + for (int i=0; i exclusionTotals = Maps.newHashMap(); + for (Integer i : exclusions.keySet()) { + exclusionTotals.put(i, 0); + } + + Row titleRow = sheet.createRow(currentRow++); + titleRow.createCell(0).setCellValue(""Exclusion Summary (""+ItpcUtils.valueToExclusion(value)+"")""); + + Row headerRow = sheet.createRow(currentRow++); + headerRow.createCell(0).setCellValue(""Site ID""); + headerRow.createCell(1).setCellValue(""N""); + for (Integer i : exclusions.keySet()) { + headerRow.createCell(i+2).setCellValue(exclusions.get(i)); + } + + for (int i=0; i criteriaTotals = Maps.newHashMap(); + for (Integer i : criteriaLabels.keySet()) { + criteriaTotals.put(i, 0); + } + + Row titleRow = sheet.createRow(currentRow++); + titleRow.createCell(0).setCellValue(""Criteria (""+ItpcUtils.valueToInclusion(value)+"")""); + + Row headerRow = sheet.createRow(currentRow++); + headerRow.createCell(0).setCellValue(""Site ID""); + for (Integer i : criteriaLabels.keySet()) { + headerRow.createCell(i+1).setCellValue(criteriaLabels.get(i)); + } + + for (int i=0; i= 0) { + wb.removeSheetAt(sheetIdx); + } + sheet = wb.createSheet(getSheetTitle()); + + return sheet; + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","src/summary/MetabStatusSummary.java",".java","11927","255","/* + * ----- BEGIN LICENSE BLOCK ----- + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the ""License""); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an ""AS IS"" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code is PharmGen. + * + * The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + * and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + * created by the Initial Developer are Copyright (C) 2013 the Initial Developer. + * All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the ""GPL""), or the + * GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + * which case the provisions of the GPL or the LGPL are applicable instead of + * those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ----- END LICENSE BLOCK ----- + */ + +package summary; + +import com.google.common.collect.Maps; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.pharmgkb.Genotype; +import org.pharmgkb.Subject; +import util.GenotypeComparator; +import util.Value; + +import java.util.SortedMap; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Aug 3, 2010 + */ +public class MetabStatusSummary extends AbstractSummary { + private static final String sf_sheetTitle = ""Metabolizer Summary""; + private static final String[] metabTable = new String[]{ + ""Ultrarapid one (score 4.0)\tUM/UM (score 4)\tno\tno"", // 0 + ""Ultrarapid two (score 3.5)\tUM/UM (score 4)\tyes\tno"", // 1 + ""Ultrarapid three (score 3.0)\tEM/UM (score 3)\tno\tno"",// 2 + ""Extensive one (score 2.5)\tIM/UM (score 2.5)\tno\tno"", // 3 + ""Extensive one (score 2.5)\tEM/UM(score 3)\tyes\tno"", // 4 + ""Extensive two (score 2.0)\tEM/EM (score 2)\tno\tno"", // 5 + ""Extensive two (score 2.0)\tIM/UM (score 2.5)\tyes\tno"",// 6 + ""Extensive two (score 2.0)\tPM/UM (score 2)\tno\tno"", // 7 + ""Intermediate one (score 1.5)\tPM/IM (score 2.0)\tyes\tno"", // 8 + ""Intermediate one (score 1.5)\tEM/IM (score 1.5)\tno\tno"", // 9 + ""Intermediate one (score 1.5)\tEM/EM (score 2.0)\tyes\tno"", //10 + ""Intermediate two (score 1.0)\tIM/IM (score 1.0)\tno\tno"", //11 + ""Intermediate two (score 1.0)\tEM/PM (score 1.0)\tno\tno"", //12 + ""Intermediate two (score 1.0)\tEM/IM (score 1.5)\tyes\tno"", //13 + ""Intermediate three (score 0.5)\tEM/PM (score 1.0)\tyes\tno"", //14 + ""Intermediate three (score 0.5)\tIM/IM (score 1.0)\tyes\tno"", //15 + ""Intermediate three (score 0.5)\tPM/IM (score 0.5)\tno\tno"", //16 + ""Poor (score 0)\tunknown\tno\tyes"", //17 + ""Poor (score 0)\tany genotype\tno\tyes"", //18 + ""Poor (score 0)\tPM/IM (score 0.5)\tyes\tno"", //19 + ""Poor (score 0)\tPM/PM (score 0)\tyes\tno"", //20 + ""Poor (score 0)\tPM/PM (score 0)\tno\tno"", //21 + ""Poor (score 0)\tPM/PM (score 0)\tunknown\tunknown"",//22 + ""No Medication Data Available\t\t\t"", //23 + ""Uncategorized\t\t\t"" //24 + }; + protected int[] metabStatusTotals; + protected SortedMap metabStatusByAssignment = Maps.newTreeMap(); + protected SortedMap metabTypeMap = Maps.newTreeMap(GenotypeComparator.getComparator()); + + public MetabStatusSummary() { + metabStatusTotals = new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + metabStatusByAssignment.put(Genotype.EXTENSIVE, 0); + metabStatusByAssignment.put(Genotype.INTERMEDIATE, 0); + metabStatusByAssignment.put(Genotype.POOR, 0); + metabStatusByAssignment.put(Genotype.UNKNOWN, 0); + } + + public String getSheetTitle() { + return sf_sheetTitle; + } + + public void addSubject(Subject subject) { + if (subject != null) { + if (subject.getPotent() == Value.Yes && subject.getGenotypeFinal().isUnknown()) { + metabStatusTotals[17]++; + } + + else if (subject.getPotent() == Value.Yes) { + metabStatusTotals[18]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.UM,Genotype.Metabolizer.UM) && subject.getWeak() == Value.No) { + metabStatusTotals[0]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.UM,Genotype.Metabolizer.UM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[1]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.EM,Genotype.Metabolizer.UM) && subject.getWeak() == Value.No) { + metabStatusTotals[2]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.IM,Genotype.Metabolizer.UM) && subject.getWeak() == Value.No) { + metabStatusTotals[3]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.EM,Genotype.Metabolizer.UM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[4]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.EM,Genotype.Metabolizer.EM) && subject.getWeak() == Value.No) { + metabStatusTotals[5]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.IM,Genotype.Metabolizer.UM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[6]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.PM,Genotype.Metabolizer.UM) && subject.getWeak() == Value.No) { + metabStatusTotals[7]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.IM,Genotype.Metabolizer.PM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[8]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.EM, Genotype.Metabolizer.IM) && subject.getWeak() == Value.No) { + metabStatusTotals[9]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.EM,Genotype.Metabolizer.EM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[10]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.IM,Genotype.Metabolizer.IM) && subject.getWeak() == Value.No) { + metabStatusTotals[11]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.EM,Genotype.Metabolizer.PM) && subject.getWeak() == Value.No) { + metabStatusTotals[12]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.EM,Genotype.Metabolizer.IM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[13]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.EM,Genotype.Metabolizer.PM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[14]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.IM,Genotype.Metabolizer.IM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[15]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.IM,Genotype.Metabolizer.PM) && subject.getWeak() == Value.No) { + metabStatusTotals[16]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.IM,Genotype.Metabolizer.PM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[19]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.PM,Genotype.Metabolizer.PM) && subject.getWeak() == Value.Yes) { + metabStatusTotals[20]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.PM,Genotype.Metabolizer.PM) && subject.getWeak() == Value.No) { + metabStatusTotals[21]++; + } + else if (subject.getGenotypeFinal().is(Genotype.Metabolizer.PM,Genotype.Metabolizer.PM) && subject.getWeak() == Value.Unknown && subject.getPotent() == Value.Unknown) { + metabStatusTotals[22]++; + } + else if (subject.getWeak() == Value.Unknown && subject.getPotent() == Value.Unknown) { + metabStatusTotals[23]++; + } + else if (!(subject.getGenotypeFinal().isUnknown() && subject.getWeak() == Value.No && subject.getPotent() == Value.No)) { + // sf_logger.warn(""No metab. status for: "" + row.get(subjectId) + "" :: "" + metab.toString() + "" :: "" + subject.getWeak() + ""/"" + subject.getPotent()); + metabStatusTotals[24]++; + } + else { + // sf_logger.warn(""No matching logic for: "" + row.get(subjectId) + "" :: "" + metab.toString() + "" :: "" + subject.getWeak() + ""/"" + subject.getPotent()); + metabStatusTotals[24]++; + } + + String metabGroup = subject.getGenotypeFinal().getMetabolizerGroup(); + metabStatusByAssignment.put(metabGroup, metabStatusByAssignment.get(metabGroup) + 1); + + if (!metabTypeMap.containsKey(subject.getGenotypeFinal())) { + metabTypeMap.put(subject.getGenotypeFinal(), 1); + } + else { + metabTypeMap.put(subject.getGenotypeFinal(), metabTypeMap.get(subject.getGenotypeFinal())+1); + } + } + } + + public void writeToWorkbook(Workbook wb) { + Sheet sheet = getSheet(wb); + int currentRow = 0; + + Row header = sheet.createRow(currentRow++); + header.createCell(0).setCellValue(""CYP2D6 Metabolizer Status (column DQ)""); + header = sheet.createRow(currentRow++); + header.createCell(0).setCellValue(""Status""); + header.createCell(1).setCellValue(""n""); + + for (String group : metabStatusByAssignment.keySet()) { + Row data = sheet.createRow(currentRow++); + data.createCell(0).setCellValue(group); + data.createCell(1).setCellValue(metabStatusByAssignment.get(group)); + } + + currentRow += 3; + + header = sheet.createRow(currentRow++); + header.createCell(0).setCellValue(""CYP2D6 Metabolizer Types""); + header = sheet.createRow(currentRow++); + header.createCell(0).setCellValue(""Type""); + header.createCell(1).setCellValue(""n""); + + for (Genotype geno : metabTypeMap.keySet()) { + Row data = sheet.createRow(currentRow++); + if (geno.isUnknown()) { + data.createCell(0).setCellValue(""Unknown""); + } + else { + data.createCell(0).setCellValue(geno.getMetabolizerStatus()); + } + data.createCell(1).setCellValue(metabTypeMap.get(geno)); + } + + currentRow += 3; + + header = sheet.createRow(currentRow++); + header.createCell(0).setCellValue(""CYP2D6 Metabolizer Status based on Score (columns DR-DU)""); + header = sheet.createRow(currentRow++); + header.createCell(0).setCellValue(""Status (score)""); + header.createCell(1).setCellValue(""Function (score)""); + header.createCell(2).setCellValue(""Weak CYP2D6 Inhibitor Administered""); + header.createCell(3).setCellValue(""Potent CYP2D6 Inhibitor Administered""); + header.createCell(4).setCellValue(""n""); + + for (int i=0; i countMap = Maps.newHashMap(); + private Map sourceMap = Maps.newHashMap(); + private static final int fourHomo = 0; + private static final int fourHeto = 1; + private static final int fourNon = 2; + private static final int fourTotal = 3; + private SortedMap tumorFreqMap = Maps.newTreeMap(); + + public GenotypeSummary() { + int[] starFour = new int[]{0,0,0,0}; + sourceMap.put(Subject.SampleSource.TUMOR_FFP, starFour); + starFour = new int[]{0,0,0,0}; + sourceMap.put(Subject.SampleSource.BLOOD, starFour); + starFour = new int[]{0,0,0,0}; + sourceMap.put(Subject.SampleSource.BUCCAL, starFour); + starFour = new int[]{0,0,0,0}; + sourceMap.put(Subject.SampleSource.TUMOR_FROZEN, starFour); + starFour = new int[]{0,0,0,0}; + sourceMap.put(Subject.SampleSource.NORMAL_PARAFFIN, starFour); + starFour = new int[]{0,0,0,0}; + sourceMap.put(Subject.SampleSource.UNKNOWN, starFour); + for (int i=0; i<12; i++) { + tumorFreqMap.put(i, new int[]{0,0,0,0,0,0}); + } + } + + public String getSheetTitle() { + return sf_sheetTitle; + } + + public void addSubject(Subject subject) { + if (subject != null) { + int siteIdx = Integer.parseInt(subject.getProjectSite())-1; + + String key = subject.getGenotypeFinal().getMetabolizerGroup() + + ""|"" + subject.getWeak() + + ""|"" + subject.getPotent(); + + StarFourStatus status; + if (subject.getGenotypeFinal().is(""*4"",""*4"")) { + status = StarFourStatus.Homozygous; + } + else if (subject.getGenotypeFinal().contains(""*4"")) { + status = StarFourStatus.Heterozygous; + } + else { + status = StarFourStatus.NonFour; + } + + if (!countMap.containsKey(key)) { + countMap.put(key, 1); + } + else { + countMap.put(key, countMap.get(key)+1); + } + + if (subject.getSampleSources().size()>1) { + sf_logger.warn(""Multiple sample sources for ""+subject.getSubjectId()); + } + Subject.SampleSource source = subject.getSampleSources().iterator().next(); + + int[] totals = sourceMap.get(source); + totals[fourTotal]++; + switch (status) { + case Homozygous: + totals[fourHomo]++; + break; + case Heterozygous: + totals[fourHeto]++; + break; + default: + totals[fourNon]++; + } + + tumorFreqMap.get(siteIdx)[source.ordinal()]++; + } + } + + public void writeToWorkbook(Workbook wb) { + Sheet sheet = getSheet(wb); + + Row header = sheet.createRow(0); + header.createCell(0).setCellValue(""Metabolizer Group based on Genotype Only""); + header.createCell(1).setCellValue(""Weak""); + header.createCell(2).setCellValue(""Potent""); + header.createCell(3).setCellValue(""Count""); + + int rowNum = 1; + for (String key : countMap.keySet()) { + String[] fields = key.split(""\\|""); + Row data = sheet.createRow(rowNum); + data.createCell(0).setCellValue(fields[0]); + data.createCell(1).setCellValue(fields[1]); + data.createCell(2).setCellValue(fields[2]); + data.createCell(3).setCellValue(countMap.get(key)); + + rowNum++; + } + + // Tumor source table + Row row = sheet.createRow(++rowNum); + row.createCell(0).setCellValue(""*4 Status by Sample Source""); + row = sheet.createRow(++rowNum); + row.createCell(0).setCellValue(""Source""); + row.createCell(1).setCellValue(""Count""); + row.createCell(2).setCellValue(""*4 Homozygous""); + row.createCell(3).setCellValue(""*4 Heterozygous""); + row.createCell(4).setCellValue(""Non-*4""); + + for (Subject.SampleSource source : Subject.SampleSource.values()) { + row = sheet.createRow(++rowNum); + row.createCell(0).setCellValue(source.toString()); + row.createCell(1).setCellValue(sourceMap.get(source)[fourTotal]); + row.createCell(2).setCellValue(sourceMap.get(source)[fourHomo]); + row.createCell(3).setCellValue(sourceMap.get(source)[fourHeto]); + row.createCell(4).setCellValue(sourceMap.get(source)[fourNon]); + } + + rowNum++; + row = sheet.createRow(++rowNum); + row.createCell(0).setCellValue(""Sample Source by Site""); + row = sheet.createRow(++rowNum); + row.createCell(0).setCellValue(""Site""); + + int colMarker = 0; + for (Subject.SampleSource source : Subject.SampleSource.values()) { + row.createCell(colMarker*2+1).setCellValue(source.name()+"" N""); + row.createCell(colMarker*2+2).setCellValue(source.name()+"" %""); + colMarker++; + } + + int[] totals = new int[]{0,0,0,0,0,0,0,0,0,0,0,0}; + CellStyle pctStyle = sheet.getWorkbook().createCellStyle(); + DataFormat format = sheet.getWorkbook().createDataFormat(); + pctStyle.setDataFormat(format.getFormat(""0.0%"")); + + for (Integer i : tumorFreqMap.keySet()) { + row = sheet.createRow(++rowNum); + Integer siteTotal = tumorFreqMap.get(i)[Subject.SampleSource.TUMOR_FFP.ordinal()] + + tumorFreqMap.get(i)[Subject.SampleSource.TUMOR_FROZEN.ordinal()] + + tumorFreqMap.get(i)[Subject.SampleSource.BLOOD.ordinal()] + + tumorFreqMap.get(i)[Subject.SampleSource.BUCCAL.ordinal()] + + tumorFreqMap.get(i)[Subject.SampleSource.NORMAL_PARAFFIN.ordinal()] + + tumorFreqMap.get(i)[Subject.SampleSource.UNKNOWN.ordinal()]; + + Cell cell; + row.createCell(0).setCellValue(i+1); + + colMarker = 0; + for (Subject.SampleSource source : Subject.SampleSource.values()) { + Integer total = tumorFreqMap.get(i)[source.ordinal()]; + Float pct = (float)tumorFreqMap.get(i)[source.ordinal()] / (float)siteTotal; + + row.createCell(colMarker*2+1).setCellValue(total); + + cell = row.createCell(colMarker*2+2); + cell.setCellValue(pct); + cell.setCellStyle(pctStyle); + + totals[source.ordinal()]+=total; + colMarker++; + } + } + row = sheet.createRow(++rowNum); + int projectTotal = totals[Subject.SampleSource.TUMOR_FFP.ordinal()] + + totals[Subject.SampleSource.TUMOR_FROZEN.ordinal()] + + totals[Subject.SampleSource.NORMAL_PARAFFIN.ordinal()] + + totals[Subject.SampleSource.BLOOD.ordinal()] + + totals[Subject.SampleSource.BUCCAL.ordinal()] + + totals[Subject.SampleSource.UNKNOWN.ordinal()]; + + colMarker = 0; + for (Subject.SampleSource source : Subject.SampleSource.values()) { + row.createCell(colMarker*2+1).setCellValue(totals[source.ordinal()]); + + Cell cell = row.createCell(colMarker*2+2); + cell.setCellValue((float)totals[source.ordinal()] / (float)projectTotal); + cell.setCellStyle(pctStyle); + colMarker++; + } + } + + enum StarFourStatus {Homozygous, Heterozygous, NonFour} +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","test/ParserTest.java",".java","736","30","import junit.framework.TestCase; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Jul 27, 2010 + * Time: 8:08:29 AM + */ +public class ParserTest extends TestCase { + + public void testOpenFile() throws Exception { + Parser parser = new Parser(); + parser.parseArgs(new String[]{""-f"",""/Users/whaleyr/Documents/Workbench/ItpcParser/test/sample.data.xls""}); + + assertNotNull(parser.getFileInput()); + assertTrue(parser.getFileInput().exists()); + + try { + parser.parseFile(); + assertTrue(parser.dataSheet != null); + assertTrue(parser.dataSheet.getCurrentRowIndex()>0); + } + catch (Exception ex) { + ex.printStackTrace(); + fail(""Exception while parsing file\n"" + ex.getMessage()); + } + } + +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","test/org/pharmgkb/GenotypeTest.java",".java","2674","101","package org.pharmgkb; + +import junit.framework.Assert; +import junit.framework.TestCase; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Jul 14, 2010 + * Time: 4:16:25 PM + */ +public class GenotypeTest extends TestCase { + + public void testIs() { + Genotype genotype = new Genotype(); + + genotype.addString(""SpongeBob""); + + genotype.addString(""*1""); + genotype.addString(""*4""); + + assertTrue(genotype.is(""*4"",""*1"")); + + genotype = new Genotype(""*1/*4""); + assertTrue(genotype.is(""*4"",""*1"")); + + genotype = new Genotype(""*1"",""*4""); + assertTrue(genotype.is(""*4"",""*1"")); + } + + public void testIsUncertain() { + + Genotype genotype = new Genotype(""*1"",""Unknown""); + + assertTrue(genotype.isUncertain()); + + genotype.removeString(""Unknown""); + genotype.addString(""*3""); + + assertTrue(!genotype.isUncertain()); + + genotype = new Genotype(); + genotype.addString(""*1""); + assertTrue(genotype.isUncertain()); + + genotype = new Genotype(); + assertTrue(genotype.isUncertain()); + } + + public void testGetScore() { + Genotype genotype = new Genotype(""*1"",""*1""); + Assert.assertEquals(2f, genotype.getScore()); + + genotype = new Genotype(""*1"",""*9""); + Assert.assertEquals(1.5f, genotype.getScore()); + + genotype = new Genotype(""*3"",""*9""); + Assert.assertEquals(0.5f, genotype.getScore()); + + genotype = new Genotype(""*1XN"",""*1XN""); + Assert.assertEquals(4.0f, genotype.getScore()); + } + + public void testAdd() { + Genotype genotype = new Genotype(""*1XN"",""*1XN""); + genotype.addString(""*1""); + + assertTrue(genotype.is(""*1"",""*1XN"")); + + genotype.addString(""*1XN""); + assertTrue(genotype.is(""*1"",""*1XN"")); + } + + public void testGetMetabolizerStatus() { + Genotype genotype = new Genotype(""*1"",""*1""); + Assert.assertEquals(""EM/EM"", genotype.getMetabolizerStatus()); + + genotype = new Genotype(""*1"",""*3""); + Assert.assertEquals(""EM/PM"", genotype.getMetabolizerStatus()); + + genotype = new Genotype(""*1XN"",""*3""); + Assert.assertEquals(""PM/UM"", genotype.getMetabolizerStatus()); + + genotype = new Genotype(""*1XN"",""*9""); + Assert.assertEquals(""IM/UM"", genotype.getMetabolizerStatus()); + Assert.assertEquals(""Unknown"", genotype.getMetabolizerGroup()); + + genotype = new Genotype(""*3"",""*1XN""); + Assert.assertEquals(""PM/UM"", genotype.getMetabolizerStatus()); + Assert.assertEquals(""Unknown"", genotype.getMetabolizerGroup()); + } + + public void testToString() { + Genotype unknownGenotype = new Genotype(""Unknown/*1""); + Assert.assertEquals(""*1/Unknown"", unknownGenotype.toString()); + + Genotype genotype = new Genotype(""*3/*1""); + Assert.assertEquals(""*1/*3"", genotype.toString()); + } +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","test/org/pharmgkb/SubjectTest.java",".java","19324","591","package org.pharmgkb; + +import junit.framework.Assert; +import junit.framework.TestCase; +import util.Med; +import util.Value; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Jul 14, 2010 + * Time: 8:57:30 PM + */ +public class SubjectTest extends TestCase { + public void testGetScore() { + Subject subject = new Subject(); + + assertNull(subject.getScore()); + + /* Getting a score when genotype data is available but inhibitor information is not should be null */ + + Genotype genotype = new Genotype(""*1/*1""); + subject.setGenotypePgkb(genotype); + + assertEquals(2.0f, subject.getScore()); + + /* First successful test, genotype and drug information is all available */ + + weaksToNo(subject); + potentToNo(subject); + + Assert.assertEquals(2f, subject.getScore()); + Assert.assertEquals(""Extensive two"", subject.getMetabolizerGroup()); + + /* Test to see if PM/PM with unknown inhibitors returns the correct values */ + + subject = new Subject(); + subject.setGenotypePgkb(new Genotype(""*3/*3"")); + Assert.assertEquals(0f, subject.getScore()); + Assert.assertEquals(""Poor"", subject.getMetabolizerGroup()); + } + + public void testCalculateGenotypePgkb() { + Subject subject = new Subject(); + Assert.assertEquals(""Unknown/Unknown"",subject.getGenotypePgkb().toString()); + subject.setDeletion(""no deletion""); + + VariantAlleles va1 = new VariantAlleles(""a/-""); + subject.setRs4986774(va1); + va1 = new VariantAlleles(""c/c""); + subject.setRs1065852(va1); + va1 = new VariantAlleles(""g/g""); + subject.setRs3892097(va1); + va1 = new VariantAlleles(""t/t""); + subject.setRs5030655(va1); + + Assert.assertEquals(""*3/Unknown"",subject.getGenotypePgkb().toString()); + + va1 = new VariantAlleles(""c/c""); + subject.setRs16947(va1); + va1 = new VariantAlleles(""c/c""); + subject.setRs28371706(va1); + va1 = new VariantAlleles(""g/g""); + subject.setRs28371725(va1); + + Assert.assertEquals(""*1/*3"",subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + Assert.assertEquals(""*1/*1"",subject.getGenotypePgkb().toString()); + + subject.setDeletion(""deletion""); + Assert.assertEquals(""*1/*5"",subject.getGenotypePgkb().toString()); + } + + public void testStarFour() { + Subject subject = makeDefaultSubject(); + + subject.setRs1065852(new VariantAlleles(""t/t"")); + subject.setRs3892097(new VariantAlleles(""a/a"")); + + Assert.assertEquals(""*4/*4"", subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + + subject.setRs1065852(new VariantAlleles(""c/t"")); + subject.setRs3892097(new VariantAlleles(""g/a"")); + + Assert.assertEquals(""*1/*4"", subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + subject.setRs1065852(new VariantAlleles(""c/t"")); + subject.setRs3892097(new VariantAlleles(""g/a"")); + subject.setRs16947(new VariantAlleles(""c/t"")); + Assert.assertEquals(""*4/Unknown"", subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + subject.setRs1065852(new VariantAlleles(""c/t"")); + subject.setRs3892097(new VariantAlleles(""g/a"")); + subject.setRs16947(new VariantAlleles(""t/t"")); + Assert.assertEquals(""*2/*4"", subject.getGenotypePgkb().toString()); + } + + public void testStarFive() { + Subject subject = makeDefaultSubject(); + subject.setDeletion(Subject.Deletion.Hetero); + Assert.assertEquals(""*1/*5"", subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + subject.setDeletion(Subject.Deletion.Unknown); + Assert.assertEquals(""*1/Unknown"", subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + subject.setDeletion(Subject.Deletion.Unknown); + subject.setRs3892097(new VariantAlleles(""a/a"")); + subject.setRs1065852(new VariantAlleles(null)); + subject.setRs5030655(new VariantAlleles(null)); + subject.setRs16947(new VariantAlleles(null)); + subject.setRs28371706(new VariantAlleles(null)); + Assert.assertEquals(""*4/Unknown"", subject.getGenotypePgkb().toString()); + } + + public void testStarTwo() { + Subject subject = makeDefaultSubject(); + Assert.assertEquals(""*1/*1"", subject.getGenotypePgkb().toString()); + + subject.setRs16947(new VariantAlleles(""c/t"")); + Assert.assertEquals(""*1/*2"", subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + subject.setRs16947(new VariantAlleles(""t/t"")); + Assert.assertEquals(""*2/*2"", subject.getGenotypePgkb().toString()); + } + + public void testStarSeventeen() { + Subject subject = makeDefaultSubject(); + subject.setRs16947(new VariantAlleles(""c/t"")); + subject.setRs28371706(new VariantAlleles(""c/t"")); + Assert.assertEquals(""*1/*17"", subject.getGenotypePgkb().toString()); + + makeDefaultSubject(); + subject.setRs16947(new VariantAlleles(""t/t"")); + subject.setRs28371706(new VariantAlleles(""c/t"")); + Assert.assertEquals(""*2/*17"", subject.getGenotypePgkb().toString()); + + makeDefaultSubject(); + subject.setRs16947(new VariantAlleles(""t/t"")); + subject.setRs28371706(new VariantAlleles(""t/t"")); + Assert.assertEquals(""*17/*17"", subject.getGenotypePgkb().toString()); + } + + public void testStarFortyone() { + Subject subject = makeDefaultSubject(); + subject.setRs16947(new VariantAlleles(""c/t"")); + subject.setRs28371725(new VariantAlleles(""g/a"")); + Assert.assertEquals(""*1/*41"", subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + subject.setRs16947(new VariantAlleles(""t/t"")); + subject.setRs28371725(new VariantAlleles(""g/a"")); + Assert.assertEquals(""*2/*41"", subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + subject.setRs16947(new VariantAlleles(""t/t"")); + subject.setRs28371725(new VariantAlleles(""a/a"")); + Assert.assertEquals(""*41/*41"", subject.getGenotypePgkb().toString()); + } + + public void testStarTen() { + Subject subject = makeDefaultSubject(); + subject.setRs1065852(new VariantAlleles(""c/t"")); + Assert.assertEquals(""*1/*10"", subject.getGenotypePgkb().toString()); + + subject = makeDefaultSubject(); + subject.setRs16947(new VariantAlleles(""c/t"")); + subject.setRs1065852(new VariantAlleles(""c/t"")); + Assert.assertEquals(""*2/*10"", subject.getGenotypePgkb().toString()); + } + + public void testCallsWithUnknownData() { + Subject subject = makeDefaultSubject(); + subject.setRs16947(new VariantAlleles(""c/t"")); + subject.setRs28371706(new VariantAlleles(null)); + subject.setRs28371725(new VariantAlleles(""a/g"")); + Assert.assertEquals(""*1/*41"", subject.getGenotypePgkb().toString()); + } + + public void testLimitedCalls() { + Subject subject = makeDefaultSubject(); + subject.setRs5030655(new VariantAlleles(null)); + assertEquals(""Unknown/Unknown"", subject.getGenotypeFinal().toString()); + subject.calculateGenotypeLimited(); + assertEquals(""*1/*1"", subject.getGenotypeLimited().toString()); + + subject = makeDefaultSubject(); + subject.setRs5030655(new VariantAlleles(null)); + subject.setRs3892097(new VariantAlleles(""g/a"")); + subject.setDeletion(Subject.Deletion.Unknown); + assertEquals(""*4/Unknown"", subject.getGenotypeFinal().toString()); + subject.calculateGenotypeLimited(); + assertEquals(""*1/*4"", subject.getGenotypeLimited().toString()); + } + + public void testSetGenotypeAmplichip() { + Subject subject = makeDefaultSubject(); + try { + subject.setGenotypeAmplichip(""*1AXN/*3B""); + Assert.assertEquals(""*1AXN/*3B"",subject.getGenotypeAmplichip().toString()); + + subject.setGenotypeAmplichip(""*1axn/*3""); + Assert.assertEquals(""*1axn/*3"",subject.getGenotypeAmplichip().toString()); + + subject.setGenotypeAmplichip(""*1/*1""); + Assert.assertEquals(""*1/*1"",subject.getGenotypeAmplichip().toString()); + + subject.setGenotypeAmplichip(""*1/*2A""); + subject.setRs1065852(new VariantAlleles("""")); + subject.setRs3892097(new VariantAlleles("""")); + Assert.assertEquals(""*1/*2A"",subject.getGenotypeAmplichip().toString()); + Assert.assertEquals(""*1/*2A"",subject.getGenotypeFinal().toString()); + Assert.assertEquals(""EM/EM"",subject.getGenotypeFinal().getMetabolizerStatus()); + } + catch (Exception ex) { + fail(""Couldn't parse amplichip""); + } + } + + public void testInclusion1() { + Subject subject = new Subject(); + Assert.assertEquals(Value.Unknown, subject.passInclusion1()); + + subject.setGender(""2""); + Assert.assertEquals(Value.No, subject.passInclusion1()); + subject.setGender(""1""); + + subject.setMenoStatus(""1""); + Assert.assertEquals(Value.No, subject.passInclusion1()); + + subject.setMenoStatus(""2""); + Assert.assertEquals(Value.Yes, subject.passInclusion1()); + + subject.setMenoStatus(null); + subject.setAge(""49""); + Assert.assertEquals(Value.No, subject.passInclusion1()); + + subject.setAge(""51""); + Assert.assertEquals(Value.Yes, subject.passInclusion1()); + } + + public void testInclusion2a() { + Subject subject = new Subject(); + Assert.assertEquals(Value.No, subject.passInclusion2a()); + + subject.setMetastatic(""0""); + Assert.assertEquals(Value.Yes, subject.passInclusion2a()); + + subject.setMetastatic(""1""); + Assert.assertEquals(Value.No, subject.passInclusion2a()); + + subject.setMetastatic(""SpongeBob""); + Assert.assertEquals(Value.No, subject.passInclusion2a()); + } + + public void testInclusion2b() { + Subject subject = new Subject(); + Assert.assertEquals(Value.Yes, subject.passInclusion2b()); + + subject.setPriorHistory(""0""); + subject.setPriorDcis(""0""); + Assert.assertEquals(Value.Yes, subject.passInclusion2b()); + + subject.setPriorHistory(""1""); + subject.setPriorDcis(""0""); + Assert.assertEquals(Value.No, subject.passInclusion2b()); + + subject.setPriorHistory(""0""); + subject.setPriorDcis(""1""); + Assert.assertEquals(Value.No, subject.passInclusion2b()); + } + + public void testInclusion3() { + Subject subject = new Subject(); + Assert.assertEquals(Value.No, subject.passInclusion3()); + + subject.setErStatus(""0""); + Assert.assertEquals(Value.No, subject.passInclusion3()); + + subject.setErStatus(""1""); + Assert.assertEquals(Value.Yes, subject.passInclusion3()); + + subject.setErStatus(""SpongeBob""); + Assert.assertEquals(Value.No, subject.passInclusion3()); + } + + public void testInclusion4() { + Subject subject = new Subject(); + Assert.assertEquals(Value.Yes, subject.passInclusion4()); + + subject.setSystemicTher(""0""); + Assert.assertEquals(Value.Yes, subject.passInclusion4()); + + subject.setSystemicTher(""1""); + Assert.assertEquals(Value.No, subject.passInclusion4()); + + subject.setSystemicTher(""2""); + Assert.assertEquals(Value.Yes, subject.passInclusion4()); + + subject.setSystemicTher(""SpongeBob""); + Assert.assertEquals(Value.Yes, subject.passInclusion4()); + } + + public void testInclusion4a() { + Subject subject = new Subject(); + Assert.assertEquals(Value.No, subject.passInclusion4a()); + + subject.setTimeBtwSurgTamox(""200""); + subject.setFirstAdjEndoTher(""0""); + Assert.assertEquals(Value.No, subject.passInclusion4a()); + + subject.setTimeBtwSurgTamox(""180""); + subject.setFirstAdjEndoTher(""0""); + Assert.assertEquals(Value.No, subject.passInclusion4a()); + + subject.setTimeBtwSurgTamox(""180""); + subject.setFirstAdjEndoTher(""1""); + Assert.assertEquals(Value.Yes, subject.passInclusion4a()); + + subject.setTimeBtwSurgTamox(""Spongebob""); + subject.setFirstAdjEndoTher(""1""); + Assert.assertEquals(Value.No, subject.passInclusion4a()); + + subject.setTimeBtwSurgTamox(""< 6 weeks""); + subject.setFirstAdjEndoTher(""1""); + Assert.assertEquals(Value.Yes, subject.passInclusion4a()); + + subject.setTimeBtwSurgTamox(""28-42""); + subject.setFirstAdjEndoTher(""1""); + Assert.assertEquals(Value.Yes, subject.passInclusion4a()); + + } + + public void testInclusion4b() { + Subject subject = new Subject(); + Assert.assertEquals(Value.No, subject.passInclusion4b()); + + subject.setDuration(""1""); + Assert.assertEquals(Value.No, subject.passInclusion4b()); + + subject.setDuration(""0""); + Assert.assertEquals(Value.Yes, subject.passInclusion4b()); + + subject.setDuration(""SpongeBob""); + Assert.assertEquals(Value.No, subject.passInclusion4b()); + } + + public void testInclusion4c() { + Subject subject = new Subject(); + Assert.assertEquals(Value.No, subject.passInclusion4c()); + + subject.setTamoxDose(""1""); + Assert.assertEquals(Value.No, subject.passInclusion4c()); + + subject.setTamoxDose(""0""); + Assert.assertEquals(Value.Yes, subject.passInclusion4c()); + + subject.setTamoxDose(""SpongeBob""); + Assert.assertEquals(Value.No, subject.passInclusion4c()); + } + + public void testInclusion5() { + Subject subject = new Subject(); + Assert.assertEquals(Value.No, subject.passInclusion5()); + + subject.setChemotherapy(""0""); + Assert.assertEquals(Value.Yes, subject.passInclusion5()); + + subject.setChemotherapy(""1""); + Assert.assertEquals(Value.No, subject.passInclusion5()); + } + + public void testInclusion6() { + Subject subject = new Subject(); + Assert.assertEquals(Value.Yes, subject.passInclusion6()); + + subject.setHormoneTherapy(""0""); + Assert.assertEquals(Value.Yes, subject.passInclusion6()); + + subject.setHormoneTherapy(""1""); + Assert.assertEquals(Value.No, subject.passInclusion6()); + } + + public void testInclusion7() { + Subject subject = new Subject(); + Assert.assertEquals(Value.No, subject.passInclusion7()); + + subject.addSampleSource(Subject.SampleSource.TUMOR_FFP); + Assert.assertEquals(Value.No, subject.passInclusion7()); + + subject.setTumorSource(""1""); + Assert.assertEquals(Value.Yes, subject.passInclusion7()); + + subject.getSampleSources().clear(); + subject.addSampleSource(Subject.SampleSource.BLOOD); + subject.setBloodSource(""3""); + Assert.assertEquals(Value.No, subject.passInclusion7()); + + subject.getSampleSources().clear(); + subject.addSampleSource(Subject.SampleSource.BLOOD); + subject.setBloodSource(""2""); + Assert.assertEquals(Value.Yes, subject.passInclusion7()); + } + + public void testInclusion8() { + Subject subject = new Subject(); + Assert.assertEquals(Value.Yes, subject.passInclusion8()); + + subject.setFollowup(""2""); + Assert.assertEquals(Value.No, subject.passInclusion8()); + + subject.setFollowup(""1""); + Assert.assertEquals(Value.Yes, subject.passInclusion8()); + } + + public void testInclusion9() { + Subject subject = new Subject(); + Assert.assertEquals(Value.No, subject.passInclusion9()); + + subject = makeDefaultSubject(); + Assert.assertEquals(Value.Yes, subject.passInclusion9()); + + subject.setRs1065852(new VariantAlleles()); + Assert.assertEquals(Value.No, subject.passInclusion9()); + } + + public void testInclude() { + Subject subject = makeDefaultSubject(); + setPhenotypes(subject); + Assert.assertEquals(Value.Yes, subject.include()); + + subject.setFollowup(""2""); + Assert.assertEquals(Value.No, subject.include()); + } + + public void testIncludeWo4a() { + Subject subject = makeDefaultSubject(); + setPhenotypes(subject); + Assert.assertEquals(Value.Yes, subject.includeWo4a()); + + subject.setTimeBtwSurgTamox(""200""); + Assert.assertEquals(Value.Yes, subject.includeWo4a()); + + subject.setFollowup(""2""); + Assert.assertEquals(Value.No, subject.includeWo4a()); + } + + public void testGenoMetabolizerGroup() { + Subject subject = makeDefaultSubject(); + subject.setGenotypeAmplichip(""*1/*1""); + Assert.assertEquals(""Extensive"", subject.getGenotypeFinal().getMetabolizerGroup()); + + subject.setGenotypeAmplichip(""*4/*4""); + Assert.assertEquals(""Poor"", subject.getGenotypeFinal().getMetabolizerGroup()); + + subject.setGenotypeAmplichip(""*41/*41""); + Assert.assertEquals(""Intermediate"", subject.getGenotypeFinal().getMetabolizerGroup()); + } + + public void testGetDiagToEventDays() { + Subject subject = makeDefaultSubject(); + subject.setAdditionalCancer(Value.Yes); + subject.setAddCxIpsilateral(""1234""); + subject.setPatientDied(Value.No); + + assertEquals(""1234"", subject.getDiagToEventDaysCalc()); + } + + + public void testExclude1() { + Subject subject = makeDefaultSubject(); + subject.setAdditionalCancer(Value.Unknown); + subject.setAddCxIpsilateral(""123""); + + assertEquals(Value.Yes, subject.exclude1()); + } + + public void testExclude4() { + Subject subject = makeDefaultSubject(); + subject.setAdditionalCancer(Value.Yes); + subject.setDiseaseFreeSurvivalTime(""123""); + + assertEquals(Value.Yes, subject.exclude4()); + + subject = makeDefaultSubject(); + subject.setDiseaseFreeSurvivalTime(""456""); + + assertEquals(Value.No, subject.exclude4()); + } + + public void testExclude5() { + Subject subject = makeDefaultSubject(); + subject.setPatientDied(Value.Yes); + subject.setSurvivalNotDied(""122""); + + assertEquals(Value.Yes, subject.exclude5()); + + subject.setPatientDied(Value.No); + subject.setSurvivalNotDied(""122""); + + assertEquals(Value.No, subject.exclude5()); + + subject.setPatientDied(Value.Yes); + subject.setSurvivalNotDied(null); + + assertEquals(Value.No, subject.exclude5()); + } + + public void testExclude6() { + Subject subject = makeDefaultSubject(); + subject.setDiseaseFreeSurvivalTime(""10""); + subject.setAddCxLastEval(""12""); + subject.setSurvivalNotDied(""14""); + + assertEquals(Value.Yes, subject.exclude6()); + + subject.setDiseaseFreeSurvivalTime(""15""); + + assertEquals(Value.No, subject.exclude6()); + + subject.setAddCxLastEval(""16""); + + assertEquals(Value.Yes, subject.exclude6()); + } + + private void setPhenotypes(Subject subject) { + subject.setMenoStatus(""2""); + subject.setMetastatic(""0""); + subject.setPriorHistory(""0""); + subject.setPriorDcis(""0""); + subject.setErStatus(""1""); + subject.setSystemicTher(""2""); + subject.setTimeBtwSurgTamox(""180""); + subject.setFirstAdjEndoTher(""1""); + subject.setDuration(""0""); + subject.setTamoxDose(""0""); + subject.setChemotherapy(""0""); + subject.setHormoneTherapy(""0""); + subject.addSampleSource(Subject.SampleSource.BLOOD); + subject.setBloodSource(""2""); + subject.setFollowup(""1""); + } + + private void weaksToNo(Subject subject) { + subject.addMedStatus(Med.Cimetidine, Value.No); + subject.addMedStatus(Med.Sertraline, Value.No); + subject.addMedStatus(Med.Citalopram, Value.No); + } + + private void potentToNo(Subject subject) { + subject.addMedStatus(Med.Paroxetine, Value.No); + subject.addMedStatus(Med.Fluoxetine, Value.No); + subject.addMedStatus(Med.Quinidine, Value.No); + subject.addMedStatus(Med.Buproprion, Value.No); + subject.addMedStatus(Med.Duloxetine, Value.No); + } + + private Subject makeDefaultSubject() { + Subject subject = new Subject(); + + weaksToNo(subject); + potentToNo(subject); + subject.setDeletion(""no deletion""); + + VariantAlleles va1 = new VariantAlleles(""a/a""); + subject.setRs4986774(va1); + va1 = new VariantAlleles(""c/c""); + subject.setRs1065852(va1); + va1 = new VariantAlleles(""g/g""); + subject.setRs3892097(va1); + va1 = new VariantAlleles(""t/t""); + subject.setRs5030655(va1); + va1 = new VariantAlleles(""c/c""); + subject.setRs16947(va1); + va1 = new VariantAlleles(""c/c""); + subject.setRs28371706(va1); + va1 = new VariantAlleles(""g/g""); + subject.setRs28371725(va1); + + return subject; + } + +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","test/org/pharmgkb/VariantAllelesTest.java",".java","658","32","package org.pharmgkb; + +import junit.framework.TestCase; +import util.StringPair; + +/** + * Created by IntelliJ IDEA. + * User: whaleyr + * Date: Aug 11, 2010 + */ +public class VariantAllelesTest extends TestCase { + + public void testVariantAlleles() { + + /* Testing typical assignments */ + VariantAlleles va = new VariantAlleles(""A/A""); + assertTrue(va.is(""a"",""a"")); + + va = new VariantAlleles(""G/C""); + assertTrue(va.is(""g"",""c"")); + assertTrue(va.is(""c"",""g"")); // order shouldn't matter + + va = new VariantAlleles(""-/-""); + assertTrue(va.is(""-"",""-"")); + + va = new VariantAlleles(""T/NA""); + assertTrue(va.is(""t"", StringPair.UNKNOWN)); + + } + +} +","Java" +"Pharmacogenomics","PharmGKB/ITPC","test/org/pharmgkb/ItpcSheetTest.java",".java","6709","172","package org.pharmgkb;/* + ----- BEGIN LICENSE BLOCK ----- + Version: MPL 1.1/GPL 2.0/LGPL 2.1 + + The contents of this file are subject to the Mozilla Public License Version + 1.1 (the ""License""); you may not use this file except in compliance with the + License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ + + Software distributed under the License is distributed on an ""AS IS"" basis, + WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + the specific language governing rights and limitations under the License. + + The Original Code is PharmGen. + + The Initial Developer of the Original Code is PharmGKB (The Pharmacogenetics + and Pharmacogenetics Knowledge Base, supported by NIH U01GM61374). Portions + created by the Initial Developer are Copyright (C) 2010 the Initial Developer. + All Rights Reserved. + + Contributor(s): + + Alternatively, the contents of this file may be used under the terms of + either the GNU General Public License Version 2 or later (the ""GPL""), or the + GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), in + which case the provisions of the GPL or the LGPL are applicable instead of + those above. If you wish to allow use of your version of this file only + under the terms of either the GPL or the LGPL, and not to allow others to + use your version of this file under the terms of the MPL, indicate your + decision by deleting the provisions above and replace them with the notice + and other provisions required by the GPL or the LGPL. If you do not delete + the provisions above, a recipient may use your version of this file under + the terms of any one of the MPL, the GPL or the LGPL. + + ----- END LICENSE BLOCK ----- + */ +import junit.framework.Assert; +import junit.framework.TestCase; +import org.apache.poi.ss.usermodel.Row; +import util.Value; + +import java.io.File; + + +/** + * Created by IntelliJ IDEA. User: whaleyr Date: Jun 18, 2010 Time: 10:51:19 AM To change this template use File | + * Settings | File Templates. + */ +public class ItpcSheetTest extends TestCase { + + File file = null; + + public void setUp() throws Exception { + file = new File(""/Users/whaleyr/Documents/Workbench/ItpcParser/test/sample.data.xls""); + } + + public void testParseColumnIndexes() throws Exception { + ItpcSheet sheet = new ItpcSheet(file, false); + + assertTrue(sheet.ageIdx>=0); + assertTrue(sheet.genderIdx>=0); + assertTrue(sheet.subjectId>=0); + assertTrue(sheet.projectSiteIdx>=0); + assertTrue(sheet.ageIdx>=0); + assertTrue(sheet.menoStatusIdx>=0); + assertTrue(sheet.metastaticIdx>=0); + assertTrue(sheet.erStatusIdx>=0); + assertTrue(sheet.durationIdx>=0); + assertTrue(sheet.tamoxDoseIdx>=0); + assertTrue(sheet.tumorSourceIdx>=0); + assertTrue(sheet.bloodSourceIdx>=0); + assertTrue(sheet.priorHistoryIdx>=0); + assertTrue(sheet.priorSitesIdx>=0); + assertTrue(sheet.priorDcisIdx>=0); + assertTrue(sheet.chemoIdx>=0); + assertTrue(sheet.hormoneIdx>=0); + assertTrue(sheet.systemicTherIdx>=0); + assertTrue(sheet.followupIdx>=0); + assertTrue(sheet.timeBtwSurgTamoxIdx>=0); + assertTrue(sheet.firstAdjEndoTherIdx>=0); + assertEquals(7, sheet.sampleSourceIdxs.size()); + assertTrue(sheet.otherGenoIdx>=0); + + assertTrue(sheet.fluoxetineCol>=0); + assertTrue(sheet.paroxetineCol>=0); + assertTrue(sheet.quinidienCol>=0); + assertTrue(sheet.buproprionCol>=0); + assertTrue(sheet.duloxetineCol>=0); + assertTrue(sheet.cimetidineCol>=0); + assertTrue(sheet.sertralineCol>=0); + assertTrue(sheet.citalopramCol>=0); + + assertTrue(sheet.rs4986774idx>=0); + assertTrue(sheet.rs1065852idx>=0); + assertTrue(sheet.rs3892097idx>=0); + assertTrue(sheet.star5idx>=0); + assertTrue(sheet.rs5030655idx>=0); + assertTrue(sheet.rs16947idx>=0); + assertTrue(sheet.rs28371706idx>=0); + assertTrue(sheet.rs28371725idx>=0); + + assertTrue(sheet.amplichipidx>=0); + + assertTrue(sheet.allele1finalIdx>=0); + assertTrue(sheet.allele2finalIdx>=0); + assertTrue(sheet.genotypeIdx>=0); + assertTrue(sheet.weakIdx>=0); + assertTrue(sheet.potentIdx>=0); + assertTrue(sheet.metabStatusIdx>=0); + assertTrue(sheet.scoreIdx>=0); + + assertTrue(sheet.incAgeIdx>=0); + assertTrue(sheet.incNonmetaIdx>=0); + assertTrue(sheet.incPriorHistIdx>=0); + assertTrue(sheet.incErPosIdx>=0); + assertTrue(sheet.incSysTherIdx>=0); + assertTrue(sheet.incAdjTamoxIdx>=0); + assertTrue(sheet.incDurationIdx>=0); + assertTrue(sheet.incTamoxDoseIdx>=0); + assertTrue(sheet.incChemoIdx>=0); + assertTrue(sheet.incHormoneIdx>=0); + assertTrue(sheet.incDnaCollectionIdx>=0); + assertTrue(sheet.incFollowupIdx>=0); + assertTrue(sheet.incGenoDataAvailIdx>=0); + } + + public void testNext() throws Exception { + ItpcSheet sheet = new ItpcSheet(file, false); + + assertTrue(sheet.hasNext()); + + Subject subject = sheet.next(); + assertNotNull(subject); + Assert.assertEquals(2,sheet.getCurrentRowIndex()); + + Assert.assertEquals(""ID1"", subject.getSubjectId()); + String subject1 = subject.getSubjectId(); + Assert.assertEquals(""999"", subject.getProjectSite()); + Assert.assertEquals(""1"", subject.getGender()); + + Assert.assertEquals(""Unknown/Unknown"",subject.getGenotypePgkb().toString()); + Assert.assertEquals(""*1/*1"",subject.getGenotypeFinal().toString()); + + Assert.assertEquals(""EM/EM"",subject.getGenotypeFinal().getMetabolizerStatus()); + + Assert.assertEquals(Value.Unknown, subject.getWeak()); + Assert.assertEquals(Value.Unknown, subject.getPotent()); + + Assert.assertEquals(Value.Yes, subject.passInclusion1()); + Assert.assertEquals(Value.Yes, subject.passInclusion2a()); + Assert.assertEquals(Value.Yes, subject.passInclusion2b()); + Assert.assertEquals(Value.Yes, subject.passInclusion3()); + Assert.assertEquals(Value.No, subject.passInclusion4()); + Assert.assertEquals(Value.No, subject.passInclusion4a()); + Assert.assertEquals(Value.Yes, subject.passInclusion4b()); + Assert.assertEquals(Value.Yes, subject.passInclusion4c()); + Assert.assertEquals(Value.Yes, subject.passInclusion5()); + Assert.assertEquals(Value.Yes, subject.passInclusion6()); + Assert.assertEquals(Value.Yes, subject.passInclusion7()); + Assert.assertEquals(Value.Yes, subject.passInclusion8()); + Assert.assertEquals(Value.Yes, subject.passInclusion9()); + Assert.assertEquals(Value.No, subject.include()); + + assertTrue(sheet.hasNext()); + subject = sheet.next(); + Assert.assertEquals(3,sheet.getCurrentRowIndex()); + assertFalse(subject1.equals(subject.getSubjectId())); + + Row row = sheet.getCurrentRow(); + Assert.assertEquals(subject.getSubjectId(), row.getCell(sheet.subjectId).getStringCellValue()); + } +} +","Java" +"Pharmacogenomics","bhklab/PharmacoGx","codecover.R",".R","107","6","Sys.unsetenv(""R_TESTS"") + +library(covr) +options(covr.fix_parallel_mcexit=TRUE) +covr::codecov(quiet = FALSE) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","CONTRIBUTING.md",".md","1187","26","# Contributing to PharmacoGx + +Thank you for taking your time to contribute to the PharmacoGx project. + +## Code of Conduct + +Please review and follow the [code of conduct](https://github.com/bhklab/PharmacoGx/blob/master/CODE_OF_CONDUCT.md) for the PharmacoGx Project. + +## How Can I Contribute? + +### Discussing or Suggesting a New Feature + +* When contributing to PharmacoGx, please first **discuss the change you wish to make via [Issues](https://github.com/PharmacoGx/issues)**. + +### Reporting Bugs + +* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/PharmacoGx/issues). + +* If you are unable to find an open issue addressing the problem, [open a new one](https://github.com/bhklab/PharmacoGx/issues/new). Be sure to include a **title and clear description**, as much relevant information as possible, and a **code sample** or an **executable test case** demonstrating the expected behavior that is not occurring. + +### Code Contribution + +* Checkout the **development** branch, add your changes, ensure the package builds, then commit to the **development** branch. + +* Once the changes are commited, make a pull request to master branch. +","Markdown" +"Pharmacogenomics","bhklab/PharmacoGx","NEWS.md",".md","2825","64","# Package Release News + +# 3.13.1 +- Updated *only* the `sessionInfo` fields example data sets due to errors + + +# 3.3.2 +- Debugging vignette issues on the Bioconductor build system + +# 3.3.1 +- Added new vignette documenting support for drug combination modelling new +drug combination features added in PharmacoGx >=3.0 + +# 3.1.4 +- Modified downloadPSet function to automatically update the PharmacoSet class structure and resave the updated object after download +- This work around is necessary until we can rerun our data engineering pipelines to regenerate all of our PharmacoSet using the 3.1.0 package updates +- Added a number of additional methods for computing drug synergy metrics + +# 3.1.1 + +## 3.1.0 +- Update to slot names ""cell"" -> ""sample"" and ""drug"" -> ""treatment"" +- Update standardized identifier column names to match the above slot nomenclature: ""cellid"" -> ""sampleid"", ""drugid"" -> ""treatmentid"" + +# 2.5 + +## 2.5.3 +- Added PharmacoSet2 constructor to allow creation of PSets with updated class definition introducted in BioC 3.13 +- The sensitivity slot is now required to be a TreatmentResponseExperiment +- The molecularProfiles slot is now required to be a MultiAssayExperiment +- The original constructor and all accessors remain in the package for full backwards compatibility + +## v2.5.2 +- Fix: remove 'fdr' item from geneDrugSensitivity return vector + +## v2.5.1 +- Fix: reverted GDSCsmall.rda and CCLEsmall.rda to original data format; they +were accidentally pushed with MultiAssayExperiments in @molecularProfiles + +## v2.5.0 +- Spring Bioconductor release! + +## v2.1.12 +- Added experimental support for a new class, the `LongTable`, for storing the +sensitivity data in a `PharmacoSet`. +- Because this is not well tested, we have left not updated the PSets available +via the `downloadPSets` function. +- Instead we have provided a convenient function, +`convertSensitivitySlotToLongTable`, which takes in a `PharmacoSet` object, +converts the data in the `@sensitivty` slot to a `LongTable` and returns an +updated `PharmacoSet` object. +- The `LongTable` class will be used in the future to allow `PharmacoSet`s to +store treatment response experiments with multiple drugs or cell-lines, greatly +expanding the variety of data which can be stored in a `PharmacoSet` object. +- For more details on the `LongTable` class, please see the vignette in the +`CoreGx` package. + +## v2.0.0 +- PharmacoGx now depends on CoreGx, a package designed to abstract core +functionality from PharmacoGx for use in other Gx suite packages +- `PharmacoSet` class has been modified to store molecular profile data in the +`SummarizedExperiment` class instead of the the `ExpressionSet` class +- Argument `pSet` in most PharmacoSet accessor methods now converted to `object` +instead; this will break code using names parameters for these accessor methods","Markdown" +"Pharmacogenomics","bhklab/PharmacoGx","CODE_OF_CONDUCT.md",".md","3465","77","# Contributor Covenant Code of Conduct for the PharmacoGx Project + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in the PharmacoGx project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +The PharmacoGx project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +The PharmacoGx project have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within the PharmacoGx project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the PharmacoGx project team at bhklab.research@gmail.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The PharmacoGx project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +The PharmacoGx project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq +","Markdown" +"Pharmacogenomics","bhklab/PharmacoGx","LICENSE.md",".md","34904","596","GNU General Public License +========================== + +_Version 3, 29 June 2007_ +_Copyright © 2007 Free Software Foundation, Inc. <>_ + +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 +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. + +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. + +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. + +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 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 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 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. + +_END OF TERMS AND CONDITIONS_ + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to +the public, the best way to achieve this is to make it 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 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 + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + 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 . + +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: + + Copyright (C) + This program 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 +<>. +","Markdown" +"Pharmacogenomics","bhklab/PharmacoGx","vignettes/DetectingDrugSynergyAndAntagonism.R",".R","7353","194","## ----eval=TRUE, include=FALSE------------------------------------------------- +# convenience variables +cgx <- BiocStyle::Biocpkg(""CoreGx"") +pgx <- BiocStyle::Biocpkg(""PharmacoGx"") +dt <- BiocStyle::CRANpkg(""data.table"") + +# knitr options +knitr::opts_chunk$set(warning=FALSE) + +## ----load_dependencies_eval, eval=TRUE, echo=FALSE---------------------------- +suppressPackageStartupMessages({ + library(PharmacoGx) + library(CoreGx) + library(data.table) + library(ggplot2) +}) + +## ----load_dependencies_echo, eval=FALSE, echo=TRUE---------------------------- +# library(PharmacoGx) +# library(CoreGx) +# library(data.table) +# library(ggplot2) + +## ----------------------------------------------------------------------------- +input_file <- system.file(""extdata/mathews_griner.csv.tar.gz"", + package=""PharmacoGx"") +mathews_griner <- fread(input_file) + +## ----experiment_design_hypothesis--------------------------------------------- +groups <- list( + rowDataMap=c( + treatment1id=""RowName"", treatment2id=""ColName"", + treatment1dose=""RowConcs"", treatment2dose=""ColConcs"" + ), + colDataMap=c(""sampleid"") +) +groups[[""assayMap""]] <- c(groups$rowDataMap, groups$colDataMap) +(groups) + +## ----handling_technical_replicates-------------------------------------------- +# The := operator modifies a data.table by reference (i.e., without making a copy) +mathews_griner[, tech_rep := seq_len(.N), by=c(groups[[""assayMap""]])] +if (max(mathews_griner[[""tech_rep""]]) > 1) { + groups[[""colDataMap""]] <- c(groups[[""colDataMap""]], ""tech_rep"") + groups[[""assayMap""]] <- c(groups[[""assayMap""]], ""tech_rep"") +} else { + # delete the additional column if not needed + message(""No technical replicates in this dataset!"") + mathews_griner[[""tech_reps""]] <- NULL +} + +## ----build_tredatamapper------------------------------------------------------ +(treMapper <- TREDataMapper(rawdata=mathews_griner)) + +## ----evaluate_tre_mapping_guess----------------------------------------------- +(guess <- guessMapping(treMapper, groups, subset=TRUE)) + +## ----update_tredatamapper_with_guess------------------------------------------ +metadataMap(treMapper) <- list(experiment_metadata=guess$metadata$mapped_columns) +rowDataMap(treMapper) <- guess$rowDataMap +colDataMap(treMapper) <- guess$colDataMap +assayMap(treMapper) <- list(raw=guess$assayMap) +treMapper + +## ----metaconstruct_the_tre---------------------------------------------------- +(tre <- metaConstruct(treMapper)) + +## ----normalize_to_dose_0_0_control-------------------------------------------- +raw <- tre[[""raw""]] +raw[, + viability := viability / .SD[treatment1dose == 0 & treatment2dose == 0, viability], + by=c(""treatment1id"", ""treatment2id"", ""sampleid"", ""tech_rep"") +] +raw[, viability := pmax(0, viability)] # truncate min viability at 0 +tre[[""raw""]] <- raw + +## ----sanity_check_viability--------------------------------------------------- +tre[[""raw""]][, range(viability)] + +## ----find_bad_viability_treatment, warning=FALSE------------------------------ +(bad_treatments <- tre[[""raw""]][viability > 2, unique(treatment1id)]) + +## ----remove_bad_viability_treatment, warning=FALSE---------------------------- +(tre <- subset(tre, !(treatment1id %in% bad_treatments))) + +## ----sanity_check_viability2-------------------------------------------------- +tre[[""raw""]][, range(viability)] + +## ----creating_monotherapy_assay----------------------------------------------- +tre_qc <- tre |> + endoaggregate( + subset=treatment2dose == 0, # filter to only monotherapy rows + assay=""raw"", + target=""mono_viability"", # create a new assay named mono_viability + mean_viability=pmin(1, mean(viability)), + by=c(""treatment1id"", ""treatment1dose"", ""sampleid"") + ) + +## ----monotherapy_curve_fits, messages=FALSE----------------------------------- +tre_fit <- tre_qc |> + endoaggregate( + { # the entire code block is evaluated for each group in our group by + # 1. fit a log logistic curve over the dose range + fit <- PharmacoGx::logLogisticRegression(treatment1dose, mean_viability, + viability_as_pct=FALSE) + # 2. compute curve summary metrics + ic50 <- computeIC50(treatment1dose, Hill_fit=fit) + aac <- computeAUC(treatment1dose, Hill_fit=fit) + # 3. assemble the results into a list, each item will become a + # column in the target assay. + list( + HS=fit[[""HS""]], + E_inf = fit[[""E_inf""]], + EC50 = fit[[""EC50""]], + Rsq=as.numeric(unlist(attributes(fit))), + aac_recomputed=aac, + ic50_recomputed=ic50 + ) + }, + assay=""mono_viability"", + target=""mono_profiles"", + enlist=FALSE, # this option enables the use of a code block for aggregation + by=c(""treatment1id"", ""sampleid""), + nthread=2 # parallelize over multiple cores to speed up the computation + ) + +## ----create_combo_viability, message=FALSE------------------------------------ +tre_combo <- tre_fit |> + endoaggregate( + assay=""raw"", + target=""combo_viability"", + mean(viability), + by=c(""treatment1id"", ""treatment2id"", ""treatment1dose"", ""treatment2dose"", + ""sampleid"") + ) + +## ----add_monotherapy_fits_to_combo_viability---------------------------------- +tre_combo <- tre_combo |> + mergeAssays( + x=""combo_viability"", + y=""mono_profiles"", + by=c(""treatment1id"", ""sampleid"") + ) |> + mergeAssays( + x=""combo_viability"", + y=""mono_profiles"", + by.x=c(""treatment2id"", ""sampleid""), + by.y=c(""treatment1id"", ""sampleid""), + suffixes=c(""_1"", ""_2"") # add sufixes to duplicate column names + ) + +## ----------------------------------------------------------------------------- +tre_combo <- tre_combo |> + endoaggregate( + viability_1=.SD[treatment2dose == 0, mean_viability], + assay=""combo_viability"", + by=c(""treatment1id"", ""treatment1dose"", ""sampleid"") + ) |> + endoaggregate( + viability_2=.SD[treatment1dose == 0, mean_viability], + assay=""combo_viability"", + by=c(""treatment1id"", ""treatment2dose"", ""sampleid"") + ) + +## ----compute_synergy_null_hypotheses, message=FALSE--------------------------- +tre_synergy <- tre_combo |> + endoaggregate( + assay=""combo_viability"", + HSA_ref=computeHSA(viability_1, viability_2), + Bliss_ref=computeBliss(viability_1, viability_2), + Loewe_ref=computeLoewe( + treatment1dose, HS_1=HS_1, EC50_1=EC50_1, E_inf_1=E_inf_1, + treatment2dose, HS_2=HS_2, EC50_2=EC50_2, E_inf_2=E_inf_2 + ), + ZIP_ref=computeZIP( + treatment1dose, HS_1=HS_1, EC50_1=EC50_1, E_inf_1=E_inf_1, + treatment2dose, HS_2=HS_2, EC50_2=EC50_2, E_inf_2=E_inf_2 + ), + by=assayKeys(tre_combo, ""combo_viability""), + nthread=2 + ) + +## ----synergy_score_vs_reference----------------------------------------------- +tre_synergy <- tre_synergy |> + endoaggregate( + assay=""combo_viability"", + HSA_score=HSA_ref - mean_viability, + Bliss_score=Bliss_ref - mean_viability, + Loewe_score=Loewe_ref - mean_viability, + ZIP_score=ZIP_ref - mean_viability, + by=assayKeys(tre_synergy, ""combo_viability"") + ) + +","R" +"Pharmacogenomics","bhklab/PharmacoGx","inst/PharmacoGx_Molecular_Data_Standards.md",".md","5096","87","--- +output: + pdf_document: default + html_document: default +--- +# Stardardized Molecular Data names and annotations for PSets + +This document will describe two things: First, we document the currently required standards for naming, annotating, and including molecular data into psets.\ +Second, we will describe the desired future state. + +This is designed to be a living document, which can be updated as things change, progress is made on the ""todo"" list, and new ideas are added. + +## Current necessary considerations in molecular profiles for PSets + +There are a few things that are necessary for proper functioning of PSets in PharmacoGx. Here, we focus on the requirements from the molecularData slot only. + +### Molecular Data Names + +This is what is returned when you run `mDataNames` on a PSet. It is also the names of the elements of the list making up the `@molecularData` slot. + +Currently, there is a mixed bag of molecular data names used across psets, as no fixed vocabulary is required here. Nothing is enforced, and only the ""show"" function in pharmacogx assumes certain names, and it handles missing entries (for example, missing profile types, or even no molecular profiles) gracefully. + +Currently, we meet the following names in PSets downloaded from orcestra: + +| Name | Data type | +|---------------------------------|--------------------------------------------------------------| +| rnaseq | rnaseq (gene tpm??) | +| rna | microarray rna | +| Kallisto_0.46.1.rnaseq | rnaseq gene level tpm | +| Kallisto_0.46.1.rnaseq.counts | rnaseq gene level counts | +| Kallisto_0.46.1.isoforms | rnaseq isoform level tpm | +| Kallisto_0.46.1.isoforms.counts | rnaseq isoform level counts | +| cnv | snp array derived copy number | +| mutation | mutation data, at protein level | +| fusion | presence of fusion data, as binary | +| mutationall | mutation data, at protein level | +| mutationchosen | mutation data, at protein level | +| mutation_exome | mutation data, at protein level, specifically from exome seq | + + +Of these, `show` is aware of: + +- rna +- rnaseq +- dna +- snp +- cnv + +Clearly, this is outdated and should be fixed. + +### Annotation of SummarizedExperiments + +PharmacoSets require a specific entry in the metadata of a SummarizedExperiment to be set to a valid value to work with the functions in the package. + +Specifically, we require `metadata(SE)$annotation` to be set to one of the valid values described below. + +Functions within the package use the value of this field to determine how to treat the data within the SummarizedExperiment (is this gene expression, copy number, mutation, etc) + +The currently allowed vocabulary is: + + +| Name | Data type | +|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| +| rna | gene expression values | +| cnv | logR copy number | +| mutation | gene level binary mutation, encoded as ""wt"" for 0, or the protein change for a 1. Multiple mutations in same gene are separated with '///' . | +| fusion | gene partner level binary fusion status, encoded as ""wt"" for 0, or the fusion partners for a 1. Multiple fusions in same genes are separated with '///' . | + + +### Annotation of the right version for the PSet + +Finally, if in the creation of your PSet, you include SummarizedExperiments and not the older ExpressionSet objects, you must set an annotation on the PSet to signify this. The original PSet used ExpressionSets. + +To do this, set `annotation(PSet)$version <- 2` or larger. + +## Future Changes + +This section is TBD. However, some considerations: + +We should have a more standardized set of annotations for each SE. Proposed additions: + +- pipeline: describing the pipeline +- transformation: any transformation applied to the raw output of the pipeline + + +We should support methylation data soon. +","Markdown" +"Pharmacogenomics","bhklab/PharmacoGx","src/RcppExports.cpp",".cpp","2386","45","// Generated by using Rcpp::compileAttributes() -> do not edit by hand +// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 + +#include + +using namespace Rcpp; + +#ifdef RCPP_USE_GLOBAL_ROSTREAM +Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); +Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); +#endif + +// partialCorQUICKSTOP +extern ""C"" SEXP partialCorQUICKSTOP(SEXP pin_x, SEXP pin_y, SEXP pobsCor, SEXP pGroupFactor, SEXP pGroupSize, SEXP pnumGroup, SEXP pMaxIter, SEXP pn, SEXP preq_alpha, SEXP ptolerance_par, SEXP plog_decision_boundary, SEXP pseed); +RcppExport SEXP _PharmacoGx_partialCorQUICKSTOP(SEXP pin_xSEXP, SEXP pin_ySEXP, SEXP pobsCorSEXP, SEXP pGroupFactorSEXP, SEXP pGroupSizeSEXP, SEXP pnumGroupSEXP, SEXP pMaxIterSEXP, SEXP pnSEXP, SEXP preq_alphaSEXP, SEXP ptolerance_parSEXP, SEXP plog_decision_boundarySEXP, SEXP pseedSEXP) { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< SEXP >::type pin_x(pin_xSEXP); + Rcpp::traits::input_parameter< SEXP >::type pin_y(pin_ySEXP); + Rcpp::traits::input_parameter< SEXP >::type pobsCor(pobsCorSEXP); + Rcpp::traits::input_parameter< SEXP >::type pGroupFactor(pGroupFactorSEXP); + Rcpp::traits::input_parameter< SEXP >::type pGroupSize(pGroupSizeSEXP); + Rcpp::traits::input_parameter< SEXP >::type pnumGroup(pnumGroupSEXP); + Rcpp::traits::input_parameter< SEXP >::type pMaxIter(pMaxIterSEXP); + Rcpp::traits::input_parameter< SEXP >::type pn(pnSEXP); + Rcpp::traits::input_parameter< SEXP >::type preq_alpha(preq_alphaSEXP); + Rcpp::traits::input_parameter< SEXP >::type ptolerance_par(ptolerance_parSEXP); + Rcpp::traits::input_parameter< SEXP >::type plog_decision_boundary(plog_decision_boundarySEXP); + Rcpp::traits::input_parameter< SEXP >::type pseed(pseedSEXP); + rcpp_result_gen = Rcpp::wrap(partialCorQUICKSTOP(pin_x, pin_y, pobsCor, pGroupFactor, pGroupSize, pnumGroup, pMaxIter, pn, preq_alpha, ptolerance_par, plog_decision_boundary, pseed)); + return rcpp_result_gen; +END_RCPP +} + +static const R_CallMethodDef CallEntries[] = { + {""_PharmacoGx_partialCorQUICKSTOP"", (DL_FUNC) &_PharmacoGx_partialCorQUICKSTOP, 12}, + {NULL, NULL, 0} +}; + +RcppExport void R_init_PharmacoGx(DllInfo *dll) { + R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); + R_useDynamicSymbols(dll, FALSE); +} +","C++" +"Pharmacogenomics","bhklab/PharmacoGx","src/metaPermC.c",".c","9309","359","/* +// Fast permutations for rCI using a naive matrix based approach. +*/ + +#include +#include +#include +#include +#include +#include + +// #include ""xoroshiro128+.h"" + + +/* This is xoroshiro128+ 1.0, our best and fastest small-state generator + for floating-point numbers. We suggest to use its upper bits for + floating-point generation, as it is slightly faster than + xoroshiro128**. It passes all tests we are aware of except for the four + lower bits, which might fail linearity tests (and just those), so if + low linear complexity is not considered an issue (as it is usually the + case) it can be used to generate 64-bit outputs, too; moreover, this + generator has a very mild Hamming-weight dependency making our test + (http://prng.di.unimi.it/hwd.php) fail after 5 TB of output; we believe + this slight bias cannot affect any application. If you are concerned, + use xoroshiro128** or xoshiro256+. + + We suggest to use a sign test to extract a random Boolean value, and + right shifts to extract subsets of bits. + + The state must be seeded so that it is not everywhere zero. If you have + a 64-bit seed, we suggest to seed a splitmix64 generator and use its + output to fill s. + + NOTE: the parameters (a=24, b=16, b=37) of this version give slightly + better results in our test than the 2016 version (a=55, b=14, c=36). +*/ + +static inline uint64_t rotl(const uint64_t x, int k) { + return (x << k) | (x >> (64 - k)); +} + + +// static uint64_t s[2]; + +uint64_t next(uint64_t *s) { + const uint64_t s0 = s[0]; + uint64_t s1 = s[1]; + const uint64_t result = s0 + s1; + + s1 ^= s0; + s[0] = rotl(s0, 24) ^ s1 ^ (s1 << 16); // a, b + s[1] = rotl(s1, 37); // c + + return result; +} + +// Code to trim random numbers from :https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c +// maxindex here is exclusive of the right edge +uint64_t generate_random_index(uint64_t *state, uint64_t maxindex){ + // uint64_t maxindex = llround(maxindexd); + + if ((maxindex-1) == UINT64_MAX){ + return next(state); + } else { + // Supporting larger values for n would requires an even more + // elaborate implementation that combines multiple calls to rand() + // assert (maxindex <= UINT64_MAX) + + // Chop off all of the values that would cause skew... + uint64_t end = UINT64_MAX / (maxindex); // truncate skew + // assert (end > 0); + end *= maxindex; + + // ... and ignore results from rand() that fall above that limit. + // (Worst case the loop condition should succeed 50% of the time, + // so we can expect to bail out of this loop pretty quickly.) + uint64_t r; + while ((r = next(state)) >= end); + + return r % maxindex; + } +} + + + +// void printVec(uint64_t *list, uint64_t N){ +// for(uint64_t i = 0; i < N; i ++){ +// printf(""%lld, "", list[i]); +// } +// } + +// Using ""inside out"" Fisher Yates https://en.wikipedia.org/wiki/Fisher–Yates_shuffle +void sampleIdx(uint64_t N, uint64_t *permPointer, uint64_t *state){ + uint64_t j; + permPointer[0] = 0; + // printf(""%lld"", N); + + for(uint64_t i = 0; i <= N-1; i++){ + j = generate_random_index(state, i+1); + if(j != i){ + permPointer[i] = permPointer[j]; + } + permPointer[j] = i; + } + +} + + +// This code is adapted from the quickstop reference implementation here: https://github.com/julianhecker/QUICK-STOP + +double log_denom(uint64_t suc,uint64_t n, double p) +{ + double tmp=0; + if(fabs(p)>pow(10,-16)) + { + tmp+=(double)(suc)*log(p); + } + if(fabs(1.0-p)>pow(10,-16)) + { + tmp+=((double)(n)-(double)(suc))*log(1.0-p); + } + return tmp; +} + + + +void runPerm(double *out, + double *xvec, + double *yvec, + double obsCor, + int *GroupFactor, + uint64_t N, + int *GroupSize, + int numGroup, + double req_alpha, + double tolerance_par, + int log_decision_boundary, + uint64_t max_iter, + uint64_t *state){ + + + + // uint64_t num_larger = 0; // Unused + uint64_t cur_success = 0; + uint64_t cur_iter = 1; + + double log_cur_PiN = log(1); // Initialization so the logic can stay the same through all loops + double log_cur_suph1; + double log_cur_suph2; + + double p1 = req_alpha; + double p2 = p1 + tolerance_par; + + double pr_min_1 = (double)1.0/2; + // int success; + + + double currCor; + + // uint64_t j = 0; + uint64_t *permIdxX = malloc(N * sizeof(uint64_t)); + uint64_t *permIdxY = malloc(N * sizeof(uint64_t)); + + double dSDx; + double dSDy; + + double *dGroupMeanY = malloc(numGroup*sizeof(double)); + double *dGroupMeanX = malloc(numGroup*sizeof(double)); + + double *yShuffled = malloc(N * sizeof(double)); + double *xShuffled = malloc(N * sizeof(double)); + double significant = NA_REAL; + + + + // sample_function <- function(){ + + // partial.dp <- sample(dd[,1], nrow(dd)) + // partial.x <- sample(dd[,2], nrow(dd)) + + // for(gp in unique(dd[,3])){ + // partial.x[dd[,3]==gp] <- partial.x[dd[,3]==gp]-mean(partial.x[dd[,3]==gp]) + // partial.dp[dd[,3]==gp] <- partial.dp[dd[,3]==gp]-mean(partial.dp[dd[,3]==gp]) + // } + + // perm.cor <- coop::pcor(partial.dp, partial.x, use=""complete.obs"") + // return(abs(obs.cor) < abs(perm.cor)) + + while(cur_iter <= max_iter){ + + sampleIdx(N, permIdxX, state); + sampleIdx(N, permIdxY, state); + dSDx = (double)0; + dSDy = (double)0; + + for(int j = 0; j < numGroup; j++){ + dGroupMeanX[j] = 0; + dGroupMeanY[j] = 0; + } + + for(int j = 0; j < N; j++){ + yShuffled[j] = yvec[permIdxY[j]]; + dGroupMeanY[GroupFactor[j]] += yvec[permIdxY[j]]; + + xShuffled[j] = xvec[permIdxX[j]]; + dGroupMeanX[GroupFactor[j]] += xvec[permIdxX[j]]; + + } + + // for(int j = 0; j < N; j++){ + // yShuffled[j] = yvec[j]; + // dGroupMeanY[GroupFactor[j]] += yvec[j]; + + // xShuffled[j] = xvec[j]; + // dGroupMeanX[GroupFactor[j]] += xvec[j]; + + // } + + for(int j = 0; j < numGroup; j++){ + dGroupMeanX[j] /= (double)GroupSize[j]; + dGroupMeanY[j] /= (double)GroupSize[j]; + } + + for(int j = 0; j < N; j++){ + yShuffled[j] = yShuffled[j] - dGroupMeanY[GroupFactor[j]]; + xShuffled[j] = xShuffled[j] - dGroupMeanX[GroupFactor[j]]; + + dSDy += pow(yShuffled[j],2); + + dSDx += pow(xShuffled[j],2); + + } + + + dSDy = sqrt(dSDy); + dSDx = sqrt(dSDx); + + currCor = 0; + + for(int j = 0; j < N; j++){ + currCor += (yShuffled[j])/dSDy * (xShuffled[j])/dSDx; + } + // printf(""%f\n"", currCor); + + + + if(fabs(currCor)>=fabs(obsCor)){ + cur_success = cur_success + 1; + log_cur_PiN = log_cur_PiN + log_denom(1,1,pr_min_1); + } else { + log_cur_PiN = log_cur_PiN + log_denom(0,1,pr_min_1); + } + + if(pr_min_1p2) { + log_cur_suph2 = log_denom(cur_success, cur_iter, pr_min_1); + } else { + log_cur_suph2 = log_denom(cur_success, cur_iter, p2); + } + + cur_iter = cur_iter + 1; + pr_min_1 = ((double)cur_success + 1.0/2.0)/cur_iter; + // printf(""%f\n"", pr_min_1); + + + // TODO: make a list to return everything to R + if(log_cur_PiN - log_cur_suph2 > log_decision_boundary){ + significant = (double) 1; + break; + } + if(log_cur_PiN - log_cur_suph1 > log_decision_boundary){ + significant = (double) 0; + break; + } + + } + + + + free(permIdxX); + free(permIdxY); + + free(dGroupMeanY); + free(dGroupMeanX); + free(yShuffled); + free(xShuffled); + + + out[0] = significant; + out[1] = pr_min_1; + out[2] = (double) cur_iter; + out[3] = (double) cur_success; + + return; + // return(currCor); + +} + +// Tested the computation of correlations by comparing against R code, perm distributions look +// very similar +SEXP partialCorQUICKSTOP(SEXP pin_x, + SEXP pin_y, + SEXP pobsCor, + SEXP pGroupFactor, + SEXP pGroupSize, + SEXP pnumGroup, + SEXP pMaxIter, + SEXP pn, + SEXP preq_alpha, + SEXP ptolerance_par, + SEXP plog_decision_boundary, + SEXP pseed){ + + double Ndouble = *REAL(pn); + + double MaxIterdouble = *REAL(pMaxIter); + double obsCor = *REAL(pobsCor); + double req_alpha = *REAL(preq_alpha); + double tolerance_par = *REAL(ptolerance_par); + int log_decision_boundary = *INTEGER(plog_decision_boundary); + + + // double temp; // Unused + + uint64_t N = (uint64_t) Ndouble; + uint64_t max_iter = (uint64_t) MaxIterdouble; + + SEXP pout = PROTECT(allocVector(REALSXP,4)); + + double *out = REAL(pout); + + double *seed = REAL(pseed); + uint64_t *state = (uint64_t*) seed; + + int numGroup = *INTEGER(pnumGroup); + + runPerm(out, REAL(pin_x), REAL(pin_y), + obsCor, + INTEGER(pGroupFactor), + N, + INTEGER(pGroupSize), + numGroup, + req_alpha, + tolerance_par, + log_decision_boundary, + max_iter, + state); + + UNPROTECT(1); + + return pout; + +} +","C" +"Pharmacogenomics","bhklab/PharmacoGx","src/rCPP_bridge.cpp",".cpp","2674","50","#include + + +//' QUICKSTOP significance testing for partial correlation +//' +//' This function will test whether the observed partial correlation is significant +//' at a level of req_alpha, doing up to MaxIter permutations. Currently, it +//' supports only grouping by discrete categories when calculating a partial correlation. +//' Currenlty, only does two sided tests. +//' +//' @param pin_x one of the two vectors to correlate. +//' @param pin_y the other vector to calculate +//' @param pobsCor the observed (partial) correlation between these varaiables +//' @param pGroupFactor an integer vector labeling group membership, to correct +//' for in the partial correlation. NEEDS TO BE ZERO BASED! +//' @param pGroupSize an integer vector of size length(unique(pGroupFactor)), counting +//' the number of members of each group (basically table(pGroupFactor)) as integer vector +//' @param pnumGroup how many groups are there (len(pGroupSize)) +//' @param pMaxIter maximum number of iterations to do, as a REAL NUMBER +//' @param pn length of x and y, as a REAL NUMBER +//' @param preq_alpha the required alpha for significance +//' @param ptolerance_par the tolerance region for quickstop. Suggested to be 1/100th of req_alpha' +//' @param plog_decision_boundary log (base e) of 1/probability of incorrectly calling significance, as +//' per quickstop paper (used to determine the log-odds) +//' @param pseed A numeric vector of length 2, used to seed the internal xoroshiro128+ 1.0 +//' random number generator. Note that currently, these values get modified per call, so pass in a copy +//' if you wish to keep a seed for running same simulation twice +//' +//' @return a double vector of length 4, entry 1 is either 0, 1 (for TRUE/FALSE) or NA_REAL_ for significance determination +//' NA_REAL_ is returned when the MaxIter were reached before a decision is made. Usually, this occurs when the real p value is close to, or +//' falls within the tolerance region of (req_alpha, req_alpha+tolerance_par). Entry 2 is the current p value estimate. entry 3 is the total +//' number of iterations performed. Entry 4 is the number of time a permuted value was larger in absolute value than the observed cor. +//' +//' @useDynLib PharmacoGx _PharmacoGx_partialCorQUICKSTOP +//' +//' +// [[Rcpp::export]] +extern ""C"" SEXP partialCorQUICKSTOP(SEXP pin_x, + SEXP pin_y, + SEXP pobsCor, + SEXP pGroupFactor, + SEXP pGroupSize, + SEXP pnumGroup, + SEXP pMaxIter, + SEXP pn, + SEXP preq_alpha, + SEXP ptolerance_par, + SEXP plog_decision_boundary, + SEXP pseed); +","C++" +"Pharmacogenomics","bhklab/PharmacoGx","R/geneDrugSensitivity.R",".R","9040","254","#' Calcualte The Gene Drug Sensitivity +#' +#' TODO:: Write a description! +#' @examples +#' print(""TODO::"") +#' +#' @param x A \code{numeric} vector of gene expression values +#' @param type A \code{vector} of factors specifying the cell lines or type types +#' @param batch A \code{vector} of factors specifying the batch +#' @param drugpheno A \code{numeric} vector of drug sensitivity values (e.g., +#' IC50 or AUC) +# @param duration A \code{numeric} vector of experiment duration in hours +#' @param interaction.typexgene \code{boolean} Should interaction between gene +#' expression and cell/type type be computed? Default set to FALSE +#' @param model \code{boolean} Should the full linear model be returned? Default +#' set to FALSE +#' @param standardize \code{character} One of 'SD', 'rescale' or 'none' +#' @param verbose \code{boolean} Should the function display messages? +#' +#' @return A \code{vector} reporting the effect size (estimate of the coefficient +#' of drug concentration), standard error (se), sample size (n), t statistic, +#' and F statistics and its corresponding p-value. +#' +#' @importFrom stats sd complete.cases lm glm anova pf formula var +geneDrugSensitivity <- function(x, type, batch, drugpheno, + interaction.typexgene=FALSE, + model=FALSE, standardize=c(""SD"", ""rescale"", ""none""), verbose=FALSE) { + + ## NOTE:: The use of T/F warning from BiocCheck is a false positive on the string 'Pr(>F)' + standardize <- match.arg(standardize) + + colnames(drugpheno) <- paste(""drugpheno"", seq_len(ncol(drugpheno)), sep=""."") + + drugpheno <- data.frame(vapply(drugpheno, function(x) { + if (!is.factor(x)) { + x[is.infinite(x)] <- NA + } + return(list(x)) + }, USE.NAMES=TRUE, + FUN.VALUE=list(1)), check.names=FALSE) + + + ccix <- complete.cases(x, type, batch, drugpheno) + nn <- sum(ccix) + + if(length(table(drugpheno)) > 2){ + if(ncol(drugpheno)>1){ + ##### FIX NAMES!!! + rest <- lapply(seq_len(ncol(drugpheno)), function(i){ + + est <- paste(""estimate"", i, sep=""."") + se <- paste(""se"", i, sep=""."") + tstat <- paste(""tstat"", i, sep=""."") + + rest <- rep(NA, 3) + names(rest) <- c(est, se, tstat) + return(rest) + }) + rest <- do.call(c, rest) + rest <- c(rest, n=nn, ""fstat""=NA, ""pvalue""=NA) + } else { + rest <- c(""estimate""=NA, ""se""=NA, ""n""=nn, ""tstat""=NA, ""fstat""=NA, ""pvalue""=NA, ""df""=NA) + } + } else { + # rest <- c(""estimate""=NA, ""se""=NA, ""n""=nn, ""pvalue""=NA) + if (is.factor(drugpheno[,1])){ + rest <- c(""estimate""=NA_real_, ""se""=NA_real_, ""n""=nn, ""pvalue""=NA_real_, df=NA_real_) + } else { + rest <- c(""estimate"" = NA, ""se"" = NA , ""n"" = nn, ""tstat"" = NA , ""fstat"" = NA , ""pvalue"" = NA , ""df"" = NA ) + } + } + + if(nn < 3 || isTRUE(all.equal(var(x[ccix], na.rm=TRUE), 0))) { + ## not enough samples with complete information or no variation in gene expression + return(rest) + } + + ## standardized coefficient in linear model + if(length(table(drugpheno)) > 2 & standardize!= ""none"") { + switch(standardize, + ""SD"" = drugpheno <- apply(drugpheno, 2, function(x){ + return(x[ccix]/sd(as.numeric(x[ccix])))}) , + ""rescale"" = drugpheno <- apply(drugpheno, 2, function(x){ + return(.rescale(as.numeric(x[ccix]), q=0.05, na.rm=TRUE)) }) + ) + + }else{ + drugpheno <- drugpheno[ccix,,drop=FALSE] + } + if(length(table(x)) > 2 & standardize!= ""none""){ + switch(standardize, + ""SD"" = xx <- x[ccix]/sd(as.numeric(x[ccix])) , + ""rescale"" = xx <- .rescale(as.numeric(x[ccix]), q=0.05, na.rm=TRUE) + ) + }else{ + xx <- x[ccix] + } + if(ncol(drugpheno)>1){ + ff0 <- paste(""cbind("", paste(paste(""drugpheno"", seq_len(ncol(drugpheno)), sep="".""), collapse="",""), "")"", sep="""") + } else { + ff0 <- ""drugpheno.1"" + } + + # ff1 <- sprintf(""%s + x"", ff0) + + dd <- data.frame(drugpheno, ""x""=xx) + # , ""x""=xx, ""type""=type[ccix], ""batch""=batch[ccix]) + + ## control for tissue type + if(length(sort(unique(type[ccix]))) > 1) { + dd <- cbind(dd, type=type[ccix]) + } + ## control for batch + if(length(sort(unique(batch[ccix]))) > 1) { + dd <- cbind(dd, batch=batch[ccix]) + } + ## control for duration + # if(length(sort(unique(duration))) > 1){ + # ff0 <- sprintf(""%s + duration"", ff0) + # ff <- sprintf(""%s + duration"", ff) + # } + + # if(is.factor(drugpheno[,1])){ + + # drugpheno <- drugpheno[,1] + + # } else { + + # drugpheno <- as.matrix(drugpheno) + + # } +if(any(unlist(lapply(drugpheno,is.factor)))){ + +## Added default '' value to ww to fix function if it is passed verbose = FALSE +ww = '' + +rr0 <- tryCatch(try(glm(formula(drugpheno.1 ~ . - x), data=dd, model=FALSE, x=FALSE, y=FALSE, family=""binomial"")), + warning=function(w) { + if(verbose) { + ww <- ""Null model did not convrge"" + print(ww) + if(""type"" %in% colnames(dd)) { + tt <- table(dd[,""type""]) + print(tt) + } + return(ww) + } + }) + rr1 <- tryCatch(try(glm(formula(drugpheno.1 ~ .), data=dd, model=FALSE, x=FALSE, y=FALSE, family=""binomial"")), + warning=function(w) { + if(verbose) { + ww <- ""Model did not converge"" + tt <- table(dd[,""drugpheno.1""]) + print(ww) + print(tt) + } + return(ww) + }) + + +} else{ + +rr0 <- tryCatch(try(lm(formula(paste(ff0, ""~ . -x"", sep="" "")), data=dd)), + warning=function(w) { + if(verbose) { + ww <- ""Null model did not converge"" + print(ww) + if(""type"" %in% colnames(dd)) { + tt <- table(dd[,""type""]) + print(tt) + } + return(ww) + } + }) + rr1 <- tryCatch(try(lm(formula(paste(ff0, ""~ . "", sep="" "")), data=dd)), + warning=function(w) { + if(verbose) { + ww <- ""Model did not converge"" + tt <- table(dd[,""drugpheno.1""]) + print(ww) + print(tt) + } + return(ww) + }) + + +} + + + if (!is(rr0, ""try-error"") && !is(rr1, ""try-error"") & !is(rr0, ""character"") && !is(rr1, ""character"")) { + rr <- summary(rr1) + + if(any(unlist(lapply(drugpheno,is.factor)))){ + rrc <- stats::anova(rr0, rr1, test=""Chisq"") + rest <- c(""estimate""=rr$coefficients[grep(""^x"", rownames(rr$coefficients)), ""Estimate""], ""se""=rr$coefficients[grep(""^x"", rownames(rr$coefficients)), ""Std. Error""], ""n""=nn, ""pvalue""=rrc$'Pr(>Chi)'[2], ""df""=rr1$df.residual) + names(rest) <- c(""estimate"", ""se"", ""n"", ""pvalue"", ""df"") + + } else { + if(ncol(drugpheno)>1){ + rrc <- summary(stats::manova(rr1)) + rest <- lapply(seq_len(ncol(drugpheno)), function(i) { + est <- paste(""estimate"", i, sep=""."") + se <- paste(""se"", i, sep=""."") + tstat <- paste(""tstat"", i, sep=""."") + rest <- c(rr[[i]]$coefficients[grep(""^x"", rownames(rr[[i]]$coefficients)), ""Estimate""], rr[[i]]$coefficients[grep(""^x"", rownames(rr[[i]]$coefficients)), ""Std. Error""], rr[[i]]$coefficients[grep(""^x"", rownames(rr[[i]]$coefficients)), ""t value""]) + names(rest) <- c(est, se, tstat) + return(rest) + }) + rest <- do.call(c, rest) + rest <- c(rest,""n""=nn, ""fstat""=rrc$stats[grep(""^x"", rownames(rrc$stats)), ""approx F""], ""pvalue""=rrc$stats[grep(""^x"", rownames(rrc$stats)), ""Pr(>F)""]) + } else { + rrc <- stats::anova(rr0, rr1, test = ""F"") + if(!length(rr$coefficients[grep(""^x"", rownames(rr$coefficients)), ""Estimate""])){ + stop(""A model failed to converge even with sufficient data. Please investigate further"") + } + rest <- c(""estimate""=rr$coefficients[grep(""^x"", rownames(rr$coefficients)), ""Estimate""], ""se""=rr$coefficients[grep(""^x"", rownames(rr$coefficients)), ""Std. Error""],""n""=nn, ""tstat""=rr$coefficients[grep(""^x"", rownames(rr$coefficients)), ""t value""], ""fstat""=rrc$F[2], ""pvalue""=rrc$'Pr(>F)'[2], ""df""=rr1$df.residual) + names(rest) <- c(""estimate"", ""se"", ""n"", ""tstat"", ""fstat"", ""pvalue"", ""df"") + } + } + + +# rest <- c(""estimate""=rr$coefficients[""x"", ""Estimate""], ""se""=rr$coefficients[""x"", ""Std. Error""], ""n""=nn, ""tsat""=rr$coefficients[""x"", ""t value""], ""fstat""=rrc$F[2], ""pvalue""=rrc$'Pr(>F)'[2]) + +# names(rest) <- c(""estimate"", ""se"", ""n"", ""tstat"", ""fstat"", ""pvalue"") + +## add tissue type/cell line statistics +# if(length(sort(unique(type))) > 1) { +# rr <- summary(rr0) +# ttype <- c(""type.fstat""=rr$fstatistic[""value""], ""type.pvalue""=pf(q=rr$fstatistic[""value""], df1=rr$fstatistic[""numdf""], df2=rr$fstatistic[""dendf""], lower.tail=FALSE)) +# names(ttype) <- c(""type.fstat"", ""type.pvalue"") +# } else { ttype <- c(""type.fstat""=NA, ""type.pvalue""=NA) } +# rest <- c(rest, ttype) + ## add model + if(model) { rest <- list(""stats""=rest, ""model""=rr1) } + } + return(rest) +} + +## Helper Functions +##TODO:: Add function documentation +#' @importFrom stats quantile +.rescale <- function(x, na.rm=FALSE, q=0) +{ + if(q == 0) { + ma <- max(x, na.rm=na.rm) + mi <- min(x, na.rm=na.rm) + } else { + ma <- quantile(x, probs=1-(q/2), na.rm=na.rm) + mi <- quantile(x, probs=q/2, na.rm=na.rm) + } + xx <- (x - mi) / (ma - mi) + return(xx) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/methods-intersect.R",".R","159","7","# ==== PharmacoSet Class + +## TODO:: Can we implement intersect method for PSets? + +# ==== LongTable Class + +## TODO:: Implement intersection of LongTable objects","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeSlope.R",".R","2050","47","#' Return Slope (normalized slope of the drug response curve) for an experiment of a pSet by taking +#' its concentration and viability as input. +#' +#' @examples +#' dose <- c(0.0025,0.008,0.025,0.08,0.25,0.8,2.53,8) +#' viability <- c(108.67,111,102.16,100.27,90,87,74,57) +#' computeSlope(dose, viability) +#' +#' @param concentration `numeric` A concentration range that the AUC should be computed for that range. +#' Concentration range by default considered as not logarithmic scaled. Converted to numeric by function if necessary. +#' @param viability `numeric` Viablities corresponding to the concentration range passed as first parameter. +#' The range of viablity values by definition should be between 0 and 100. But the viabalities greater than +#' 100 and lower than 0 are also accepted. +#' @param trunc `logical(1)` A flag that identify if the viabality values should be truncated to be in the +#' range of (0,100) +#' @param verbose `logical(1)` If 'TRUE' the function will retrun warnings and other infomrative messages. +#' @return Returns the normalized linear slope of the drug response curve +#' +#' @export +computeSlope <- function(concentration, viability, trunc=TRUE, verbose=TRUE) { + concentration <- as.numeric(concentration[!is.na(concentration)]) + viability <- as.numeric(viability[!is.na(viability)]) + ii <- which(concentration == 0) + if(length(ii) > 0) { + concentration <- concentration[-ii] + viability <- viability[-ii] + } + ##convert to nanomolar with the assumption that always concentrations are in micro molar + concentration <- concentration + concentration <- log10(concentration) + 6 + if(trunc) { + viability <- pmin(viability, 100) + viability <- pmax(viability, 0) + } + + most.sensitive <- NULL + for(dose in concentration) + { + most.sensitive <- rbind(most.sensitive, cbind(dose,0)) + } + + slope.prime <- .optimizeRegression(x = most.sensitive[,1], y = most.sensitive[,2]) + slope <- .optimizeRegression(x = concentration, y = viability) + slope <- round(slope/abs(slope.prime),digits=2) + return(-slope) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/rankGeneDrugPerturbation.R",".R","5980","132","################################################# +## Rank genes based on drug effect in the Connectivity Map +## +## inputs: +## - data: gene expression data matrix +## - drug: single or vector of drug(s) of interest; if a vector of drugs is provided, they will be considered as being the same drug and will be jointly analyszed +## - drug.id: drug used in each experiment +## - drug.concentration: drug concentration used in each experiment +## - type: cell or tissue type for each experiment +## - xp: type of experiment (perturbation or control) +## - batch: experiment batches +## - duration: The duration of the experiment, in a consistent unit +## - single.type: Should the statitsics be computed for each cell/tissue type separately? +## - nthread: number of parallel threads (bound to the maximum number of cores available) +## +## outputs: +## list of datafraes with the statistics for each gene, for each type +## - list of data.frame with similar results for each type line separately if any +## +################################################# + +rankGeneDrugPerturbation <- +function (data, drug, drug.id, drug.concentration, type, xp, batch, duration, single.type=FALSE, nthread=1, verbose=FALSE) { + + if (nthread != 1) { + availcore <- parallel::detectCores() + if (missing(nthread) || nthread < 1 || nthread > availcore) { + # print(paste(""available cores"",availcore,""allocated"")) + nthread <- availcore + } + else{ + # print(paste(""all"",nthread,""cores have been allocated"")) + } + } + if (any(c(length(drug.id), length(drug.concentration), length(type), length(xp), length(batch), length(duration)) != nrow(data))) { + stop(""length of drug.id, drug.concentration, type, xp, duration and batch should be equal to the number of rows of data!"") + } + names(drug.id) <- names(drug.concentration) <- names(type) <- names(batch) <- names(duration) <- rownames(data) + if (!all(complete.cases(type, xp, batch, duration))) { + stop(""type, batch, duration and xp should not contain missing values!"") + } +## is the drug in the dataset? + drugix <- drug.id %in% drug + + if (sum(drugix) == 0) { + warning(sprintf(""Drug(s) %s not in the dataset"", paste(drug, collapse="", ""))) + return(list(""all.type""=NULL, ""single.type""=NULL)) + } +## select xps with controls or with the drug(s) of interest + iix <- xp==""control"" | drugix + data <- data[iix, ,drop=FALSE] + drug.id <- drug.id[iix] + drug.concentration <- drug.concentration[iix] + type <- type[iix] + xp <- xp[iix] + batch <- batch[iix] + duration <- duration[iix] + + res.type <- NULL + +## build input matrix + inpumat <- NULL +## for each batch/vehicle of perturbations+controls (test within each batch/vehicle to avoid batch effect) + ubatch <- sort(unique(batch[!is.na(xp) & xp == ""perturbation""])) + names(ubatch) <- paste(""batch"", ubatch, sep="""") + + for (bb in seq_len(length(ubatch))) { +## identify the perturbations and corresponding control experiments + xpix <- rownames(data)[complete.cases(batch, xp) & batch == ubatch[bb] & xp == ""perturbation""] + ctrlix <- rownames(data)[complete.cases(batch, xp) & batch == ubatch[bb] & xp == ""control""] + + if (all(!is.na(c(xpix, ctrlix))) && length(xpix) > 0 && length(ctrlix) > 0) { + if (!all(is.element(ctrlix, rownames(data)))) { + stop(""data for some control experiments are missing!"") + } + if (verbose) { + cat(sprintf(""type %s: batch %i/%i -> %i vs %i\n"", utype[bb], bb, length(ubatch), length(xpix), length(ctrlix))) + } +## transformation of drug concentrations values + conc <- drug.concentration * 10^6 + inpumat <- rbind(inpumat, data.frame(""treated""=c(rep(1, length(xpix)), rep(0, length(ctrlix))), ""type""=c(type[xpix], type[ctrlix]), ""batch""=paste(""batch"", c(batch[xpix], batch[ctrlix]), sep=""""), ""concentration""=c(conc[xpix], conc[ctrlix]), ""duration""= c(duration[xpix], duration[ctrlix]))) + } + } + + inpumat[ , ""type""] <- factor(inpumat[ , ""type""], ordered=FALSE) + inpumat[ , ""batch""] <- factor(inpumat[ , ""batch""], ordered=FALSE) + + if (nrow(inpumat) < 3 || length(sort(unique(inpumat[ , ""concentration""]))) < 2 || length(unique(inpumat[ , ""duration""])) < 2) { +## not enough experiments in drug list + warning(sprintf(""Not enough data for drug(s) %s"", paste(drug, collapse="", ""))) + return(list(""all.type""=NULL, ""single.type""=NULL)) + } + + res <- NULL + utype <- sort(unique(as.character(inpumat[ , ""type""]))) + ltype <- list(""all""=utype) + if(single.type) { + ltype <- c(ltype, as.list(utype)) + names(ltype)[-1] <- utype + } + for(ll in seq_len(length(ltype))) { +## select the type of cell line/tissue of interest + inpumat2 <- inpumat[!is.na(inpumat[ , ""type""]) & is.element(inpumat[ , ""type""], ltype[[ll]]), , drop=FALSE] + inpumat2 <- inpumat2[complete.cases(inpumat2), , drop=FALSE] + if (nrow(inpumat2) < 3 || length(sort(unique(inpumat2[ , ""concentration""]))) < 2) { +## not enough experiments in data + nc <- c(""estimate"", ""se"", ""n"", ""tstat"", ""fstat"", ""pvalue"") + rest <- matrix(NA, nrow=nrow(data), ncol=length(nc), dimnames=list(rownames(data), nc)) + } else { +## test perturbation vs control + if(nthread > 1) { +## parallel threads + splitix <- parallel::splitIndices(nx=ncol(data), ncl=nthread) + splitix <- splitix[vapply(splitix, length, FUN.VALUE=numeric(1)) > 0] + mcres <- parallel::mclapply(splitix, function(x, data, inpumat) { + res <- t(apply(data[rownames(inpumat), x, drop=FALSE], 2, geneDrugPerturbation, concentration=inpumat[ , ""concentration""], type=inpumat[ , ""type""], batch=inpumat[ , ""batch""], duration=inpumat[,""duration""])) + return(res) + }, data=data, inpumat=inpumat2) + rest <- do.call(rbind, mcres) + } else { + rest <- t(apply(data[rownames(inpumat2), , drop=FALSE], 2, geneDrugPerturbation, concentration=inpumat2[ , ""concentration""], type=inpumat2[ , ""type""], batch=inpumat2[ , ""batch""], duration=inpumat2[,""duration""])) + } + } + rest <- cbind(rest, ""fdr""=p.adjust(rest[ , ""pvalue""], method=""fdr"")) + res <- c(res, list(rest)) + } + names(res) <- names(ltype) + return(res) +} + +## End +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/geneDrugPerturbation.R",".R","3075","79","#' @importFrom stats median +#' @importFrom stats complete.cases +#' @importFrom stats lm +#' @importFrom stats anova +#' @importFrom stats pf +#' + +## function computing gene-drug associations from perturbation data (CMAP) +geneDrugPerturbation <- function(x, concentration, type, batch, duration, model=FALSE) { +## input: +## x: numeric vector of gene expression values +## concentration: numeric vector with drug concentrations/doses +## type: vector of factors specifying the cell lines or type types +## batch: vector of factors specifying the batch +## duration: numeric vector of measurement times (in hours) +## model: Should the full linear model be returned? Default set to FALSE +## +## output: +## vector reporting the effect size (estimateof the coefficient of drug concentration), standard error (se), sample size (n), t statistic, and f statistics and its corresponding p-value + + ## NOTE:: The use of T/F warning from BiocCheck is a false positive on the string 'Pr(>F)' + + nc <- c(""estimate"", ""se"", ""n"", ""tstat"", ""fstat"", ""pvalue"") + if (length(sort(unique(concentration))) < 2) { + warning(""No drug concentrations tested"") + tt <- rep(NA, length(nc)) + names(tt) <- nc + return(tt) + } + ff0 <- sprintf(""x ~ 1"") + ff <- sprintf(""%s + concentration"", ff0) + + + if (length(sort(unique(type))) > 1) { + ff0 <- sprintf(""%s + type"", ff0) + ff <- sprintf(""%s + type"", ff) + } + if (length(sort(unique(batch))) > 1) { + ff0 <- sprintf(""%s + batch"", ff0) + ff <- sprintf(""%s + batch"", ff) + } + +### add experiment duration if the vector consists of more than one different value + + if (length(sort(unique(duration))) > 2) { + ff0 <- sprintf(""%s + duration"", ff0) + ff <- sprintf(""%s + duration"", ff) + } + + dd <- data.frame(""x""=x, ""concentration""=concentration, ""duration""=duration, ""type""=type, ""batch""=batch) + nn <- sum(complete.cases(dd)) + if(nn < 3) { + tt <- c(""estimate""=NA, ""se""=NA, ""n""=nn, ""tsat""=NA, ""fstat""=NA, ""pvalue""=NA) + } else { + names(dd)[1]<-""x"" + mm0 <- lm(formula=ff0, data=dd, model=FALSE, x=FALSE, y=FALSE, qr=TRUE) + mm <- lm(formula=ff, data=dd, model=model, x=FALSE, y=FALSE, qr=TRUE) + + mmc <- stats::anova(mm0, mm) + mm <- summary(mm) +## extract statistics + tt <- c(""estimate""=mm$coefficients[""concentration"", ""Estimate""], ""se""=mm$coefficients[""concentration"", ""Std. Error""], ""n""=nn, ""tsat""=mm$coefficients[""concentration"", ""t value""], ""fstat""=mmc$F[2], ""pvalue""=mmc$'Pr(>F)'[2]) + } + names(tt) <- nc +## add tissue type/cell line statistics + if(length(sort(unique(type))) > 1) { + rr <- summary(mm0) + ttype <- c(""type.fstat""=rr$fstatistic[""value""], ""type.pvalue""=pf(q=rr$fstatistic[""value""], df1=rr$fstatistic[""numdf""], df2=rr$fstatistic[""dendf""], lower.tail=FALSE)) + names(ttype) <- c(""type.fstat"", ""type.pvalue"") + } else { ttype <- c(""type.fstat""=NA, ""type.pvalue""=NA) } + tt <- c(tt, ttype) +## add model + if (model) { tt <- list(""stats""=tt, ""model""=mm)} + return(tt) +} + + +## End +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/PharmacoSet-utils.R",".R","2174","88","#' @include PharmacoSet-class.R PharmacoSet-accessors.R +NULL + +.local_class <- 'PharmacoSet' +.local_data <- 'CCLEsmall' +.local_treatment <- 'drug' + + +#### PharmacoGx dynamic documentation +#### +#### Warning: for dynamic docs to work, you must set +#### Roxygen: list(markdown=TRUE, r6=FALSE) +#### in the DESCRPTION file! + + +# =================================== +# Utility Method Documentation Object +# ----------------------------------- + + +#' @name PharmacoSet-utils +#' @eval CoreGx:::.docs_CoreSet_utils(class_=.local_class) +#' @eval .parseToRoxygen(""@examples data({data_})"", data_=.local_data) +NULL + + +# ====================================== +# Subset Methods +# -------------------------------------- + + + +## =================== +## ---- subsetBySample +## ------------------- + + +#' @rdname PharmacoSet-utils +#' @importMethodsFrom CoreGx subsetBySample +#' @eval CoreGx:::.docs_CoreSet_subsetBySample(class_=.local_class, +#' data_=.local_data) +setMethod('subsetBySample', signature(x='PharmacoSet'), function(x, samples) { + callNextMethod(x=x, samples=samples) +}) + + +## ====================== +## ---- subsetByTreatment +## ---------------------- + + +#' @rdname PharmacoSet-utils +#' @importMethodsFrom CoreGx subsetByTreatment +#' @eval CoreGx:::.docs_CoreSet_subsetByTreatment(class_=.local_class, +#' data_=.local_data, treatment_=.local_treatment) +setMethod('subsetByTreatment', signature(x='PharmacoSet'), + function(x, treatments) { + callNextMethod(x=x, treatments=treatments) +}) + + +## ==================== +## ---- subsetByFeature +## -------------------- + + +#' @rdname PharmacoSet-utils +#' @importFrom CoreGx subsetByFeature +#' @eval CoreGx:::.docs_CoreSet_subsetByFeature(class_=.local_class, +#' data_=.local_data) +setMethod('subsetByFeature', signature(x='PharmacoSet'), + function(x, features, mDataTypes) { + callNextMethod(x=x, features=features, mDataTypes) +}) + +## =========== +## ---- subset +## ----------- + +#' +#' +#' +setMethod('subset', signature('PharmacoSet'), + function(x, samples, treatments, features, ..., mDataTypes) { + callNextMethod(x=x, samples=samples, treatments=treatments, + features=features, ..., mDataTypes=mDataTypes) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/methods-summarizeMolecularProfiles.R",".R","10360","239","#' Takes molecular data from a PharmacoSet, and summarises them +#' into one entry per drug +#' +#' Given a PharmacoSet with molecular data, this function will summarize +#' the data into one profile per cell line, using the chosen summary.stat. Note +#' that this does not really make sense with perturbation type data, and will +#' combine experiments and controls when doing the summary if run on a +#' perturbation dataset. +#' +#' @examples +#' data(GDSCsmall) +#' GDSCsmall <- summarizeMolecularProfiles(GDSCsmall, mDataType = ""rna"", cell.lines=sampleNames(GDSCsmall), summary.stat = 'median', fill.missing = TRUE, verbose=TRUE) +#' GDSCsmall +#' +#' @param object \code{PharmacoSet} The PharmacoSet to summarize +#' @param mDataType \code{character} which one of the molecular data types +#' to use in the analysis, out of all the molecular data types available for the pset +#' for example: rna, rnaseq, snp +#' @param cell.lines \code{character} The cell lines to be summarized. +#' If any cell.line has no data, missing values will be created +#' @param features \code{caracter} A vector of the feature names to include in the summary +#' @param summary.stat \code{character} which summary method to use if there are repeated +#' cell.lines? Choices are ""mean"", ""median"", ""first"", or ""last"" +#' In case molecular data type is mutation or fusion ""and"" and ""or"" choices are available +#' @param fill.missing \code{boolean} should the missing cell lines not in the +#' molecular data object be filled in with missing values? +#' @param summarize A flag which when set to FALSE (defaults to TRUE) disables summarizing and +#' returns the data unchanged as a ExpressionSet +#' @param verbose \code{boolean} should messages be printed +#' @param binarize.threshold \code{numeric} A value on which the molecular data is binarized. +#' If NA, no binarization is done. +#' @param binarize.direction \code{character} One of ""less"" or ""greater"", the direction of binarization on +#' binarize.threshold, if it is not NA. +#' @param removeTreated \code{logical} If treated/perturbation experiments are present, should they +#' be removed? Defaults to yes. +#' +#' @return \code{matrix} An updated PharmacoSet with the molecular data summarized +#' per cell line. +#' +#' @importMethodsFrom CoreGx summarizeMolecularProfiles +#' @importFrom utils setTxtProgressBar txtProgressBar +#' @importFrom SummarizedExperiment SummarizedExperiment rowData rowData<- colData colData<- assays assays<- assayNames assayNames<- +#' @importFrom Biobase AnnotatedDataFrame +#' @keywords internal +#' @export +setMethod('summarizeMolecularProfiles', signature(object='PharmacoSet'), + function(object, mDataType, cell.lines, features, + summary.stat = c(""mean"", ""median"", ""first"", ""last"", ""and"", ""or""), + fill.missing = TRUE, summarize = TRUE, verbose = TRUE, + binarize.threshold = NA, binarize.direction = c(""less"", ""greater""), + removeTreated=TRUE) +{ + + mDataTypes <- mDataNames(object) + if (!(mDataType %in% mDataTypes)) { + stop (sprintf(""Invalid mDataType, choose among: %s"", paste(names(molecularProfilesSlot(object)), collapse="", ""))) + } + + if(summarize==FALSE){ + return(molecularProfilesSlot(object)[[mDataType]]) + } + + if (missing(features)) { + features <- rownames(featureInfo(object, mDataType)) + } else { + fix <- is.element(features, rownames(featureInfo(object, mDataType))) + if (verbose && !all(fix)) { + warning (sprintf(""Only %i/%i features can be found"", sum(fix), length(features))) + } + features <- features[fix] + } + + summary.stat <- match.arg(summary.stat) + binarize.direction <- match.arg(binarize.direction) + + if((!S4Vectors::metadata(molecularProfilesSlot(object)[[mDataType]])$annotation %in% c(""mutation"",""fusion"")) & (!summary.stat %in% c(""mean"", ""median"", ""first"", ""last""))) { + stop (""Invalid summary.stat, choose among: mean, median, first, last"" ) + } + if((S4Vectors::metadata(molecularProfilesSlot(object)[[mDataType]])$annotation %in% c(""mutation"",""fusion"")) & (!summary.stat %in% c(""and"", ""or""))) { + stop (""Invalid summary.stat, choose among: and, or"" ) + } + + if (missing(cell.lines)) { + cell.lines <- sampleNames(object) + } + + if(datasetType(object) %in% c(""perturbation"", ""both"") && removeTreated){ + if(!""xptype"" %in% colnames(phenoInfo(object, mDataType))) { + warning(""The passed in molecular data had no column: xptype. + \rEither the mDataType does not include perturbations, or the PSet is malformed. + \rAssuming the former and continuing."") + } else { + keepCols <- phenoInfo(object, mDataType)$xptype %in% c(""control"", ""untreated"") + molecularProfilesSlot(object)[[mDataType]] <- molecularProfilesSlot(object)[[mDataType]][,keepCols] + } + } + + + ##TODO:: have less confusing variable names + dd <- molecularProfiles(object, mDataType) + pp <- phenoInfo(object, mDataType) + + if(S4Vectors::metadata(molecularProfilesSlot(object)[[mDataType]])$annotation == ""mutation"") { + tt <- dd + tt[which(!is.na(dd) & dd ==""wt"")] <- FALSE + tt[which(!is.na(dd) & dd !=""wt"")] <- TRUE + tt <- apply(tt, 2, as.logical) + dimnames(tt) <- dimnames(dd) + dd <- tt + } + if(S4Vectors::metadata(molecularProfilesSlot(object)[[mDataType]])$annotation == ""fusion"") { + tt <- dd + tt[which(!is.na(dd) & dd ==""0"")] <- FALSE + tt[which(!is.na(dd) & dd !=""0"")] <- TRUE + tt <- apply(tt, 2, as.logical) + dimnames(tt) <- dimnames(dd) + dd <- tt + } + if(S4Vectors::metadata(molecularProfilesSlot(object)[[mDataType]])$annotation %in% c(""cnv"", ""rna"", ""rnaseq"", ""isoform"") + && !is.na(binarize.threshold)) { + tt <- dd + switch(binarize.direction, ""less"" = { + tt[which(!is.na(dd) & dd < binarize.threshold)] <- TRUE + tt[which(!is.na(dd) & dd >= binarize.threshold)] <- FALSE + }, ""greater"" = { + tt[which(!is.na(dd) & dd > binarize.threshold)] <- TRUE + tt[which(!is.na(dd) & dd <= binarize.threshold)] <- FALSE + }) + tt <- apply(tt, 2, as.logical) + dimnames(tt) <- dimnames(dd) + dd <- tt + } + if (any(colnames(dd) != rownames(pp))) { + warning (""Samples in phenodata and expression matrices must be ordered the same way"") + dd <- dd[ , rownames(pp), drop=FALSE] + } + if (!fill.missing) { + cell.lines <- intersect(cell.lines, unique(pp[!is.na(pp[ , ""sampleid""]), ""sampleid""])) + } + if (length(cell.lines) == 0) { + stop (""No cell lines in common"") + } + + ## select profiles with no replicates + duplix <- unique(pp[!is.na(pp[ , ""sampleid""]) & duplicated(pp[ , ""sampleid""]), ""sampleid""]) + ucell <- setdiff(cell.lines, duplix) + + ## keep the non ambiguous cases + dd2 <- dd[ , match(ucell, pp[ , ""sampleid""]), drop=FALSE] + pp2 <- pp[match(ucell, pp[ , ""sampleid""]), , drop=FALSE] + if (length(duplix) > 0) { + if (verbose) { + message(sprintf(""Summarizing %s molecular data for:\t%s"", mDataType, annotation(object)$name)) + total <- length(duplix) + # create progress bar + pb <- utils::txtProgressBar(min=0, max=total, style=3) + i <- 1 + } + ## replace factors by characters to allow for merging duplicated experiments + pp2 <- apply(pp2, 2, function (x) { + if (is.factor(x)) { + return (as.character(x)) + } else { + return (x) + } + }) + ## there are some replicates to collapse + for (x in duplix) { + myx <- which(!is.na(pp[ , ""sampleid""]) & is.element(pp[ , ""sampleid""], x)) + switch(summary.stat, + ""mean"" = { + ddt <- apply(dd[ , myx, drop=FALSE], 1, mean) + }, + ""median""={ + ddt <- apply(dd[ , myx, drop=FALSE], 1, median) + }, + ""first""={ + ddt <- dd[ , myx[1], drop=FALSE] + }, + ""last"" = { + ddt <- dd[ , myx[length(myx)], drop=FALSE] + }, + ""and"" = { + ddt <- apply(dd[ , myx, drop=FALSE], 1, function(x) do.call(`&`, as.list(x))) + }, + ""or"" = { + ddt <- apply(dd[ , myx, drop=FALSE], 1, function(x) do.call(`|`, as.list(x))) + } + ) + ppt <- apply(pp[myx, , drop=FALSE], 2, function (x) { + x <- paste(unique(as.character(x[!is.na(x)])), collapse=""///"") + return (x) + }) + ppt[!is.na(ppt) & ppt == """"] <- NA + dd2 <- cbind(dd2, ddt) + pp2 <- rbind(pp2, ppt) + if (verbose){ + utils::setTxtProgressBar(pb, i) + i <- i + 1 + } + } + if (verbose) { + close(pb) + } + } + colnames(dd2) <- rownames(pp2) <- c(ucell, duplix) + + ## reorder cell lines + dd2 <- dd2[ , cell.lines, drop=FALSE] + pp2 <- pp2[cell.lines, , drop=FALSE] + pp2[ , ""sampleid""] <- cell.lines + res <- molecularProfilesSlot(object)[[mDataType]] + if(S4Vectors::metadata(molecularProfilesSlot(object)[[mDataType]])$annotation %in% c(""mutation"", ""fusion"")) { + tt <- dd2 + tt[which(!is.na(dd2) & dd2)] <- ""1"" + tt[which(!is.na(dd2) & !dd2)] <- ""0"" + dd2 <- tt + } + res <- SummarizedExperiment::SummarizedExperiment(dd2) + pp2 <- S4Vectors::DataFrame(pp2, row.names=rownames(pp2)) + pp2$tissueid <- sampleInfo(object)[pp2$sampleid, ""tissueid""] + SummarizedExperiment::colData(res) <- pp2 + SummarizedExperiment::rowData(res) <- featureInfo(object, mDataType) + ##TODO:: Generalize this to multiple assay SummarizedExperiments! + # if(!is.null(SummarizedExperiment::assay(res, 1))) { + # SummarizedExperiment::assay(res, 2) <- matrix(rep(NA, + # length(assay(res, 1)) + # ), + # nrow=nrow(assay(res, 1)), + # ncol=ncol(assay(res, 1)), + # dimnames=dimnames(assay(res, 1)) + # ) + # } + assayNames(res) <- assayNames(molecularProfilesSlot(object)[[mDataType]])[[1]] + res <- res[features,] + S4Vectors::metadata(res) <- S4Vectors::metadata(molecularProfilesSlot(object)[[mDataType]]) + return(res) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/methods-View.R",".R","1774","53","#' Guarded View for CoreSet/PharmacoSet +#' +#' Emits the same compatibility error as `CoreGx::show()` and stops for +#' outdated CoreSet-derived objects. Otherwise delegates to whatever +#' `utils::View` is installed in `package:utils` (RStudio/Positron override +#' or base). +#' +#' @param x Any R object, typically a data.frame-like or `CoreSet`-derived. +#' @param title Optional title for the data viewer. +#' +#' @return Invisibly returns whatever the underlying viewer returns. +#' @seealso [utils::View()] +#' +#' @examples +#' if (interactive()) { +#' data(""CCLEsmall"", package = ""PharmacoGx"") +#' View(CCLEsmall) +#' } +#' +#' @export +View <- function(x, title = NULL) { + # Only intercept for CoreSet-derived objects; keep everything else untouched + if (methods::is(x, ""CoreSet"")) { + # Replicate CoreGx::show() outdated check (CoreGx/R/CoreSet-class.R:424-428) + hasSample <- methods::.hasSlot(x, ""sample"") + hasTreatment <- methods::.hasSlot(x, ""treatment"") + if (!(hasSample && hasTreatment)) { + # Hard stop with the same message as CoreGx::show() + stop( + CoreGx::.errorMsg( + ""This "", + class(x)[1], + "" object appears to be out of date! "", + ""Please run object <- updateObject(object) to update "", + ""the object for compatibility with the current release."" + ), + call. = FALSE + ) + } + } + + # Ensure Positron/RStudio/base receive a scalar string title + if (missing(title) || is.null(title)) { + title2 <- base::deparse(substitute(x)) + } else { + title2 <- base::as.character(title)[1] + if (is.na(title2)) title2 <- base::deparse(substitute(x)) + } + + # Delegate to whatever View is installed in package:utils + get(""View"", envir = as.environment(""package:utils""))(x, title2) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/downloadSignatures.R",".R","3055","81","#' Download Drug Perturbation Signatures +#' +#' This function allows you to download an array of drug perturbation +#' signatures, as would be computed by the `drugPerturbationSig` function, +#' for the available perturbation `PharmacoSets`. This function allows the +#' user to skip these very lengthy calculation steps for the datasets available, +#' and start their analysis from the already computed signatures +#' +#' @examples +#' +#' \dontrun{ +#' if (interactive()) downloadPertSig(""CMAP_2016"") +#' } +#' +#' @param name A `character(1)` string, the name of the PharmacoSet for which +#' to download signatures. The name should match the names returned in the +#' `PSet Name` column of `availablePSets(canonical=FALSE)`. +#' @param saveDir A `character(1)` string with the folder path where the +#' PharmacoSet should be saved. Defaults to `""./PSets/Sigs/""`. Will +#' create directory if it does not exist. +#' @param fileName `character(1)` What to name the downloaded file. Defaults +#' to '`name`_signature.RData' when excluded. +#' @param verbose `logical(1)` Should `downloader` show detailed messages? +#' @param ... `pairlist` Force subsequent arguments to be named. +#' @param myfn `character(1)` A deprecated version of `fileName`. Still works +#' for now, but will be deprecated in future releases. +#' +#' @return An array type object contaning the signatures +#' +#' @export +#' @importFrom CoreGx .warning .funContext +#' @import downloader +downloadPertSig <- function(name, saveDir=file.path(""."", ""PSets"", ""Sigs""), + fileName, verbose=TRUE, ..., myfn) +{ + funContext <- .funContext('::downloadPertSig') + if (missing(fileName) && !missing(myfn)) { + .warning(funContext, 'The `myfn` parameter is being deprecated in + favour of `fileName`. It still works for now, but will be retired + in a future release.') + fileName <- myfn + } + + # change the download timeout since the files are big + opts <- options() + options(timeout=600) + on.exit(options(opts)) + + # get the annotations for available data + pSetTable <- availablePSets(canonical=FALSE) + + # pick a signature from the list + whichx <- match(name, pSetTable[, 3]) + if (is.na(whichx)){ + stop('Unknown Dataset. Please use the `Dataset Name` column in the + data.frame returned by the availablePSet function to select a + PharmacoSet') + } + if (!pSetTable[whichx, ""type""] %in% c(""perturbation"", ""both"")){ + stop('Signatures are available only for perturbation type datasets') + } + + if(!file.exists(saveDir)) { + dir.create(saveDir, recursive=TRUE) + } + + if (missing(fileName)) { + fileName <- paste(pSetTable[whichx, ]$`Dataset Name`, + ""_signatures.RData"", sep="""") + } + + downloader::download( + paste(""https://www.pmgenomics.ca/bhklab/sites/default/files/downloads"", + fileName, sep='/'), + destfile=file.path(saveDir, fileName), quiet=!verbose, mode='wb') + + sig <- load(file.path(saveDir, fileName)) + + return(get(sig)) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/cosinePerm.R",".R","349","12","#' Cosine Permuations +#' +#' @inherit CoreGx::cosinePerm +#' @inheritParams CoreGx::cosinePerm +#' +#' @export +cosinePerm <- function(x, y, nperm=1000, + alternative=c(""two.sided"", ""less"", ""greater""), + include.perm=FALSE, nthread=1) +{ + CoreGx::cosinePerm(x, y, nperm, alternative, include.perm, nthread) +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/GR.R",".R","396","7",".GR <- function(x, pars, tau) { + #GR takes in a vector of log concentrations, a vector of DRC parameters from the .Hill() + #function, and a coefficient tau equal to the number of doubling times occuring between + #the start of the experiment and the taking of the viability measurements. It then returns + #the GR-value associated with those conditions. + return((.Hill(x, pars)) ^ (1 / tau)) +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeAUC.R",".R","4797","126","#' Computes the AUC for a Drug Dose Viability Curve +#' +#' Returns the AUC (Area Under the drug response Curve) given concentration and viability as input, normalized by the concentration +#' range of the experiment. The area returned is the response (1-Viablility) area, i.e. area under the curve when the response curve +#' is plotted on a log10 concentration scale, with high AUC implying high sensitivity to the drug. The function can calculate both +#' the area under a fitted Hill Curve to the data, and a trapz numeric integral of the actual data provided. Alternatively, the parameters +#' of a Hill Slope returned by logLogisticRegression can be passed in if they already known. +#' +#' @examples +#' dose <- c(0.0025,0.008,0.025,0.08,0.25,0.8,2.53,8) +#' viability <- c(108.67,111,102.16,100.27,90,87,74,57) +#' computeAUC(dose, viability) +#' +#' +#' @param concentration `numeric` is a vector of drug concentrations. +#' @param viability `numeric` is a vector whose entries are the viability values observed in the presence of the +#' drug concentrations whose logarithms are in the corresponding entries of conc, where viability 0 +#' indicates that all cells died, and viability 1 indicates that the drug had no effect on the cells. +#' @param Hill_fit `list` or `vector` In the order: c(""Hill Slope"", ""E_inf"", ""EC50""), the parameters of a Hill Slope +#' as returned by logLogisticRegression. If conc_as_log is set then the function assumes logEC50 is passed in, and if +#' viability_as_pct flag is set, it assumes E_inf is passed in as a percent. Otherwise, E_inf is assumed to be a decimal, +#' and EC50 as a concentration. +#' @param conc_as_log `logical`, if true, assumes that log10-concentration data has been given rather than concentration data. +#' @param viability_as_pct `logical`, if false, assumes that viability is given as a decimal rather +#' than a percentage, and returns AUC as a decimal. Otherwise, viability is interpreted as percent, and AUC is returned 0-100. +#' @param trunc `logical`, if true, causes viability data to be truncated to lie between 0 and 1 before +#' curve-fitting is performed. +#' @param area.type Should the area be computed using the actual data (""Actual""), or a fitted curve (""Fitted"") +#' @param verbose `logical`, if true, causes warnings thrown by the function to be printed. +#' @return Numeric AUC value +#' +#' @export +#' @import caTools +computeAUC <- function (concentration, + viability, + Hill_fit, + conc_as_log = FALSE, + viability_as_pct = TRUE, + trunc = TRUE, + area.type = c(""Fitted"", ""Actual""), + verbose = TRUE + #, ... + ) { + + if (missing(concentration)) { + + stop(""The concentration values to integrate over must always be provided."") + + } +if (missing(area.type)) { + area.type <- ""Fitted"" +} else { + area.type <- match.arg(area.type) +} +if (area.type == ""Fitted"" && missing(Hill_fit)) { + + Hill_fit <- logLogisticRegression(concentration, + viability, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + cleanData <- sanitizeInput(conc=concentration, + Hill_fit=Hill_fit, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + pars <- cleanData[[""Hill_fit""]] + concentration <- cleanData[[""log_conc""]] +} else if (area.type == ""Fitted"" && !missing(Hill_fit)) { + + cleanData <- sanitizeInput(conc = concentration, + viability = viability, + Hill_fit = Hill_fit, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + pars <- cleanData[[""Hill_fit""]] + concentration <- cleanData[[""log_conc""]] +} else if (area.type == ""Actual"" && !missing(viability)){ + cleanData <- sanitizeInput(conc = concentration, + viability = viability, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + concentration <- cleanData[[""log_conc""]] + viability <- cleanData[[""viability""]] +} else if (area.type == ""Actual"" && missing(viability)) { + + stop(""To calculate the actual area using a trapezoid integral, the raw viability values are needed!"") +} + +if (length(concentration) < 2) { + return(NA) +} + +a <- min(concentration) +b <- max(concentration) +if (area.type == ""Actual"") { + trapezoid.integral <- caTools::trapz(concentration, viability) + AUC <- 1 - trapezoid.integral / (b - a) +} +else { + if (pars[2] == 1) { + AUC <- 0 + } else if (pars[1] == 0){ + AUC <- (1 - pars[2]) / 2 + } else { + AUC <- as.numeric( + (1 - pars[2]) / (pars[1] * (b - a)) * + log10((1 + (10 ^ (b - pars[3])) ^ pars[1]) / + (1 + (10 ^ (a - pars[3])) ^ pars[1]))) + } +} + +if(viability_as_pct){ + + AUC <- AUC*100 + +} + +return(AUC) +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/connectivityScore.R",".R","395","13","#' Function computing connectivity scores between two signatures +#' +#' @inherit CoreGx::connectivityScore +#' @inheritParams CoreGx::connectivityScore +#' +#' @export +connectivityScore <- + function(x, y, method=c(""gsea"", ""fgsea"", ""gwc""), nperm=1e4, nthread=1, + gwc.method=c(""spearman"", ""pearson""), ...) +{ + CoreGx::connectivityScore(x, y, method, nperm, nthread, gwc.method, ...) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/callingWaterfall.R",".R","403","12","#' Drug sensitivity calling using waterfall plots +#' +#' @inherit CoreGx::callingWaterfall +#' @inheritParams CoreGx::callingWaterfall +#' +#' +callingWaterfall <- function(x, type=c(""IC50"", ""AUC"", ""AMAX""), + intermediate.fold=c(4, 1.2, 1.2), cor.min.linear=0.95, name=""Drug"", + plot=FALSE) { + CoreGx::callingWaterfall(x, type, intermediate.fold, cor.min.linear, name, + plot) +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/drugPerturbationSig.R",".R","5683","115","#' Creates a signature representing gene expression (or other molecular profile) +#' change induced by administrating a drug, for use in drug effect analysis. +#' +#' Given a Pharmacoset of the perturbation experiment type, and a list of drugs, +#' the function will compute a signature for the effect of drug concentration on +#' the molecular profile of a cell. The algorithm uses a regression model which +#' corrects for experimental batch effects, cell specific differences, and +#' duration of experiment to isolate the effect of the concentration of the drug +#' applied. The function returns the estimated coefficient for concentration, +#' the t-stat, the p-value and the false discovery rate associated with that +#' coefficient, in a 3 dimensional array, with genes in the first direction, +#' drugs in the second, and the selected return values in the third. +#' +#' @examples +#' data(CMAPsmall) +#' drug.perturbation <- drugPerturbationSig(CMAPsmall, mDataType=""rna"", nthread=1) +#' print(drug.perturbation) +#' +#' @param pSet [PharmacoSet] a PharmacoSet of the perturbation experiment type +#' @param mDataType `character` which one of the molecular data types to use +#' in the analysis, out of dna, rna, rnaseq, snp, cnv +#' @param drugs `character` a vector of drug names for which to compute the +#' signatures. Should match the names used in the PharmacoSet. +#' @param cells `character` a vector of cell names to use in computing the +#' signatures. Should match the names used in the PharmacoSet. +#' @param features `character` a vector of features for which to compute the +#' signatures. Should match the names used in correspondant molecular data in PharmacoSet. +#' @param nthread `numeric` if multiple cores are available, how many cores +#' should the computation be parallelized over? +#' @param returnValues `character` Which of estimate, t-stat, p-value and fdr +#' should the function return for each gene drug pair? +#' @param verbose `logical(1)` Should diagnostive messages be printed? (default false) +#' +#' @return `list` a 3D array with genes in the first dimension, drugs in the +#' second, and return values in the third. +#' +#' @export +drugPerturbationSig <- function(pSet, mDataType, drugs, cells, features, + nthread=1, returnValues=c(""estimate"",""tstat"", ""pvalue"", ""fdr""), + verbose=FALSE) +{ + availcore <- parallel::detectCores() + if ( nthread > availcore) { + nthread <- availcore + } + options(""mc.cores""=nthread) + if(!missing(cells)){ + if(!all(cells%in%sampleNames(pSet))){ + stop(""The cell names should match to the names used in sampleNames(pSet)"") + } + pSet <- subsetTo(pSet, cells=cells) + } + if (mDataType %in% names(pSet@molecularProfiles)) { + #eset <- pSet@molecularProfiles[[mDataType]] + if(S4Vectors::metadata(pSet@molecularProfiles[[mDataType]])$annotation != ""rna""){ + stop(sprintf(""Only rna data type perturbations are currently implemented"")) + } + } else { + stop (sprintf(""This pSet does not have any molecular data of type %s, choose among: %s"", mDataType), paste(names(pSet@molecularProfiles), collapse="", "")) + } + + + if (missing(drugs)) { + drugn <- treatmentNames(pSet) + } else { + drugn <- drugs + } + dix <- is.element(drugn, PharmacoGx::phenoInfo(pSet, mDataType)[ , ""treatmentid""]) + if (verbose && !all(dix)) { + warning (sprintf(""%i/%i drugs can be found"", sum(dix), length(drugn))) + } + if (!any(dix)) { + stop(""None of the drugs were found in the dataset"") + } + drugn <- drugn[dix] + + if (missing(features)) { + features <- rownames(featureInfo(pSet, mDataType)) + } else { + fix <- is.element(features, rownames(featureInfo(pSet, mDataType))) + if (verbose && !all(fix)) { + warning (sprintf(""%i/%i features can be found"", sum(fix), length(features))) + } + features <- features[fix] + } + + # splitix <- parallel::splitIndices(nx=length(drugn), ncl=nthread) + # splitix <- splitix[vapply(splitix, length, FUN.VALUE=numeric(1)) > 0] + mcres <- lapply(drugn, function(x, exprs, sampleinfo) { + res <- NULL + i = x + ## using a linear model (x ~ concentration + cell + batch + duration) + res <- rankGeneDrugPerturbation(data=exprs, drug=i, drug.id=as.character(sampleinfo[ , ""treatmentid""]), drug.concentration=as.numeric(sampleinfo[ , ""concentration""]), type=as.character(sampleinfo[ , ""sampleid""]), xp=as.character(sampleinfo[ , ""xptype""]), batch=as.character(sampleinfo[ , ""batchid""]), duration=as.character(sampleinfo[ , ""duration""]) ,single.type=FALSE, nthread=nthread, verbose=FALSE)$all[ , returnValues, drop=FALSE] + res <- list(res) + names(res) <- i + return(res) + }, exprs=t(molecularProfiles(pSet, mDataType)[features, , drop=FALSE]), sampleinfo=PharmacoGx::phenoInfo(pSet, mDataType)) + res <- do.call(c, mcres) + res <- res[!vapply(res, is.null, FUN.VALUE=logical(1))] + drug.perturbation <- array(NA, dim=c(nrow(featureInfo(pSet, mDataType)[features,, drop=FALSE]), length(res), ncol(res[[1]])), dimnames=list(rownames(featureInfo(pSet, mDataType)[features,,drop=FALSE]), names(res), colnames(res[[1]]))) + for (j in seq_len(ncol(res[[1]]))) { + ttt <- vapply(res, function(x, j, k) { + xx <- array(NA, dim=length(k), dimnames=list(k)) + xx[rownames(x)] <- x[ , j, drop=FALSE] + return (xx) + }, j=j, k=rownames(featureInfo(pSet, mDataType)[features,, drop=FALSE]), + FUN.VALUE=numeric(dim(drug.perturbation)[1])) + drug.perturbation[rownames(featureInfo(pSet, mDataType)[features,, drop=FALSE]), names(res), j] <- ttt + } + + drug.perturbation <- PharmacoSig(drug.perturbation, PSetName = name(pSet), Call = as.character(match.call()), SigType='Perturbation') + + return(drug.perturbation) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/methods-drugSensitivitySig.R",".R","16965","377","#' Creates a signature representing the association between gene expression (or +#' other molecular profile) and drug dose response, for use in drug sensitivity +#' analysis. +#' +#' Given a Pharmacoset of the sensitivity experiment type, and a list of drugs, +#' the function will compute a signature for the effect gene expression on the +#' molecular profile of a cell. The function returns the estimated coefficient, +#' the t-stat, the p-value and the false discovery rate associated with that +#' coefficient, in a 3 dimensional array, with genes in the first direction, +#' drugs in the second, and the selected return values in the third. +#' +#' @examples +#' data(GDSCsmall) +#' drug.sensitivity <- drugSensitivitySig(GDSCsmall, +#' mDataType = ""rna"", +#' nthread = 1, features = fNames(GDSCsmall, ""rna"")[1] +#' ) +#' print(drug.sensitivity) +#' +#' @param object `PharmacoSet` a PharmacoSet of the perturbation experiment type +#' @param mDataType `character` which one of the molecular data types to use +#' in the analysis, out of dna, rna, rnaseq, snp, cnv +#' @param drugs `character` a vector of drug names for which to compute the +#' signatures. Should match the names used in the PharmacoSet. +#' @param features `character` a vector of features for which to compute the +#' signatures. Should match the names used in correspondant molecular data in PharmacoSet. +#' @param cells `character` allows choosing exactly which cell lines to include for the signature fitting. +#' Should be a subset of sampleNames(pSet) +#' @param tissues `character` a vector of which tissue types to include in the signature fitting. +#' Should be a subset of sampleInfo(pSet)$tissueid +#' @param nthread `numeric` if multiple cores are available, how many cores +#' should the computation be parallelized over? +#' @param returnValues `character` Which of estimate, t-stat, p-value and fdr +#' should the function return for each gene drug pair? +#' @param sensitivity.measure `character` which measure of the drug dose +#' sensitivity should the function use for its computations? Use the +#' sensitivityMeasures function to find out what measures are available for each PSet. +#' @param molecular.summary.stat `character` What summary statistic should be used to +#' summarize duplicates for cell line molecular profile measurements? +#' @param sensitivity.summary.stat `character` What summary statistic should be used to +#' summarize duplicates for cell line sensitivity measurements? +#' @param sensitivity.cutoff `numeric` Allows the user to binarize the sensitivity data using this threshold. +#' @param standardize `character` One of ""SD"", ""rescale"", or ""none"", for the form of standardization of +#' the data to use. If ""SD"", the the data is scaled so that SD = 1. If rescale, then the data is scaled so that the 95% +#' interquantile range lies in \[0,1\]. If none no rescaling is done. +#' @param molecular.cutoff Allows the user to binarize the sensitivity data using this threshold. +#' @param molecular.cutoff.direction `character` One of ""less"" or ""greater"", allows to set direction of binarization. +#' @param verbose `logical` 'TRUE' if the warnings and other informative message shoud be displayed +#' @param parallel.on One of ""gene"" or ""drug"", chooses which level to parallelize computation (by gene, or by drug). +#' @param modeling.method One of ""anova"" or ""pearson"". If ""anova"", nested linear models (including and excluding the molecular feature) adjusted for +#' are fit after the data is standardized, and ANOVA is used to estimate significance. If ""pearson"", partial correlation adjusted for tissue of origin are +#' fit to the data, and a Pearson t-test (or permutation) test are used. Note that the difference is in whether standardization is done across the whole +#' dataset (anova) or within each tissue (pearson), as well as the test applied. +#' @param inference.method Should ""analytic"" or ""resampling"" (permutation testing + bootstrap) inference be used to estimate significance. +#' For permutation testing, QUICK-STOP is used to adaptively stop permutations. Resampling is currently only implemented for ""pearson"" modelling method. +#' @param ... additional arguments not currently fully supported by the function +#' +#' @return `array` a 3D array with genes in the first dimension, drugs in the +#' second, and return values in the third. +#' +#' @importMethodsFrom CoreGx drugSensitivitySig +#' @export +setMethod( + ""drugSensitivitySig"", + signature(object = ""PharmacoSet""), + function(object, mDataType, drugs, features, cells, tissues, sensitivity.measure = ""auc_recomputed"", + molecular.summary.stat = c(""mean"", ""median"", ""first"", ""last"", ""or"", ""and""), + sensitivity.summary.stat = c(""mean"", ""median"", ""first"", ""last""), + returnValues = c(""estimate"", ""pvalue"", ""fdr""), + sensitivity.cutoff, standardize = c(""SD"", ""rescale"", ""none""), molecular.cutoff = NA, + molecular.cutoff.direction = c(""less"", ""greater""), + nthread = 1, parallel.on = c(""drug"", ""gene""), modeling.method = c(""anova"", ""pearson""), + inference.method = c(""analytic"", ""resampling""), verbose = TRUE, ...) { + .drugSensitivitySigPharmacoSet( + object, mDataType, drugs, features, cells, tissues, sensitivity.measure, + molecular.summary.stat, sensitivity.summary.stat, returnValues, + sensitivity.cutoff, standardize, molecular.cutoff, molecular.cutoff.direction, + nthread, parallel.on, modeling.method, inference.method, verbose, ... + ) + } +) + +#' @import parallel +#' @importFrom SummarizedExperiment assayNames assay +#' @keywords internal +.drugSensitivitySigPharmacoSet <- function(object, + mDataType, + drugs, + features, + cells, + tissues, + sensitivity.measure = ""auc_recomputed"", + molecular.summary.stat = c(""mean"", ""median"", ""first"", ""last"", ""or"", ""and""), + sensitivity.summary.stat = c(""mean"", ""median"", ""first"", ""last""), + returnValues = c(""estimate"", ""pvalue"", ""fdr""), + sensitivity.cutoff, standardize = c(""SD"", ""rescale"", ""none""), + molecular.cutoff = NA, + molecular.cutoff.direction = c(""less"", ""greater""), + nthread = 1, + parallel.on = c(""drug"", ""gene""), + modeling.method = c(""anova"", ""pearson""), + inference.method = c(""analytic"", ""resampling""), + verbose = TRUE, + ...) { + + ### This function needs to: Get a table of AUC values per cell line / drug + ### Be able to recompute those values on the fly from raw data if needed to change concentration + ### Be able to choose different summary methods on fly if needed (need to add annotation to table to tell what summary method previously used) + ### Be able to extract genomic data + ### Run rankGeneDrugSens in parallel at the drug level + ### Return matrix as we had before + + # sensitivity.measure <- match.arg(sensitivity.measure) + molecular.summary.stat <- match.arg(molecular.summary.stat) + sensitivity.summary.stat <- match.arg(sensitivity.summary.stat) + standardize <- match.arg(standardize) + molecular.cutoff.direction <- match.arg(molecular.cutoff.direction) + parallel.on <- match.arg(parallel.on) + dots <- list(...) + ndots <- length(dots) + modeling.method <- match.arg(modeling.method) + inference.method <- match.arg(inference.method) + + + + if (is.null(dots[[""sProfiles""]]) & !all(sensitivity.measure %in% colnames(sensitivityProfiles(object)))) { + stop(sprintf(""Invalid sensitivity measure for %s, choose among: %s"", annotation(object)$name, paste(colnames(sensitivityProfiles(object)), collapse = "", ""))) + } + + if (!(mDataType %in% names(molecularProfilesSlot(object)))) { + stop(sprintf(""Invalid mDataType for %s, choose among: %s"", annotation(object)$name, paste(names(molecularProfilesSlot(object)), collapse = "", ""))) + } + switch(S4Vectors::metadata(molecularProfilesSlot(object)[[mDataType]])$annotation, + ""mutation"" = { + if (!is.element(molecular.summary.stat, c(""or"", ""and""))) { + stop(""Molecular summary statistic for mutation must be either 'or' or 'and'"") + } + }, + ""fusion"" = { + if (!is.element(molecular.summary.stat, c(""or"", ""and""))) { + stop(""Molecular summary statistic for fusion must be either 'or' or 'and'"") + } + }, + ""rna"" = { + if (!is.element(molecular.summary.stat, c(""mean"", ""median"", ""first"", ""last""))) { + stop(""Molecular summary statistic for rna must be either 'mean', 'median', 'first' or 'last'"") + } + }, + ""cnv"" = { + if (!is.element(molecular.summary.stat, c(""mean"", ""median"", ""first"", ""last""))) { + stop(""Molecular summary statistic for cnv must be either 'mean', 'median', 'first' or 'last'"") + } + }, + ""rnaseq"" = { + if (!is.element(molecular.summary.stat, c(""mean"", ""median"", ""first"", ""last""))) { + stop(""Molecular summary statistic for rna must be either 'mean', 'median', 'first' or 'last'"") + } + }, + ""isoform"" = { + if (!is.element(molecular.summary.stat, c(""mean"", ""median"", ""first"", ""last""))) { + stop(""Molecular summary statistic for rna must be either 'mean', 'median', 'first' or 'last'"") + } + }, + stop(sprintf(""No summary statistic for %s has been implemented yet"", S4Vectors::metadata(molecularProfilesSlot(object)[[mDataType]])$annotation)) + ) + + if (!is.element(sensitivity.summary.stat, c(""mean"", ""median"", ""first"", ""last""))) { + stop(""Sensitivity summary statistic for sensitivity must be either 'mean', 'median', 'first' or 'last'"") + } + + if (missing(sensitivity.cutoff)) { + sensitivity.cutoff <- NA + } + if (missing(drugs)) { + if(is.null(dots[[""sProfiles""]])){ + drugn <- drugs <- treatmentNames(object) + } else { + drugn <- drugs <- rownames(dots[[""sProfiles""]]) + } + } else { + drugn <- drugs + } + + if (missing(cells)) { + celln <- cells <- sampleNames(object) + } else { + celln <- cells + } + + availcore <- parallel::detectCores() + + if (nthread > availcore) { + nthread <- availcore + } + + if (parallel.on == ""drug"") { + nthread_drug <- nthread + nthread_gene <- 1 + } else { + nthread_gene <- nthread + nthread_drug <- 1 + } + + if (missing(features)) { + features <- rownames(featureInfo(object, mDataType)) + } else { + fix <- is.element(features, rownames(featureInfo(object, mDataType))) + if (verbose && !all(fix)) { + warning(sprintf(""%i/%i features can be found"", sum(fix), length(features))) + } + features <- features[fix] + } + + # if(missing(modeling.method)){ + # modeling.method <- ""anova"" + # } + # + # if(missing(inference.method)){ + # inference.method <- ""analytic"" + # } + + if (is.null(dots[[""sProfiles""]])) { + drugpheno.all <- lapply(sensitivity.measure, function(sensitivity.measure) { + return(t(summarizeSensitivityProfiles(object, + sensitivity.measure = sensitivity.measure, + summary.stat = sensitivity.summary.stat, + verbose = verbose + ))) + }) + } else { + sProfiles <- dots[[""sProfiles""]] + drugpheno.all <- list(t(sProfiles)) + } + + dix <- is.element(drugn, do.call(colnames, drugpheno.all)) + if (verbose && !all(dix)) { + warning(sprintf(""%i/%i drugs can be found"", sum(dix), length(drugn))) + } + if (!any(dix)) { + stop(""None of the drugs were found in the dataset"") + } + drugn <- drugn[dix] + + cix <- is.element(celln, do.call(rownames, drugpheno.all)) + if (verbose && !all(cix)) { + warning(sprintf(""%i/%i cells can be found"", sum(cix), length(celln))) + } + if (!any(cix)) { + stop(""None of the cells were found in the dataset"") + } + celln <- celln[cix] + + if (!missing(tissues)) { + celln <- celln[sampleInfo(object)[celln, ""tissueid""] %in% tissues] + } else { + tissues <- unique(sampleInfo(object)[celln, ""tissueid""]) + } + + molecularProfilesSlot(object)[[mDataType]] <- summarizeMolecularProfiles( + object = object, + mDataType = mDataType, + summary.stat = molecular.summary.stat, + binarize.threshold = molecular.cutoff, + binarize.direction = molecular.cutoff.direction, + verbose = verbose + )[features, ] + + if (!is.null(dots[[""mProfiles""]])) { + mProfiles <- dots[[""mProfiles""]] + SummarizedExperiment::assay(molecularProfilesSlot(object)[[mDataType]]) <- mProfiles[features, colnames(molecularProfilesSlot(object)[[mDataType]]), drop = FALSE] + } + + drugpheno.all <- lapply(drugpheno.all, function(x) { + x[intersect(phenoInfo(object, mDataType)[, ""sampleid""], celln), , drop = FALSE] + }) + + molcellx <- phenoInfo(object, mDataType)[, ""sampleid""] %in% celln + + type <- as.factor(sampleInfo(object)[phenoInfo(object, mDataType)[molcellx, ""sampleid""], ""tissueid""]) + + if (""batchid"" %in% colnames(phenoInfo(object, mDataType))) { + batch <- phenoInfo(object, mDataType)[molcellx, ""batchid""] + } else { + batch <- rep(NA, times = nrow(phenoInfo(object, mDataType))) + } + batch[!is.na(batch) & batch == ""NA""] <- NA + batch <- as.factor(batch) + names(batch) <- phenoInfo(object, mDataType)[molcellx, ""sampleid""] + batch <- batch[rownames(drugpheno.all[[1]])] + if (verbose) { + message(""Computing drug sensitivity signatures..."") + } + + ### Calculate approximate number of perms needed + + + + if (is.null(dots[[""req_alpha""]])) { + req_alpha <- 0.05 / (nrow(molecularProfilesSlot(object)[[mDataType]])) ## bonferonni correction + } else { + req_alpha <- dots[[""req_alpha""]] + } + + + + # splitix <- parallel::splitIndices(nx = length(drugn), ncl = nthread_drug) + # splitix <- splitix[vapply(splitix, length, FUN.VALUE=numeric(1)) > 0] + mcres <- parallel::mclapply(seq_along(drugn), function(x, drugn, expr, drugpheno, type, batch, standardize, nthread, modeling.method, inference.method, req_alpha) { + res <- NULL + for (i in drugn[x]) { + ## using a linear model (x ~ concentration + cell + batch) + dd <- lapply(drugpheno, function(x) x[, i]) + dd <- do.call(cbind, dd) + colnames(dd) <- seq_len(ncol(dd)) + if (!is.na(sensitivity.cutoff)) { + dd <- factor(ifelse(dd > sensitivity.cutoff, 1, 0), levels = c(0, 1)) + } + rr <- rankGeneDrugSensitivity(data = expr, drugpheno = dd, type = type, batch = batch, single.type = FALSE, standardize = standardize, nthread = nthread, verbose = verbose, modeling.method = modeling.method, inference.method = inference.method, req_alpha) + res <- c(res, list(rr$all)) + } + names(res) <- drugn[x] + return(res) + }, + drugn = drugn, expr = t(molecularProfiles(object, mDataType)[features, molcellx, drop = FALSE]), + drugpheno = drugpheno.all, type = type, batch = batch, nthread = nthread_gene, standardize = standardize, + modeling.method = modeling.method, inference.method = inference.method, + req_alpha = req_alpha, mc.cores = nthread_drug, mc.preschedule = FALSE + ) + + res <- do.call(c, mcres) + res <- res[!vapply(res, is.null, FUN.VALUE = logical(1))] + drug.sensitivity <- array(NA, + dim = c( + nrow(featureInfo(object, mDataType)[features, , drop = FALSE]), + length(res), ncol(res[[1]]) + ), + dimnames = list(rownames(featureInfo(object, mDataType)[features, , drop = FALSE]), names(res), colnames(res[[1]])) + ) + for (j in seq_len(ncol(res[[1]]))) { + ttt <- vapply(res, function(x, j, k) { + xx <- array(NA, dim = length(k), dimnames = list(k)) + xx[rownames(x)] <- x[, j, drop = FALSE] + return(xx) + }, + j = j, + k = rownames(featureInfo(object, mDataType)[features, , drop = FALSE]), + FUN.VALUE = numeric(dim(drug.sensitivity)[1]) + ) + drug.sensitivity[rownames(featureInfo(object, mDataType)[features, , drop = FALSE]), names(res), j] <- ttt + } + + drug.sensitivity <- PharmacoSig(drug.sensitivity, + PSetName = name(object), + Call = as.character(match.call()), + SigType = ""Sensitivity"", + Arguments = list( + ""mDataType"" = mDataType, + ""drugs"" = drugs, + ""features"" = features, + ""cells"" = cells, + ""tissues"" = tissues, + ""sensitivity.measure"" = sensitivity.measure, + ""molecular.summary.stat"" = molecular.summary.stat, + ""sensitivity.summary.stat"" = sensitivity.summary.stat, + ""returnValues"" = returnValues, + ""sensitivity.cutoff"" = sensitivity.cutoff, + ""standardize"" = standardize, + ""molecular.cutoff"" = molecular.cutoff, + ""molecular.cutoff.direction"" = molecular.cutoff.direction, + ""nthread"" = nthread, + ""verbose"" = verbose + ) + ) + + return(drug.sensitivity) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/methods-[.R",".R","759","24","# ==== PharmacoSet Class +#'`[` +#' +#' @examples +#' data(CCLEsmall) +#' CCLEsmall[""WM1799"", ""Sorafenib""] +#' +#' @param x object +#' @param i Cell lines to keep in object +#' @param j Drugs to keep in object +#' @param ... further arguments +#' @param drop A boolean flag of whether to drop single dimensions or not +#' +#'@return Returns the subsetted object +#' +#' @export +setMethod(`[`, 'PharmacoSet', function(x, i, j, ..., drop = FALSE){ + if(is.character(i)&&is.character(j)){ + return(subsetTo(x, cells=i, drugs=j, molecular.data.cells=i)) + } + else if(is.numeric(i) && is.numeric(j) && all(as.integer(i)==i) && all(as.integer(j)==j)){ + return(subsetTo(x, cells=sampleNames(x)[i], drugs=treatmentNames(x)[j], molecular.data.cells=sampleNames(x)[i])) + } +})","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/matthewCor.R",".R","209","9","## Matthews correlatipon coefficient +#' Compute a Mathews Correlation Coefficient +#' +#' @inherit CoreGx::mcc +#' +#' @export +mcc <- function(x, y, nperm=1000, nthread=1) { + CoreGx::mcc(x, y, nperm, nthread) +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeIC50.R",".R","817","24","#' @describeIn computeICn Returns the IC50 of a Drug Dose response curve +#' +#' @return `numeric(1)` The ICn of the Hill curve over the specified dose +#' range. +#' +#' @export +computeIC50 <- function(concentration, + viability, + Hill_fit, + conc_as_log = FALSE, + viability_as_pct = TRUE, + verbose = TRUE, + trunc = TRUE) { + + return(computeICn(concentration = concentration, + viability = viability, + Hill_fit = Hill_fit, + n = ifelse(viability_as_pct, 50, .5), + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + verbose=TRUE, + trunc=TRUE)) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/zzz.R",".R","2182","34",".onLoad <- function(libname, pkgname) { + options(PharmacoGx_useC = TRUE) # setting default option for using c code across package + +} +# Package Start-up Functions + +.onAttach <- function(libname, pkgname) { + + if (interactive() && is.null(options('bhklab.startup_'))) { + oldOpts <- options() + options(warn=-1) + on.exit(options(oldOpts)) + + packageStartupMessage( + "" +PharmacoGx package brought to you by: + +\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 +\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u255d\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 +\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d +\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 +\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d +\u255a\u2550\u2550\u2550\u2550\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u255d + +For more of our work visit bhklab.ca! + +Like PharmacoGx? Check out our companion web-app at PharmacoDB.ca. + "" + ) + # Prevent repeated messages when loading multiple lab packages + options(bhklab.startup_=FALSE) + } +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/updateObject-methods.R",".R","776","24","#' Update the PharmacoSet class after changes in it struture or API +#' +#' @param object A `PharmacoSet` object to update the class structure for. +#' +#' @return `PharmacoSet` with update class structure. +#' +#' @examples +#' data(GDSCsmall) +#' updateObject(GDSCsmall) +#' +#' @md +#' @importMethodsFrom CoreGx updateObject +#' @export +setMethod(""updateObject"", signature(""PharmacoSet""), function(object) { + cSet <- callNextMethod(object) + pSet <- as(cSet, ""PharmacoSet"") + names(curation(pSet)) <- gsub(""drug"", ""treatment"", names(curation(pSet))) + if (""treatment"" %in% names(curation(pSet))) { + colnames(curation(pSet)$treatment) <- gsub(""treatmentid"", ""treatmentid"", + colnames(curation(pSet)$treatment)) + } + validObject(pSet) + return(pSet) +})","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/methods-summarizeSensitivityProfiles.R",".R","9442","225","#' Takes the sensitivity data from a PharmacoSet, and summarises them into a +#' drug vs cell line table +#' +#' This function creates a table with cell lines as rows and drugs as columns, +#' summarising the drug senstitivity data of a PharmacoSet into drug-cell line +#' pairs +#' +#' @examples +#' data(GDSCsmall) +#' GDSCauc <- summarizeSensitivityProfiles(GDSCsmall, +#' sensitivity.measure='auc_published') +#' +#' @param object [PharmacoSet] The PharmacoSet from which to extract the data +#' @param sensitivity.measure [character] The sensitivity measure to use. Use the sensitivityMeasures function to find out what measures are available for each object. +#' @param cell.lines [character] The cell lines to be summarized. If any cell lines have no data, they will be filled with missing values. +#' @param profiles_assay [character] The name of the assay in the PharmacoSet object that contains the sensitivity profiles. +#' @param treatment_col [character] The name of the column in the profiles assay that contains the treatment IDs. +#' @param sample_col [character] The name of the column in the profiles assay that contains the sample IDs. +#' @param drugs [character] The drugs to be summarized. If any drugs have no data, they will be filled with missing values. +#' @param summary.stat [character] The summary method to use if there are repeated cell line-drug experiments. Choices are ""mean"", ""median"", ""first"", ""last"", ""max"", or ""min"". +#' @param fill.missing Should the missing cell lines not in the molecular data object be filled in with missing values? +#' @param verbose Should the function print progress messages? +#' +#' @return [matrix] A matrix with cell lines going down the rows, drugs across the columns, with the selected sensitivity statistic for each pair. +#' +#' @importMethodsFrom CoreGx summarizeSensitivityProfiles +#' @export +setMethod(""summarizeSensitivityProfiles"", signature(object=""PharmacoSet""), + function( + object, + sensitivity.measure=""auc_recomputed"", + cell.lines, + profiles_assay = ""profiles"", + treatment_col = ""treatmentid"", + sample_col = ""sampleid"", + drugs, + summary.stat=c(""mean"", ""median"", ""first"", ""last"", ""max"", ""min""), + fill.missing=TRUE, + verbose=TRUE + ) { + if (is(treatmentResponse(object), 'LongTable')) + .summarizeSensProfiles(object, sensitivity.measure, profiles_assay = profiles_assay, + treatment_col, sample_col, cell.lines, drugs, summary.stat, fill.missing) + else + .summarizeSensitivityProfilesPharmacoSet(object, + sensitivity.measure, cell.lines, drugs, summary.stat, + fill.missing, verbose) +}) + +#' Summarize the sensitivity profiles when the sensitivity slot is a LongTable +#' +#' @return [matrix] A matrix with cell lines going down the rows, drugs across +#' the columns, with the selected sensitivity statistic for each pair. +#' +#' @import data.table +#' @keywords internal +.summarizeSensProfiles <- function(object, + sensitivity.measure='auc_recomputed', profiles_assay = ""profiles"", + treatment_col = ""treatmentid"", sample_col = ""sampleid"", cell.lines, drugs, summary.stat, + fill.missing=TRUE) { + + # handle missing + if (missing(cell.lines)) cell.lines <- sampleNames(object) + if (missing(drugs)) drugs <- treatmentNames(object) + if (missing(summary.stat) || length(summary.stat)>1) summary.stat <- 'mean' + + checkmate::assert_class(treatmentResponse(object), 'LongTable') + checkmate::assert_string(sensitivity.measure) + checkmate::assert_string(profiles_assay) + # get LongTable object + longTable <- treatmentResponse(object) + + checkmate::assert((profiles_assay %in% names(longTable)), + msg = paste0(""[PharmacoGx::summarizeSensivitiyProfiles,LongTable-method] "", + ""The assay '"", profiles_assay, ""' is not in the LongTable object."")) + + # extract the sensitivty profiles + sensProfiles <- assay(longTable, profiles_assay, withDimnames=TRUE, key=FALSE) + profileOpts <- setdiff(colnames(sensProfiles), idCols(longTable)) + + # compute max concentration and add it to the profiles + if (sensitivity.measure == 'max.conc') { + dose <- copy(assay(longTable, 'dose', withDimnames=TRUE, key=FALSE)) + dose[, max.conc := max(.SD, na.rm=TRUE), + .SDcols=grep('dose\\d+id', colnames(dose))] + dose <- dose[, .SD, .SDcols=!grepl('dose\\d+id', colnames(dose))] + sensProfiles <- dose[sensProfiles, on=idCols(longTable)] + } + + # deal with drug combo methods + if (sensitivity.measure == 'Synergy_score') + drugs <- grep('///', drugs, value=TRUE) + + # ensure selected measure is an option + if (!(sensitivity.measure %in% profileOpts)) + stop(.errorMsg('[PharmacoGx::summarizeSensivitiyProfiles,LongTable-method] ', + 'there is no measure ', sensitivity.measure, ' in this PharmacoSet.', + ' Please select one of: ', .collapse(profileOpts))) + + # match summary function + ## TODO:: extend this function to support passing in a custom summary function + summary.function <- function(x) { + if (all(is.na(x))) { + return(NA_real_) + } + switch(summary.stat, + ""mean"" = { mean(as.numeric(x), na.rm=TRUE) }, + ""median"" = { median(as.numeric(x), na.rm=TRUE) }, + ""first"" = { as.numeric(x)[[1]] }, + ""last"" = { as.numeric(x)[[length(x)]] }, + ""max""= { max(as.numeric(x), na.rm=TRUE) }, + ""min"" = { min(as.numeric(x), na.rm=TRUE)} + ) + } + sensProfiles <- data.table::as.data.table(sensProfiles) + + # do the summary + profSummary <- sensProfiles[, summary.function(get(sensitivity.measure)), + by=c(treatment_col, sample_col)] + + print(profSummary) + + # NA pad the missing cells and drugs + if (fill.missing) { + allCombos <- data.table(expand.grid(drugs, cell.lines)) + colnames(allCombos) <- c(treatment_col, sample_col) + profSummary <- profSummary[allCombos, on=c(treatment_col, sample_col)] + print(profSummary) + } + + # reshape and convert to matrix + setorderv(profSummary, c(sample_col, treatment_col)) + profSummary <- dcast(profSummary, get(treatment_col) ~ get(sample_col), value.var='V1') + summaryMatrix <- as.matrix(profSummary, rownames='treatment_col') + return(summaryMatrix) + +} + + + +#' @importFrom utils setTxtProgressBar txtProgressBar +#' @importFrom stats median +#' @importFrom reshape2 acast +#' @keywords internal +.summarizeSensitivityProfilesPharmacoSet <- function(object, + sensitivity.measure=""aac_recomputed"", + cell.lines, + drugs, + summary.stat=c(""mean"", ""median"", ""first"", ""last"", ""max"", ""min""), + fill.missing=TRUE, verbose=TRUE) { + + summary.stat <- match.arg(summary.stat) + #sensitivity.measure <- match.arg(sensitivity.measure) + if (!(sensitivity.measure %in% c(colnames(sensitivityProfiles(object)), ""max.conc""))) { + stop (sprintf(""Invalid sensitivity measure for %s, choose among: %s"", annotation(object)$name, paste(colnames(sensitivityProfiles(object)), collapse="", ""))) + } + if (missing(cell.lines)) { + cell.lines <- sampleNames(object) + } + if (missing(drugs)) { + if (sensitivity.measure != ""Synergy_score"") + { + drugs <- treatmentNames(object) + }else{ + drugs <- sensitivityInfo(object)[grep(""///"", sensitivityInfo(object)$treatmentid), ""treatmentid""] + } + } + + pp <- sensitivityInfo(object) + ppRows <- which(pp$sampleid %in% cell.lines & pp$treatmentid %in% drugs) ### NEEDED to deal with duplicated rownames!!!!!!! + if(sensitivity.measure != ""max.conc"") { + dd <- sensitivityProfiles(object) + } else { + + if(!""max.conc"" %in% colnames(sensitivityInfo(object))) { + + object <- updateMaxConc(object) + + } + dd <- sensitivityInfo(object) + + } + + result <- matrix(NA_real_, nrow=length(drugs), ncol=length(cell.lines)) + rownames(result) <- drugs + colnames(result) <- cell.lines + + if(is.factor(dd[, sensitivity.measure]) | is.character(dd[, sensitivity.measure])){ + warning(""Sensitivity measure is stored as a factor or character in the pSet. This is incorrect.\n + Please correct this and/or file an issue. Fixing in the call of this function."") + dd[, sensitivity.measure] <- as.numeric(as.character(dd[, sensitivity.measure])) + } + + pp_dd <- cbind(pp[,c(""sampleid"", ""treatmentid"")], ""sensitivity.measure""=dd[, sensitivity.measure]) + + + summary.function <- function(x) { + if(all(is.na(x))){ + return(NA_real_) + } + switch(summary.stat, + ""mean"" = { mean(as.numeric(x), na.rm=TRUE) }, + ""median"" = { median(as.numeric(x), na.rm=TRUE) }, + ""first"" = { as.numeric(x)[[1]] }, + ""last"" = { as.numeric(x)[[length(x)]] }, + ""max""= { max(as.numeric(x), na.rm=TRUE) }, + ""min"" = { min(as.numeric(x), na.rm=TRUE)} + ) + } + + pp_dd <- pp_dd[pp_dd[,""sampleid""] %in% cell.lines & pp_dd[,""treatmentid""]%in%drugs,] + + tt <- reshape2::acast(pp_dd, treatmentid ~ sampleid, fun.aggregate=summary.function, value.var=""sensitivity.measure"") + + result[rownames(tt), colnames(tt)] <- tt + + if (!fill.missing) { + + myRows <- apply(result, 1, function(x) !all(is.na(x))) + myCols <- apply(result, 2, function(x) !all(is.na(x))) + result <- result[myRows, myCols] + } + return(result) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/PharmacoSet-accessors.R",".R","17756","639","## Navigating this file: +## - Slot section names start with ---- +## - Method section names start with == +## +## As a result, you can use Ctrl + f to find the slot or method you are looking +## for quickly, assuming you know its name. +## +## For example Ctrl + f '== molecularProfiles' would take you the molecularProfiles +## method, while Ctrl +f '---- molecularProfiles' would take you to the slot +## section. + +#' @include PharmacoSet-class.R +NULL + +## Variables for dynamic inheritted roxygen2 docs + +.local_class <- 'PharmacoSet' +.local_data <- 'CCLEsmall' + +#### CoreGx inherited methods +#### +#### Note: The raw documentation lives in CoreGx, see the functions called +#### in @eval tags for the content of the metaprogrammed roxygen2 docs. +#### +#### See .parseToRoxygen method in utils-messages.R file of CoreGx to +#### create similar metaprogrammed docs. +#### +#### Warning: for dynamic docs to work, you must set +#### Roxygen: list(markdown = TRUE, r6=FALSE) +#### in the DESCRPTION file! + + +#' @title .parseToRoxygen +#' +#' @description +#' Helper for metaprogramming roxygen2 documentation +#' +#' @details +#' Takes a string block of roxygen2 tags sepearated by new-line +#' characteres and parses it to the appropriate format for the @eval tag, +#' subtituting any string in { } for the argument of the same name in `...`. +#' +#' @keywords internal +#' @importFrom CoreGx .parseToRoxygen +#' @export +#' @noRd +.parseToRoxygen <- function(string, ...) { + CoreGx::.parseToRoxygen(string, ...) +} + + +# ======================================= +# Accessor Method Documentation Object +# --------------------------------------- + + +#' @name PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_accessors(class_=.local_class) +#' @eval .parseToRoxygen( +#' ""@examples data({data_}) +#' "", data_=.local_data) +#' @importFrom methods callNextMethod +NULL + + +# ====================================== +# Accessor Methods +# -------------------------------------- + + +## ============== +## ---- drug slot +## -------------- + + +## +## == drugInfo + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_treatmentInfo(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx treatmentInfo +#' @aliases drugInfo +#' @export +drugInfo <- function(...) treatmentInfo(...) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_treatmentInfo(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx treatmentInfo<- +#' @aliases drugInfo<- +#' @export +`drugInfo<-` <- function(..., value) `treatmentInfo<-`(..., value=value) + + + +## +## == drugNames + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_treatmentNames(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx treatmentNames +#' @aliases drugNames +#' @export +drugNames <- function(...) treatmentNames(...) + + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_treatmentNames(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx treatmentNames<- +#' @aliases drugNames<- +#' @export +`drugNames<-` <- function(..., value) `treatmentNames<-`(..., value=value) + + + + +## ==================== +## ---- annotation slot +## -------------------- + + +## +## == annotation + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_annotation(class_=.local_class, data_=.local_data) +#' @importMethodsFrom CoreGx annotation +#' @export +setMethod('annotation', signature(""PharmacoSet""), function(object) { + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_annotation(class_=.local_class, data_=.local_data) +#' @importMethodsFrom CoreGx annotation<- +#' @export +setReplaceMethod(""annotation"", signature(""PharmacoSet"", ""list""), + function(object, value) { + callNextMethod(object=object, value=value) +}) + + +## +## == dateCreated + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_dateCreated(class_=.local_class, data_=.local_data) +#' @importMethodsFrom CoreGx dateCreated +#' @export +setMethod('dateCreated', signature(""PharmacoSet""), function(object) { + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_dateCreated(class_=.local_class, data_=.local_data) +#' @importMethodsFrom CoreGx dateCreated<- +#' @export +setReplaceMethod('dateCreated', signature(object=""PharmacoSet"", value=""character""), + function(object, value) { + callNextMethod(object=object, value=value) +}) + + +## +## === name + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_name(class_=.local_class, data_=.local_data) +#' @importMethodsFrom CoreGx name +setMethod('name', signature(""PharmacoSet""), function(object){ + callNextMethod(object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_name(class_=.local_class, data_=.local_data) +#' @importMethodsFrom CoreGx name<- +setReplaceMethod('name', signature(""PharmacoSet""), function(object, value){ + object <- callNextMethod(object, value=value) + return(invisible(object)) +}) + +## ============== +## ---- sample slot +## -------------- + + +## +## == sampleInfo + +.local_sample <- ""cell"" + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_sampleInfo(class_=.local_class, sample_=.local_sample) +#' @importFrom CoreGx sampleInfo +#' @export +setMethod(""sampleInfo"", ""PharmacoSet"", function(object) { + callNextMethod(object) +}) + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_sampleInfo(class_=.local_class, +#' data_=.local_data, sample_=""cell"") +#' @importFrom CoreGx sampleInfo<- +#' @export +setReplaceMethod(""sampleInfo"", signature(object=""PharmacoSet"", + value=""data.frame""), function(object, value) { + callNextMethod(object, value=value) +}) + + +## +## == sampleNames + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_sampleNames(class_=.local_class, +#' data_=.local_data, sample_=.local_sample) +#' @importMethodsFrom CoreGx sampleNames +setMethod(""sampleNames"", signature(""PharmacoSet""), function(object) { + callNextMethod(object) +}) + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_sampleNames(class_=.local_class, +#' data_=.local_data, sample_=.local_sample) +#' @importMethodsFrom CoreGx sampleNames<- +setReplaceMethod(""sampleNames"", signature(object=""PharmacoSet"", value=""character""), + function(object, value) { + callNextMethod(object=object, value=value) +}) + + + +## ------------------ +## ---- curation slot + + +## +## == curation + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_curation(class_=.local_class, +#' data_=.local_data, details_=""Contains three `data.frame`s, 'cell' with +#' cell-line ids and 'tissue' with tissue ids and 'drug' with drug ids."") +#' @importMethodsFrom CoreGx curation +setMethod('curation', signature(object=""PharmacoSet""), function(object) { + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_curation(class_=.local_class, +#' data_=.local_data, details_=""For a `PharmacoSet` object the slot should +#' contain tissue, cell-line and drug id `data.frame`s."") +#' @importMethodsFrom CoreGx curation<- +setReplaceMethod(""curation"", signature(object=""PharmacoSet"", value=""list""), + function(object, value) +{ + callNextMethod(object=object, value=value) +}) + + +## ---------------------- +## ---- datasetType slot + + +# +# == datasetType + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_datasetType(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx datasetType +setMethod(""datasetType"", signature(""PharmacoSet""), function(object) { + callNextMethod(object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_datasetType(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx datasetType<- +setReplaceMethod(""datasetType"", signature(object=""PharmacoSet"", + value='character'), function(object, value) +{ + callNextMethod(object=object, value=value) +}) + + +## --------------------------- +## ---- molecularProfiles slot + + +## +## == molecularProfiles + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_molecularProfiles(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx molecularProfiles +setMethod(molecularProfiles, ""PharmacoSet"", function(object, mDataType, assay) +{ + callNextMethod() +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_molecularProfiles(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx molecularProfiles<- +setReplaceMethod(""molecularProfiles"", signature(object=""PharmacoSet"", + mDataType =""character"", assay=""character"", value=""matrix""), + function(object, mDataType, assay, value) +{ + callNextMethod(object=object, mDataType=mDataType, assay=assay, value=value) +}) +setReplaceMethod(""molecularProfiles"", + signature(object=""PharmacoSet"", mDataType =""character"", assay=""missing"", + value=""matrix""), function(object, mDataType, assay, value) +{ + callNextMethod(object=object, mDataType=mDataType, assay=assay, value=value) +}) + + +## +## == featureInfo + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_featureInfo(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx featureInfo +setMethod(featureInfo, ""PharmacoSet"", function(object, mDataType) { + callNextMethod(object=object, mDataType=mDataType) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_featureInfo(class_=.local_class, +#' data_=.local_data, mDataType_='rna') +#' @importMethodsFrom CoreGx featureInfo<- +setReplaceMethod(""featureInfo"", signature(object=""PharmacoSet"", + mDataType =""character"",value=""data.frame""), + function(object, mDataType, value) +{ + callNextMethod(object=object, mDataType=mDataType, value=value) +}) +setReplaceMethod(""featureInfo"", signature(object=""PharmacoSet"", + mDataType =""character"",value=""DataFrame""), + function(object, mDataType, value) +{ + callNextMethod(object=object, mDataType=mDataType, value=value) +}) + + + +## +## == phenoInfo + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_phenoInfo(class_=.local_class, +#' data_=.local_data, mDataType_='rna') +#' @importMethodsFrom CoreGx phenoInfo +setMethod('phenoInfo', signature(object='PharmacoSet', mDataType='character'), + function(object, mDataType) +{ + callNextMethod(object=object, mDataType=mDataType) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_phenoInfo(class_=.local_class, +#' data_=.local_data, mDataType_='rna') +#' @importMethodsFrom CoreGx phenoInfo<- +setReplaceMethod(""phenoInfo"", signature(object=""PharmacoSet"", + mDataType =""character"", value=""data.frame""), + function(object, mDataType, value) +{ + callNextMethod(object=object, mDataType=mDataType, value=value) +}) +setReplaceMethod(""phenoInfo"", signature(object=""PharmacoSet"", + mDataType =""character"", value=""DataFrame""), + function(object, mDataType, value) +{ + callNextMethod(object=object, mDataType=mDataType, value=value) +}) + + +## +## == fNames + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_fNames(class_=.local_class, +#' data_=.local_data, mDataType_='rna') +#' @importMethodsFrom CoreGx fNames +setMethod('fNames', signature(object='PharmacoSet', mDataType='character'), + function(object, mDataType) +{ + callNextMethod(object=object, mDataType=mDataType) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_fNames(class_=.local_class, +#' data_=.local_data, mDataType_='rna') +#' @importMethodsFrom CoreGx fNames<- +setReplaceMethod('fNames', signature(object='PharmacoSet', mDataType='character', + value='character'), function(object, mDataType, value) +{ + callNextMethod(object=object, mDataType=mDataType, value=value) +}) + + +## +## == mDataNames + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_mDataNames(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx mDataNames +setMethod(""mDataNames"", ""PharmacoSet"", function(object){ + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_mDataNames(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx mDataNames<- +setReplaceMethod(""mDataNames"", ""PharmacoSet"", function(object, value){ + callNextMethod(object=object, value=value) +}) + + + +## +## == molecularProfilesSlot + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_molecularProfilesSlot(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx molecularProfilesSlot +setMethod(""molecularProfilesSlot"", signature(""PharmacoSet""), function(object) { + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_molecularProfilesSlot(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx molecularProfilesSlot<- +setReplaceMethod(""molecularProfilesSlot"", signature(""PharmacoSet"", ""list_OR_MAE""), + function(object, value) +{ + callNextMethod(object=object, value=value) +}) + + +# --------------------- +## ---- sensitivity slot + + +## +## == sensitivityInfo + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_sensitivityInfo(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx sensitivityInfo +setMethod('sensitivityInfo', signature(""PharmacoSet""), + function(object, dimension, ...) +{ + callNextMethod(object=object, dimension=dimension, ...) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_sensitivityInfo(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx sensitivityInfo<- +setReplaceMethod(""sensitivityInfo"", signature(object=""PharmacoSet"", + value=""data.frame""), function(object, dimension, ..., value) +{ + callNextMethod(object=object, dimension=dimension, ..., value=value) +}) + + +## +## == sensitvityMeasures + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_sensitivityMeasures(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx sensitivityMeasures +setMethod('sensitivityMeasures', signature(object=""PharmacoSet""), + function(object) +{ + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_sensitityMeasures(class_=.local_class, +#' data_=.local_data) +setReplaceMethod('sensitivityMeasures', + signature(object='PharmacoSet', value='character'), function(object, value) +{ + callNextMethod(object=object, value=value) +}) + + +## +## == sensitivityProfiles + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_sensitivityProfiles(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx sensitivityProfiles +setMethod('sensitivityProfiles', signature(object=""PharmacoSet""), function(object) +{ + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_sensitivityProfiles(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx sensitivityProfiles<- +setReplaceMethod(""sensitivityProfiles"", + signature(object=""PharmacoSet"", value=""data.frame""), + function(object, value) +{ + callNextMethod(object=object, value=value) +}) + + +# +# == sensitivityRaw + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_sensitivityRaw(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx sensitivityRaw +setMethod(""sensitivityRaw"", signature(""PharmacoSet""), function(object) { + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_sensitivityRaw(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx sensitivityRaw<- +setReplaceMethod('sensitivityRaw', signature(""PharmacoSet"", ""array""), + function(object, value) +{ + callNextMethod(object=object, value=value) +}) + +# +# == treatmentResponse + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_treatmentResponse(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx treatmentResponse +setMethod(""treatmentResponse"", signature(""PharmacoSet""), function(object) { + callNextMethod(object=object) +}) + + + +#' @rdname PharmacoSet-accessors +#' @importMethodsFrom CoreGx treatmentResponse<- +#' @eval CoreGx:::.docs_CoreSet_set_treatmentResponse(class_=.local_class, +#' data_=.local_data) +setReplaceMethod('treatmentResponse', signature(object='PharmacoSet', + value='list_OR_LongTable'), function(object, value) +{ + callNextMethod(object=object, value=value) +}) + + +## +## == sensNumber + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_sensNumber(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx sensNumber +setMethod('sensNumber', ""PharmacoSet"", function(object){ + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_sensNumber(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx sensNumber<- +setReplaceMethod('sensNumber', signature(object=""PharmacoSet"", value=""matrix""), + function(object, value) +{ + callNextMethod(object=object, value=value) +}) + + +## ====================== +## ---- perturbation slot + + +## +## == pertNumber + + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_get_pertNumber(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx pertNumber +setMethod('pertNumber', signature(object='PharmacoSet'), function(object) { + callNextMethod(object=object) +}) + +#' @rdname PharmacoSet-accessors +#' @eval CoreGx:::.docs_CoreSet_set_pertNumber(class_=.local_class, +#' data_=.local_data) +#' @importMethodsFrom CoreGx pertNumber<- +setReplaceMethod('pertNumber', signature(object='PharmacoSet', value=""array""), + function(object, value) +{ + callNextMethod(object=object, value=value) +})","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeDSS.R",".R","2982","90","##TODO:: Add function documentation +computeDSS <- function(concentration, + viability, + Hill_fit, + t_param = 10, + conc_as_log = FALSE, + viability_as_pct = TRUE, + trunc = TRUE, + verbose = TRUE, + dss_type = 3, + censor = FALSE + #, ... +) { + + if(missing(concentration)){ + stop(""The concentration values to integrate over must always be provided."") + } + if (missing(Hill_fit)) { + + Hill_fit <- logLogisticRegression(concentration, + viability, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + cleanData <- sanitizeInput(conc = concentration, + Hill_fit = Hill_fit, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + pars <- cleanData[[""Hill_fit""]] + concentration <- cleanData[[""log_conc""]] + + } else { + + cleanData <- sanitizeInput(conc = concentration, + viability = viability, + Hill_fit = Hill_fit, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) #is this coercing the concentration to log? + pars <- cleanData[[""Hill_fit""]] + concentration <- cleanData[[""log_conc""]] + + } + + if(pars[[3]] > max(concentration)) { + return(0) + } + + if(!viability_as_pct){ + t_param = t_param * 100 + pars[[2]] <- pars[[2]] * 100 + } + + x2 = max(concentration) + x1 = computeICn(concentration = concentration, Hill_fit = unlist(pars), n = t_param, conc_as_log = TRUE, viability_as_pct = TRUE) + if(!is.finite(x1)){return(0)} + + x1 <- max(x1, min(concentration)) + + if (censor) { + if (pars[[2]] > 50) { + return(NA) + } else if (all(concentration < pars[[3]])) { + return(0) + } + } + + AUC <- computeAUC(concentration = c(x1, x2), Hill_fit = unlist(pars), conc_as_log = TRUE, viability_as_pct = TRUE, verbose = verbose, trunc = trunc) + + + DSS <- (AUC * (x2 - x1) - t_param * (x2 - x1)) / ((100 - t_param) * (max(concentration) - min(concentration))) + if (dss_type == 1) { + return(DSS) + } + DSS <- DSS / log(100 - pars[[2]]) + if (dss_type == 2) { + return(DSS) + } + DSS <- DSS * (x2 - x1) / (max(concentration) - min(concentration)) + if (dss_type == 3) { + return(DSS) + } else { + stop(""Invalid DSS type entered."") + } +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeGR.R",".R","3771","115","#' @keywords internal +#' @noRd +grRegression <- function(conc, + viability, + duration, + Hill_fit, + dbl_time, + conc_as_log = FALSE, + viability_as_pct = TRUE, + verbose = FALSE, + density = c(2, 10, 2), + step = .5 / density, + precision = 0.05, + lower_bounds = c(0, 0, -6), + upper_bounds = c(4, 1, 6), + scale = 0.07, + family = c(""normal"", ""Cauchy""), + scale_01 = FALSE, + trunc=TRUE) { #If true, fits parameters to a transformed GR curve + #with image [0, 1]. If false, fits parameters to Sorger's original [-1, 1]-image curve. + + #GRFit takes in dose-response data and a bunch of formatting parameters, then returns + #the GHS, GEC_50, and G_inf values associated with them in accordance with the Sorger + #paper. However, the definitions are corrected in accordance with my adjustment of the + #relevant Sorger equations. While this may change the form of the equations, it does + #not affect their intuitive meanings. G_inf is still the GR in the presence of arbitrarily + #large drug concentration, GEC_50 is the dose that produces a half-minimal GR-value, + #and GHS is the magnitude of the slope of the tangent to the log dose-response curve + #when the drug concentration is GEC_50. + + #DO SANITY CHECKS ON INPUT + # if(missing(concentration)){ + + # stop(""The concentration values the drug was tested on must always be provided."") + family <- match.arg(family) + + +if (missing(Hill_fit)) { + + Hill_fit <- logLogisticRegression(conc, + viability, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose, + density = density, + step = step, + precision = precision, + lower_bounds = lower_bounds, + upper_bounds = upper_bounds, + scale = scale, + family = family + ) + cleanData <- sanitizeInput(conc=conc, + Hill_fit=Hill_fit, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + Hill_fit <- cleanData[[""Hill_fit""]] + log_conc <- cleanData[[""log_conc""]] +} else if (!missing(Hill_fit)){ + + cleanData <- sanitizeInput(conc = conc, + viability = viability, + Hill_fit = Hill_fit, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + Hill_fit <- cleanData[[""Hill_fit""]] + # log_conc <- cleanData[[""log_conc""]] +} + + if (missing(viability) && missing(Hill_fit)) { + stop(""Please enter viability data and/or Hill equation parameters."") + } + + if(missing(duration)){ + stop(""Cannot calculate GR without duration of experiment"") + } + if(missing(dbl_time)){ + stop(""Cannot calculate GR without cell doubling time"") + } + + tau <- duration / dbl_time + + #CALCULATE GR STATISTICS + + Ginf <- (Hill_fit[2]) ^ (1 / tau) + GEC50 <- 10 ^ Hill_fit[3] * ((2 ^ tau - (1 + Ginf) ^ tau) / ((1 + Ginf) ^ tau - (2 * Ginf) ^ tau)) ^ (1 / Hill_fit[1]) + GHS <- (1 - Hill_fit[2]) / tau * + (.Hill(log10(GEC50), Hill_fit)) ^ (1 / tau - 1) * + 1 / (1 + (GEC50 / 10 ^ Hill_fit[3]) ^ Hill_fit[1]) ^ 2 * Hill_fit[1] / 10 ^ Hill_fit[3] * + (GEC50 / 10 ^ Hill_fit[3]) ^ (Hill_fit[1] - 1) * GEC50 * log(10) + + #CONVERT OUTPUT TO CONFORM TO FORMATTING PARAMETERS + + if (scale_01 == FALSE) { + Ginf <- 2 * Ginf - 1 + GHS <- 2 * GHS + } + + if (viability_as_pct == TRUE) { + Ginf <- 100 * Ginf + GHS <- 100 * GHS + } + + if (conc_as_log == TRUE) { + GEC50 <- log10(GEC50) + } + + return(list(GHS = as.numeric(GHS), Ginf = as.numeric(Ginf), GEC50 = as.numeric(GEC50))) + +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/datasets.R",".R","2776","74"," #' Connectivity Map Example PharmacoSet +#' +#' A small example version of the Connectivity Map PharmacoSet, used in the +#' documentation examples. All credit for the data goes to the Connectivity Map +#' group at the Broad Institute. This is not a full version of the dataset, most of +#' of the dataset was removed to make runnable example code. For the full dataset, +#' please download using the downloadPSet function. +#' +#' @references +#' Lamb et al. The Connectivity Map: using gene-expression signatures to connect small molecules, genes, and disease. Science, 2006. +#' +#' @docType data +#' @name CMAPsmall +#' @usage data(CMAPsmall) +#' @keywords datasets +#' @format PharmacoSet object +#' +NULL + +#' Genomics of Drug Sensitivity in Cancer Example PharmacoSet +#' +#' A small example version of the Genomics of Drug Sensitivity in Cancer Project +#' PharmacoSet, used in the documentation examples. All credit for the data goes +#' to the Genomics of Drug Sensitivity in Cancer Project group at the Sanger.This is not a full version of the dataset, most of +#' of the dataset was removed to make runnable example code. For the full dataset, +#' please download using the downloadPSet function. +#' +#' @references +#' Garnett et al. Systematic identification of genomic markers of drug sensitivity in cancer cells. Nature, 2012. +#' +#' @docType data +#' @name GDSCsmall +#' @usage data(GDSCsmall) +#' @keywords datasets +#' @format PharmacoSet object +#' +NULL + +#' Cancer Cell Line Encyclopedia (CCLE) Example PharmacoSet +#' +#' A small example version of the CCLE PharmacoSet, used in the +#' documentation examples. All credit for the data goes to the CCLE +#' group at the Broad Institute. This is not a full version of the dataset, most of +#' of the dataset was removed to make runnable example code. For the full dataset, +#' please download using the downloadPSet function. +#' +#' @references +#' Barretina et al. The Cancer Cell Line Encyclopedia enables predictive modelling of anticancer drug sensitivity. Nature, 2012 +#' +#' @docType data +#' @name CCLEsmall +#' @usage data(CCLEsmall) +#' @keywords datasets +#' @format PharmacoSet object +#' +NULL + +#' HDAC Gene Signature +#' +#' A gene signature for HDAC inhibitors, as detailed by Glaser et al. The +#' signature is mapped from the probe to gene level using +#' \code{probeGeneMapping} +#' +#' @references +#' Glaser et al. Gene expression profiling of multiple histone deacetylase (HDAC) inhibitors: defining a common gene set produced by HDAC inhibition in T24 and MDA carcinoma cell lines. Molecular cancer therapeutics, 2003. +#' +#' @docType data +#' @name HDAC_genes +#' @usage data(HDAC_genes) +#' @keywords datasets +#' @format a 13x2 data.frame with gene identifiers in the first column and +#' direction change in the second +#' +NULL","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeAUC_old.R",".R","2082","49","# Return AUC (Area Under the drug response curve) for an experiment of a pSet by taking +# its concentration and viability as input. +# +# @param conc `numeric` A concentration range that the AUC should be computed for that range. +# Concentration range by default considered as not logarithmic scaled. +# @param viability `numeric` Viablities correspondant to the concentration range passed as first parameter. +# The range of viablity values by definition should be between 0 and 100. But the viabalities greater than +# 100 and lower than 0 are also accepted. +# @param trunc [binary] A flag that identify if the viabality values should be truncated to be in the +# range of (0,100) +# @param verbose `logical(1)` If 'TRUE' the function will retrun warnings and other infomrative messages. +# @import caTools +#' @keywords internal +#' @noRd +computeAUC_old <- function(conc, viability, + conc_as_log = FALSE, + viability_as_pct = TRUE, + trunc=TRUE, + verbose=TRUE, + area.type=c(""Fitted"",""Actual"")) { + cleanData <- sanitizeInput(conc, viability, + conc_as_log=conc_as_log, + viability_as_pct=viability_as_pct, + trunc=trunc, verbose=verbose) + log_conc <- cleanData[[""log_conc""]] + viability <- cleanData[[""viability""]] + +# ii <- which(concentration == 0) +# if(length(ii) > 0) { +# concentration <- concentration[-ii] +# viability <- viability[-ii] +# } + + if(missing(area.type)){ + area.type <- ""Fitted"" + } + if(length(conc) < 2){ + return(NA) + } + if(area.type == ""Actual""){ + # if(trunc) {viability = pmin(as.numeric(viability), 100); viability = pmax(as.numeric(viability), 0)} + trapezoid.integral <- caTools::trapz(log10(as.numeric(conc) + 1) ,as.numeric(viability)) + AUC <- round(1- (trapezoid.integral/trapz(log10(as.numeric(conc)), rep(100, length(viability)))), digits=2) + }else{ + AUC <- .computeAUCUnderFittedCurve(conc, viability, trunc) + } + return (AUC) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeICn.R",".R","3960","97","#' Computes the ICn for any n in 0-100 for a Drug Dose Viability Curve +#' +#' Returns the ICn for any given nth percentile when given concentration and viability as input, normalized by the concentration +#' range of the experiment. A Hill Slope is first fit to the data, and the ICn is inferred from the fitted curve. Alternatively, the parameters +#' of a Hill Slope returned by logLogisticRegression can be passed in if they already known. +#' +#' @examples +#' dose <- c(0.0025,0.008,0.025,0.08,0.25,0.8,2.53,8) +#' viability <- c(108.67,111,102.16,100.27,90,87,74,57) +#' computeIC50(dose, viability) +#' computeICn(dose, viability, n=10) +#' +#' @param concentration `numeric` is a vector of drug concentrations. +#' @param viability `numeric` is a vector whose entries are the viability values observed in the presence of the +#' drug concentrations whose logarithms are in the corresponding entries of conc, where viability 0 +#' indicates that all cells died, and viability 1 indicates that the drug had no effect on the cells. +#' @param Hill_fit `list` or `vector` In the order: c(""Hill Slope"", ""E_inf"", ""EC50""), the parameters of a Hill Slope +#' as returned by logLogisticRegression. If conc_as_log is set then the function assumes logEC50 is passed in, and if +#' viability_as_pct flag is set, it assumes E_inf is passed in as a percent. Otherwise, E_inf is assumed to be a decimal, +#' and EC50 as a concentration. +#' @param n `numeric` The percentile concentration to compute. If viability_as_pct set, assumed to be percentage, otherwise +#' assumed to be a decimal value. +#' @param conc_as_log `logical`, if true, assumes that log10-concentration data has been given rather than concentration data, +#' and that log10(ICn) should be returned instead of ICn. +#' @param viability_as_pct `logical`, if false, assumes that viability is given as a decimal rather +#' than a percentage, and that E_inf passed in as decimal. +#' @param trunc `logical`, if true, causes viability data to be truncated to lie between 0 and 1 before +#' curve-fitting is performed. +#' @param verbose `logical`, if true, causes warnings thrown by the function to be printed. +#' @return a numeric value for the concentration of the nth precentile viability reduction +#' @export +computeICn <- function(concentration, + viability, + Hill_fit, + n, + conc_as_log = FALSE, + viability_as_pct = TRUE, + verbose = TRUE, + trunc = TRUE) { + + if (missing(Hill_fit) & !missing(concentration) & !missing(viability)) { + + Hill_fit <- logLogisticRegression(conc = concentration, + viability, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + cleanData <- sanitizeInput(conc=concentration, + Hill_fit=Hill_fit, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + pars <- cleanData[[""Hill_fit""]] + concentration <- cleanData[[""log_conc""]] + } else if (!missing(Hill_fit)){ + + cleanData <- sanitizeInput(conc = concentration, + viability = viability, + Hill_fit = Hill_fit, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + pars <- cleanData[[""Hill_fit""]] + } else { + + stop(""Insufficient information to calculate ICn. Please enter concentration and viability or Hill parameters."") + + } + if(viability_as_pct){ + n <- n/100 + } + + + n <- 1 - n + + if (n < pars[2] || n > 1) { + return(NA_real_) + } else if (n == pars[2]) { + + return(Inf) + + } else if (n == 1) { + + return(ifelse(conc_as_log, -Inf, 0)) + + } else { + + return(ifelse(conc_as_log, + log10(10 ^ pars[3] * ((n - 1) / (pars[2] - n)) ^ (1 / pars[1])), + 10 ^ pars[3] * ((n - 1) / (pars[2] - n)) ^ (1 / pars[1]))) + + } + +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeDrugSensitivity.R",".R","12999","322","#' @importFrom BiocParallel bplapply +.calculateSensitivitiesStar <- function (pSets=list(), exps=NULL, cap=NA, + na.rm=TRUE, area.type=c(""Fitted"", ""Actual""), nthread=1) { + if (missing(area.type)) { + area.type <- ""Fitted"" + } + if (is.null(exps)) { + stop(""expriments is empty!"") + } + for (study in names(pSets)) { + sensitivityProfiles(pSets[[study]])$auc_recomputed_star <- NA + } + if (!is.na(cap)) { + trunc <- TRUE + }else{ + trunc <- FALSE + } + + for (i in seq_len(nrow(exps))) { + ranges <- list() + for (study in names(pSets)) { + ranges[[study]] <- as.numeric(sensitivityRaw(pSets[[study]])[ + exps[i, study], , ""Dose"" + ]) + } + ranges <- .getCommonConcentrationRange(ranges) + names(ranges) <- names(pSets) + for (study in names(pSets)) { + myx <- as.numeric(sensitivityRaw(pSets[[study]])[ + exps[i, study],,""Dose""]) %in% ranges[[study] + ] + sensitivityRaw(pSets[[study]])[exps[i, study], !myx, ] <- NA + } + } + + op <- options() + options(mc.cores=nthread) + on.exit(options(op)) + + for (study in names(pSets)) { + auc_recomputed_star <- unlist( + bplapply(rownames(sensitivityRaw(pSets[[study]])), + FUN=function(experiment, exps, study, dataset, area.type) { + if (!experiment %in% exps[,study]) return(NA_real_) + return(computeAUC( + concentration=as.numeric(dataset[experiment, , 1]), + viability=as.numeric(dataset[experiment, , 2]), + trunc=trunc, conc_as_log=FALSE, viability_as_pct=TRUE, + area.type=area.type + ) / 100 + ) + }, + exps=exps, study=study, dataset=sensitivityRaw(pSets[[study]]), + area.type=area.type) + ) + sensitivityProfiles(pSets[[study]])$auc_recomputed_star <- + auc_recomputed_star + } + return(pSets) +} + +## This function computes AUC for the whole raw sensitivity data of a pset +.calculateFromRaw <- function(raw.sensitivity, cap=NA, nthread=1, + family=c(""normal"", ""Cauchy""), scale=0.07, n=1) { + family <- match.arg(family) + + AUC <- vector(length=dim(raw.sensitivity)[1]) + names(AUC) <- dimnames(raw.sensitivity)[[1]] + + IC50 <- vector(length=dim(raw.sensitivity)[1]) + names(IC50) <- dimnames(raw.sensitivity)[[1]] + + trunc <- !is.na(cap) + + if (nthread == 1) { + pars <- lapply(names(AUC), + FUN=function(exp, raw.sensitivity, family, scale, n) { + if (length(grep(""///"", raw.sensitivity[exp, , ""Dose""])) > 0 || + all(is.na(raw.sensitivity[exp, , ""Dose""]))) { + NA + } else{ + logLogisticRegression(raw.sensitivity[exp, , ""Dose""], + raw.sensitivity[exp, , ""Viability""], trunc=trunc, + conc_as_log=FALSE, viability_as_pct=TRUE, family=family, + scale=scale, median_n=n) + } + }, + raw.sensitivity=raw.sensitivity, family=family, scale=scale, + n=n + ) + names(pars) <- dimnames(raw.sensitivity)[[1]] + AUC <- unlist(lapply(names(pars), + FUN=function(exp, raw.sensitivity, pars) { + if (any(is.na(pars[[exp]]))) { + NA + } else{ + computeAUC(concentration=raw.sensitivity[exp, , ""Dose""], + Hill_fit=pars[[exp]], trunc=trunc, conc_as_log=FALSE, + viability_as_pct=TRUE) + } + }, + raw.sensitivity=raw.sensitivity, pars=pars + )) + IC50 <- unlist(lapply(names(pars), function(exp, pars) { + if (any(is.na(pars[[exp]]))) { + NA + } else{ + computeIC50(Hill_fit=pars[[exp]], trunc=trunc, + conc_as_log=FALSE, viability_as_pct=TRUE) + } + }, pars=pars)) + } else { + pars <- parallel::mclapply(names(AUC), + FUN=function(exp, raw.sensitivity, family, scale, n, trunc) { + if (length(grep(""///"", raw.sensitivity[exp, , ""Dose""])) > 0 || + all(is.na(raw.sensitivity[exp, , ""Dose""]))) { + NA + } else { + logLogisticRegression( + raw.sensitivity[exp, , ""Dose""], + raw.sensitivity[exp, , ""Viability""], + trunc=trunc, conc_as_log=FALSE, viability_as_pct=TRUE, + family=family, scale=scale, median_n=n) + } + }, + raw.sensitivity=raw.sensitivity, family=family, scale=scale, n=n, + trunc=trunc, mc.cores=nthread + ) + names(pars) <- dimnames(raw.sensitivity)[[1]] + AUC <- unlist(parallel::mclapply(names(pars), + FUN=function(exp, raw.sensitivity, pars, trunc) { + if (any(is.na(pars[[exp]]))) { + NA + } else{ + computeAUC( + concentration=raw.sensitivity[exp, , ""Dose""], + Hill_fit=pars[[exp]], + trunc=trunc, conc_as_log=FALSE, viability_as_pct=TRUE) + } + }, + raw.sensitivity=raw.sensitivity, pars=pars, trunc=trunc, + mc.cores=nthread + )) + IC50 <- unlist(parallel::mclapply(names(pars), + FUN=function(exp, pars, trunc) { + if(any(is.na(pars[[exp]]))) { + NA + } else{ + computeIC50(Hill_fit=pars[[exp]], trunc=trunc, + conc_as_log=FALSE, viability_as_pct=TRUE) + } + }, pars=pars, trunc=trunc, mc.cores=nthread + )) + } + names(AUC) <- dimnames(raw.sensitivity)[[1]] + names(IC50) <- dimnames(raw.sensitivity)[[1]] + + return(list(""AUC""=AUC, ""IC50""=IC50, ""pars""=pars)) +} + + +## This function computes intersected concentration range between a list of +## concentration ranges +.getCommonConcentrationRange <- function(doses) { + min.dose <- 0 + max.dose <- 10^100 + for (i in seq_len(length(doses))) { + min.dose <- max(min.dose, min(as.numeric(doses[[i]]), na.rm=TRUE), + na.rm=TRUE) + max.dose <- min(max.dose, max(as.numeric(doses[[i]]), na.rm=TRUE), + na.rm=TRUE) + } + common.ranges <- list() + for (i in seq_len(length(doses))) { + common.ranges[[i]] <- doses[[i]][ + seq(which.min(abs(as.numeric(doses[[i]]) - min.dose)), max( + which(abs(as.numeric(doses[[i]]) - max.dose) == + min(abs(as.numeric(doses[[i]]) - max.dose), na.rm=TRUE) + )) + ) + ] + } + return(common.ranges) +} + +## predict viability from concentration data and curve parameters +.Hill <- function(x, pars) { + return(pars[2] + (1 - pars[2]) / (1 + (10 ^ x / 10 ^ pars[3]) ^ pars[1])) +} + +## calculate residual of fit +## FIXME:: Why is this different from CoreGx? +#' @importFrom CoreGx .dmedncauchys .dmednnormals .edmednnormals .edmedncauchys +.residual <- function(x, y, n, pars, scale=0.07, family=c(""normal"", ""Cauchy""), + trunc=FALSE) { + family <- match.arg(family) + Cauchy_flag=(family == ""Cauchy"") + if (Cauchy_flag == FALSE) { + # return(sum((.Hill(x, pars) - y) ^ 2)) + diffs <- .Hill(x, pars)-y + if (trunc == FALSE) { + return(sum(-log(.dmednnormals(diffs, n, scale)))) + } else { + down_truncated <- abs(y) >= 1 + up_truncated <- abs(y) <= 0 + + # For up truncated, integrate the cauchy dist up until - + #>because anything less gets truncated to 0, and thus the residual + #>is -diff, and the prob function becomes discrete For + #>down_truncated, 1-cdf(diffs)=cdf(-diffs) + return( + sum(-log(.dmednnormals(diffs[!(down_truncated | up_truncated)], + n, scale))) + + sum(-log(.edmednnormals(-diffs[up_truncated | down_truncated], + n, scale))) + ) + + } + } else { + diffs <- .Hill(x, pars) - y + if (trunc == FALSE) { + return(sum(-log(.dmedncauchys(diffs, n, scale)))) + } else { + down_truncated <- abs(y) >= 1 + up_truncated <- abs(y) <= 0 + # For up truncated, integrate the cauchy dist up until -diff because + #> anything less gets truncated to 0, and thus the residual is -diff, + #>and the prob function becomes discrete For down_truncated, + #>1 - cdf(diffs) = cdf(-diffs) + return( + sum(-log(.dmedncauchys(diffs[!(down_truncated | up_truncated)], + n, scale))) + + sum(-log(.edmedncauchys(-diffs[up_truncated | down_truncated], + n, scale)))) + } + } +} + +##FIXME:: Why is this different from CoreGx? +.meshEval <- function(log_conc, viability, lower_bounds=c(0, 0, -6), + upper_bounds=c(4, 1, 6), density=c(2, 10, 2), scale=0.07, n=1, + family=c(""normal"", ""Cauchy""), trunc=FALSE) { + family <- match.arg(family) + guess <- c(pmin(pmax(1, lower_bounds[1]), upper_bounds[1]), + pmin(pmax(min(viability), lower_bounds[2]), upper_bounds[2]), + pmin(pmax(log_conc[which.min(abs(viability - 1 / 2))], lower_bounds[3]), + upper_bounds[3])) + guess_residual <- .residual(log_conc, viability, pars=guess, n=n, + scale=scale, family=family, trunc=trunc) + for (i in seq(from=lower_bounds[1], to=upper_bounds[1], + by=1 / density[1])) { + for (j in seq(from=lower_bounds[2], to=upper_bounds[2], + by=1 / density[2])) { + for (k in seq(from=lower_bounds[3], to=upper_bounds[3], + by=1 / density[3])) { + test_guess_residual <- .residual(log_conc, viability, + pars=c(i, j, k), n=n, scale=scale, family=family, + trunc=trunc) + if (!is.finite(test_guess_residual)) { + warning(paste0("" Test Guess Residual is: "", + test_guess_residual, ""\n Other Pars: log_conc: "", + paste(log_conc, collapse="", ""), ""\n Viability: "", + paste(viability, collapse="", ""), ""\n Scale: "", scale, + ""\n Family: "", family, ""\n Trunc "", trunc, ""\n HS: "", + i, "", Einf: "", j, "", logEC50: "", k, ""\n n: "", n)) + } + if (!length(test_guess_residual)) { + warning(paste0("" Test Guess Residual is: "", + test_guess_residual, ""\n Other Pars: log_conc: "", + paste(log_conc, collapse="", ""), ""\n Viability: "", + paste(viability, collapse="", ""), ""\n Scale: "", scale, + ""\n Family: "", family, ""\n Trunc "", trunc, ""\n HS: "", i, + "", Einf: "", j, "", logEC50: "", k, ""\n n: "", n)) + } + if (test_guess_residual < guess_residual) { + guess <- c(i, j, k) + guess_residual <- test_guess_residual + } + } + } + } + return(guess) +} + +## FIXME:: Documentation? +# Fits dose-response curves to data given by the user +# and returns the AUC of the fitted curve, normalized to the length of the concentration range. +# +# @param concentration `numeric` is a vector of drug concentrations. +# +# @param viability `numeric` is a vector whose entries are the viability values observed in the presence of the +# drug concentrations whose logarithms are in the corresponding entries of the log_conc, expressed as percentages +# of viability in the absence of any drug. +# +# @param trunc `logical`, if true, causes viability data to be truncated to lie between 0 and 1 before +# curve-fitting is performed. +#' @importFrom CoreGx .getSupportVec +#' @export +#' @keywords internal +.computeAUCUnderFittedCurve <- function(concentration, viability, trunc=TRUE, + verbose=FALSE) { + log_conc <- concentration + #FIT CURVE AND CALCULATE IC50 + pars <- unlist(logLogisticRegression(log_conc, viability, + conc_as_log=TRUE, viability_as_pct=FALSE, trunc=trunc)) + x <- .getSupportVec(log_conc) + return(1 - trapz(x, .Hill(x, pars)) / + (log_conc[length(log_conc)] - log_conc[1])) +} + +#This function is being used in computeSlope +.optimizeRegression <- function(x, y, x0=-3, y0=100) { + beta1 <- (sum(x * y) - y0 * sum(x)) / (sum(x * x) - x0 * sum(x)) + return(beta1) +} + +updateMaxConc <- function(pSet) { + sensitivityInfo(pSet)$max.conc <- apply(sensitivityRaw(pSet)[, , ""Dose""], + 1, max, na.rm=TRUE) + return(pSet) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/GWC.R",".R","527","20","#' GWC Score +#' +#' @inherit CoreGx::gwc +#' +#' @examples +#' data(CCLEsmall) +#' x <- molecularProfiles(CCLEsmall,""rna"")[,1] +#' y <- molecularProfiles(CCLEsmall,""rna"")[,2] +#' x_p <- rep(0.05, times=length(x)) +#' y_p <- rep(0.05, times=length(y)) +#' names(x_p) <- names(x) +#' names(y_p) <- names(y) +#' gwc(x,x_p,y,y_p, nperm=100) +#' +#' @export +gwc <- +function (x1, p1, x2, p2, method.cor=c(""pearson"", ""spearman""), nperm=1e4, + truncate.p=1e-16, ...) { + CoreGx::gwc(x1, p1, x2, p2, method.cor, nperm, truncate.p, ...) +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/logLogisticRegression.R",".R","10212","222","#' Fits curves of the form E = E_inf + (1 - E_inf)/(1 + (c/EC50)^HS) to dose-response data points (c, E) given by the user +#' and returns a vector containing estimates for HS, E_inf, and EC50. +#' +#' By default, logLogisticRegression uses an L-BFGS algorithm to generate the fit. However, if +#' this fails to converge to solution, logLogisticRegression samples lattice points throughout the parameter space. +#' It then uses the lattice point with minimal least-squares residual as an initial guess for the optimal parameters, +#' passes this guess to drm, and re-attempts the optimization. If this still fails, logLogisticRegression uses the +#' PatternSearch algorithm to fit a log-logistic curve to the data. +#' +#' @examples +#' dose <- c(0.0025,0.008,0.025,0.08,0.25,0.8,2.53,8) +#' viability <- c(108.67,111,102.16,100.27,90,87,74,57) +#' computeAUC(dose, viability) +#' +#' @param conc `numeric` is a vector of drug concentrations. +#' @param viability `numeric` is a vector whose entries are the viability values observed in the presence of the +#' drug concentrations whose logarithms are in the corresponding entries of the log_conc, where viability 0 +#' indicates that all cells died, and viability 1 indicates that the drug had no effect on the cells. +#' @param density `numeric` is a vector of length 3 whose components are the numbers of lattice points per unit +#' length along the HS-, E_inf-, and base-10 logarithm of the EC50-dimensions of the parameter space, respectively. +#' @param step `numeric` is a vector of length 3 whose entries are the initial step sizes in the HS, E_inf, and +#' base-10 logarithm of the EC50 dimensions, respectively, for the PatternSearch algorithm. +#' @param precision is a positive real number such that when the ratio of current step size to initial step +#' size falls below it, the PatternSearch algorithm terminates. A smaller value will cause LogisticPatternSearch +#' to take longer to complete optimization, but will produce a more accurate estimate for the fitted parameters. +#' @param lower_bounds `numeric` is a vector of length 3 whose entries are the lower bounds on the HS, E_inf, +#' and base-10 logarithm of the EC50 parameters, respectively. +#' @param upper_bounds `numeric` is a vector of length 3 whose entries are the upper bounds on the HS, E_inf, +#' and base-10 logarithm of the EC50 parameters, respectively. +#' @param scale is a positive real number specifying the shape parameter of the Cauchy distribution. +#' @param family `character`, if ""cauchy"", uses MLE under an assumption of Cauchy-distributed errors +#' instead of sum-of-squared-residuals as the objective function for assessing goodness-of-fit of +#' dose-response curves to the data. Otherwise, if ""normal"", uses MLE with a gaussian assumption of errors +#' @param median_n If the viability points being fit were medians of measurements, they are expected to follow a median of \code{family} +#' distribution, which is in general quite different from the case of one measurement. Median_n is the number of measurements +#' the median was taken of. If the measurements are means of values, then both the Normal and the Cauchy distributions are stable, so means of +#' Cauchy or Normal distributed variables are still Cauchy and normal respectively. +#' @param conc_as_log `logical`, if true, assumes that log10-concentration data has been given rather than concentration data, +#' and that log10(EC50) should be returned instead of EC50. +#' @param viability_as_pct `logical`, if false, assumes that viability is given as a decimal rather +#' than a percentage, and that E_inf should be returned as a decimal rather than a percentage. +#' @param trunc `logical`, if true, causes viability data to be truncated to lie between 0 and 1 before +#' curve-fitting is performed. +#' @param verbose `logical`, if true, causes warnings thrown by the function to be printed. +#' @return A list containing estimates for HS, E_inf, and EC50. It is annotated with the attribute Rsquared, which is the R^2 of the fit. +#' Note that this is calculated using the values actually used for the fit, after truncation and any transform applied. With truncation, this will be +#' different from the R^2 compared to the variance of the raw data. This also means that if all points were truncated down or up, there is no variance +#' in the data, and the R^2 may be NaN. +#' +#' @export +#' +#' @importFrom CoreGx .meshEval .residual +#' @importFrom stats optim dcauchy dnorm pcauchy rcauchy rnorm pnorm integrate +logLogisticRegression <- function(conc, + viability, + density = c(2, 10, 5), + step = .5 / density, + precision = 1e-4, + lower_bounds = c(0, 0, -6), + upper_bounds = c(4, 1, 6), + scale = 0.07, + family = c(""normal"", ""Cauchy""), + median_n = 1, + conc_as_log = FALSE, + viability_as_pct = TRUE, + trunc = TRUE, + verbose = TRUE) { + # guess <- .logLogisticRegressionRaw(conc, viability, density , step, precision, lower_bounds, upper_bounds, scale, Cauchy_flag, conc_as_log, viability_as_pct, trunc, verbose) + + +# .logLogisticRegressionRaw <- function(conc, +# viability, +# density = c(2, 10, 2), +# step = .5 / density, +# precision = 0.05, +# lower_bounds = c(0, 0, -6), +# upper_bounds = c(4, 1, 6), +# scale = 0.07, +# Cauchy_flag = FALSE, +# conc_as_log = FALSE, +# viability_as_pct = TRUE, +# trunc = TRUE, +# verbose = FALSE) { + family <- match.arg(family) + + + if (prod(is.finite(step)) != 1) { + print(step) + stop(""Step vector contains elements which are not positive real numbers."") + } + + if (prod(is.finite(precision)) != 1) { + print(precision) + stop(""Precision value is not a real number."") + } + + if (prod(is.finite(lower_bounds)) != 1) { + print(lower_bounds) + stop(""Lower bounds vector contains elements which are not real numbers."") + } + + if (prod(is.finite(upper_bounds)) != 1) { + print(upper_bounds) + stop(""Upper bounds vector contains elements which are not real numbers."") + } + + if (prod(is.finite(density)) != 1) { + print(density) + stop(""Density vector contains elements which are not real numbers."") + } + + if (is.finite(scale) == FALSE) { + print(scale) + stop(""Scale is not a real number."") + } + + if (is.character(family) == FALSE) { + print(family) + stop(""Cauchy flag is not a string."") + } + + if (length(density) != 3){ + stop(""Density parameter needs to have length of 3, for HS, Einf, EC50"") + } + + if (!median_n==as.integer(median_n)){ + stop(""There can only be a integral number of samples to take a median of. Check your setting of median_n parameter, it is not an integer"") + } + + + if (min(upper_bounds - lower_bounds) < 0) { + print(rbind(lower_bounds, upper_bounds)) + stop(""Upper bounds on parameters do not exceed lower bounds."") + } + + + + if (min(density) <= 0) { + print(density) + stop(""Lattice point density vector contains negative values."") + } + + if (precision <= 0) { + print(precision) + stop(""Negative precision value."") + } + + if (min(step) <= 0) { + print(step) + stop(""Step vector contains nonpositive numbers."") + } + + if (scale <= 0) { + print(scale) + stop(""Scale parameter is a nonpositive number."") + } + + + + + + CoreGx::.sanitizeInput(x = conc, + y = viability, + x_as_log = conc_as_log, + y_as_log = FALSE, + y_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + + cleanData <- CoreGx::.reformatData(x = conc, + y = viability, + x_to_log = !conc_as_log, + y_to_log = FALSE, + y_to_frac = viability_as_pct, + trunc = trunc) + + if (!(all(lower_bounds < upper_bounds))) { + if (verbose == 2) { + message(""lower_bounds:"") + message(lower_bounds) + message(""upper_bounds:"") + message(upper_bounds) + } + stop (""All lower bounds must be less than the corresponding upper_bounds."") + } + + + log_conc <- cleanData[[""x""]] + viability <- cleanData[[""y""]] + + + #ATTEMPT TO REFINE GUESS WITH L-BFGS OPTIMIZATION + # tryCatch( + gritty_guess <- c(pmin(pmax(1, lower_bounds[1]), upper_bounds[1]), + pmin(pmax(min(viability), lower_bounds[2]), upper_bounds[2]), + pmin(pmax(log_conc[which.min(abs(viability - 1/2))], lower_bounds[3]), upper_bounds[3])) + + + guess <- CoreGx::.fitCurve(x = log_conc, + y = viability, + f = PharmacoGx:::.Hill, + density = density, + step = step, + precision = precision, + lower_bounds = lower_bounds, + upper_bounds = upper_bounds, + scale = scale, + family = family, + median_n = median_n, + trunc = trunc, + verbose = verbose, + gritty_guess = gritty_guess, + span = 1) + + returnval <- list(""HS"" = guess[1], + ""E_inf"" = ifelse(viability_as_pct, 100 * guess[2], guess[2]), + ""EC50"" = ifelse(conc_as_log, guess[3], 10 ^ guess[3])) + attr(returnval, ""Rsquare"") <- attr(guess, ""Rsquare"") + + return(returnval) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeSynergy.R",".R","57779","1428","# ==== Loewe Additivity + +#' @title Inverse function of Hill equation +#' +#' @description +#' For the dose-response Hill equation of a drug defined by +#' \eqn{E(x) = E_{inf}+\frac{1-E_{inf}}{1+(\frac{x}{EC50})^(\frac{1}{HS})}}, +#' that computes the response in viability from a dose in micromole for a drug, +#' this function is the inverse function of the Hill curve that +#' computes the dose required to produce a given response: +#' \eqn{ +#' f^{-1}(E) = EC50 ( +#' \frac{1-E}{E-E_{inf}} )^{\frac{1}{HS}} +#' ) +#' } +#' +#' @param viability `numeric` is a vector whose entries are the viability values +#' in the range \[0, 1\] if `is_pct` is `FALSE` or \[0, 100\] if it is +#' `TRUE`. +#' @param EC50 `numeric` is a vector of relative EC50 for drug-response equation. +#' @param HS `numeric` Hill coefficient of the drug-response equation +#' that represents the sigmoidity of the curve. +#' @param E_inf `numeric` the maximum attanable effect of a drug +#' when it is administered with a infinitely high concentration. +#' @param is_pct `logical` whether both the input viabiliy and `E_inf` are given +#' in percentage (\[0, 100\]) rather than decimal (\[0, 1\]). Default FALSE. +#' +#' @return `numeric` concentrations in micromoles required to produce +#' `viability` in the corresponding entries. +#' +#' @examples +#' dose <- effectToDose(viability = 80, +#' EC50 = 42, +#' HS = 1, +#' E_inf = 10, +#' is_pct = TRUE) +#' +#' @importFrom checkmate assertLogical +#' @export +effectToDose <- function(viability, EC50, HS, E_inf, is_pct = FALSE) { + assertLogical(is_pct, len = 1) + if (is_pct) { + viability <- viability / 100 + E_inf <- E_inf / 100 + } + EC50 * ((1 - viability) / (viability - E_inf))^(1 / HS) +} + +#' @title Loewe Additive Combination Index (CI) +#' +#' @description +#' Computes the Loewe additive combination index (CI) from its definition +#' \eqn{ +#' CI = \frac{x_1}{f_1^{-1}(E)} + +#' \frac{x_2}{f_2^{-1}(E)} +#' } +#' +#' @param viability `numeric` is a vector whose entries are the viability values +#' in the range \[0, 1\]. +#' @param treatment1dose `numeric` a vector of concentrations for treatment 1 +#' @param HS_1 `numeric` Hill coefficient of treatment 1 +#' @param E_inf_1 `numeric` the maximum attainable effect of treatment 1. +#' @param EC50_1 `numeric` relative EC50 of treatment 1. +#' @param treatment2dose `numeric` a vector of concentrations for treatment 2 +#' @param HS_2 `numeric` Hill coefficient of treatment 2 +#' @param E_inf_2 `numeric` the maximum attainable effect of treatment 2. +#' @param EC50_2 `numeric` relative EC50 of treatment 2. +#' @param is_pct `logical` whether both the input viabiliy and E_inf are given +#' in percentage (\[0, 100\]) rather than decimal (\[0, 1\]). Default FALSE. +#' +#' @return CI under Loewe additive definition +#' +#' @examples +#' \dontrun{ +#' tre |> +#' endoaggregate( +#' assay=""combo_viability"", +#' Loewe = PharmacoGx::computeLoewe( +#' treatment1dose = treatment1dose, +#' treatment2dose = treatment2dose, +#' HS_1 = HS_1, +#' HS_2 = HS_2, +#' E_inf_1 = E_inf_1, +#' E_inf_2 = E_inf_2, +#' EC50_1 = EC50_1, +#' EC50_2 = EC50_2 +#' ), +#' by = assayKeys(tre, ""combo_viability"") +#' ) -> tre +#' } +#' +#' @export +loeweCI <- function(viability, + treatment1dose, HS_1, E_inf_1, EC50_1, + treatment2dose, HS_2, E_inf_2, EC50_2, + is_pct = FALSE) { + (treatment1dose / effectToDose( + viability = viability, + EC50 = EC50_1, + HS = HS_1, + E_inf = E_inf_1, + is_pct = is_pct)) + + (treatment2dose / effectToDose( + viability = viability, + EC50 = EC50_2, + HS = HS_2, + E_inf = E_inf_2, + is_pct = is_pct)) +} + +## Objective function to mimimise for solving E_Loewe +#' @param viability `numeric` is a vector whose entries are the viability values +#' in the range [0, 1]. +#' @param treatment1dose `numeric` a vector of concentrations for treatment 1 +#' @param HS_1 `numeric` Hill coefficient of treatment 1 +#' @param E_inf_1 `numeric` the maximum attainable effect of treatment 1. +#' @param EC50_1 `numeric` relative EC50 of treatment 1. +#' @param treatment2dose `numeric` a vector of concentrations for treatment 2 +#' @param HS_2 `numeric` Hill coefficient of treatment 2 +#' @param E_inf_2 `numeric` the maximum attainable effect of treatment 2. +#' @param EC50_2 `numeric` relative EC50 of treatment 2. +#' +#' @return the distance between computed Loewe CI and 1 +#' +#' @noRd +.loeweLoss <- function(viability, + treatment1dose, HS_1, E_inf_1, EC50_1, + treatment2dose, HS_2, E_inf_2, EC50_2) { + abs( + loeweCI(viability = viability, + treatment1dose, HS_1, E_inf_1, EC50_1, + treatment2dose, HS_2, E_inf_2, EC50_2) - 1 + ) +} + +#' @title Computes Loewe Null References +#' +#' @description +#' Predict the response of a treatment combination under +#' the Loewe additive null assumption. +#' +#' @param treatment1dose `numeric` a vector of concentrations for treatment 1 +#' @param HS_1 `numeric` Hill coefficient of treatment 1 +#' @param E_inf_1 `numeric` viability produced by the maximum attainable effect of treatment 1. +#' @param EC50_1 `numeric` relative EC50 of treatment 1. +#' @param treatment2dose `numeric` a vector of concentrations for treatment 2 +#' @param HS_2 `numeric` Hill coefficient of treatment 2 +#' @param E_inf_2 `numeric` viability produced by the maximum attainable effect of treatment 2. +#' @param EC50_2 `numeric` relative EC50 of treatment 2. +#' @param tol `numeric` Error tolerance for deviations from Loewe assumption. Loewe predictions with error higher than `tol` will be returned as `NA`. Deafult 0.1. +#' @param lower_bound `numeric` Lowest possible value for Loewe expected viability. Default 0. +#' @param upper_bound `numeric` Highest possible value for Loewe expected viability. Default 1. +#' @param verbose `logical` whether to display warning messages. Default `FALSE`. +#' +#' @return `numeric` expected viability under Loewe additive null assumption. +#' +#' @export +#' +#' @examples +#' \dontrun{ +#' tre |> +#' endoaggregate( +#' assay=""combo_viability"", +#' Loewe = computeLoewe( +#' treatment1dose=treatment1dose, +#' treatment2dose=treatment2dose, +#' HS_1=HS_1, +#' HS_2=HS_2, +#' E_inf_1=E_inf_1, +#' E_inf_2=E_inf_2, +#' EC50_1=EC50_1, +#' EC50_2=EC50_2 +#' ), +#' by = assayKeys(tre, ""combo_viability"") +#' ) -> tre +#' } +#' +#' @importFrom stats optimise +#' @importFrom checkmate assertNumeric assertLogical +computeLoewe <- function(treatment1dose, HS_1, E_inf_1, EC50_1, + treatment2dose, HS_2, E_inf_2, EC50_2, + tol = 0.1, lower_bound = 0, upper_bound = 1, + verbose = FALSE) { + + len <- length(treatment1dose) + assertNumeric(treatment1dose, len = len) + assertNumeric(treatment2dose, len = len) + assertNumeric(HS_1, len = len) + assertNumeric(HS_2, len = len) + assertNumeric(E_inf_1, len = len) + assertNumeric(E_inf_2, len = len) + assertNumeric(EC50_1, len = len) + assertNumeric(EC50_2, len = len) + assertNumeric(tol, len = 1) + assertNumeric(lower_bound, len = 1) + assertNumeric(upper_bound, len = 1) + assertLogical(verbose, len = 1) + + ## Find viability that minimises the distance between Loewe CI and 1 + if (verbose) { + loewe_guess <- optimise( + f = .loeweLoss, + lower = lower_bound, + upper = upper_bound, + treatment1dose = treatment1dose, + HS_1 = HS_1, E_inf_1 = E_inf_1, EC50_1 = EC50_1, + treatment2dose = treatment2dose, + HS_2 = HS_2, E_inf_2 = E_inf_2, EC50_2 = EC50_2 + ) + } else { + suppressWarnings({ + loewe_guess <- optimise( + f = .loeweLoss, + lower = lower_bound, + upper = upper_bound, + treatment1dose = treatment1dose, + HS_1 = HS_1, E_inf_1 = E_inf_1, EC50_1 = EC50_1, + treatment2dose = treatment2dose, + HS_2 = HS_2, E_inf_2 = E_inf_2, EC50_2 = EC50_2 + ) + }) + } + + guess_err <- loewe_guess$objective + loewe_estimate <- loewe_guess$minimum + + if (is.nan(guess_err) | guess_err > tol) + loewe_estimate <- NA_real_ + + return(loewe_estimate) +} + + +# ==== Zero Interaction Potency (ZIP) + +#' @title Computes ZIP Null References +#' +#' @description +#' Predict the additive response of a treatment combination under +#' the ZIP null assumption. +#' +#' @param treatment1dose `numeric` a vector of concentrations for treatment 1 +#' @param HS_1 `numeric` Hill coefficient of treatment 1 +#' @param EC50_1 `numeric` relative EC50 of treatment 1. +#' @param E_inf_1 `numeric` viability produced by the maximum attainable effect of treatment 1. +#' Default 0 by the original paper. +#' @param treatment2dose `numeric` a vector of concentrations for treatment 2 +#' @param HS_2 `numeric` Hill coefficient of treatment 2 +#' @param EC50_2 `numeric` relative EC50 of treatment 2. +#' @param E_inf_2 `numeric` viability produced by maximum effect of treatment 2. +#' Default 0 by the original paper. +#' +#' @return `numeric` expected viability under ZIP null assumption. +#' +#' @examples +#' (zip <- computeZIP( +#' treatment1dose = c(0.1, 0.01, 0.001), +#' treatment2dose = c(1, 0.1, 0.01), +#' HS_1 = rep(1, 3), HS_2 = rep(1.2, 3), +#' EC50_1 = rep(0.01, 3), EC50_2 = rep(0.1, 3), +#' E_inf_1 = rep(0, 3), E_inf_2 = rep(0.1, 3) +#' )) +#' +#' @importFrom checkmate assertNumeric +#' +#' @export +computeZIP <- function(treatment1dose, HS_1, EC50_1, E_inf_1, + treatment2dose, HS_2, EC50_2, E_inf_2) { + len <- length(treatment1dose) + assertNumeric(treatment1dose, len = len) + assertNumeric(treatment2dose, len = len) + assertNumeric(HS_1, len = len) + assertNumeric(HS_2, len = len) + assertNumeric(E_inf_1, len = len) + assertNumeric(E_inf_2, len = len) + assertNumeric(EC50_1, len = len) + assertNumeric(EC50_2, len = len) + + y_1 <- .Hill(log10(treatment1dose), c(HS_1, E_inf_1, log10(EC50_1))) + y_2 <- .Hill(log10(treatment2dose), c(HS_2, E_inf_2, log10(EC50_2))) + y_zip <- y_1 * y_2 + return(y_zip) +} + +#' @title 4-Parameter Hill Equation for Stimuli-Response Curves +#' +#' @description +#' Sigmoidal function which fits well to many stimuli-response associations +#' observed in biology and pharmacology. In the context of PharmacoGx we +#' are using it to model treatment-response assocations in cancer cell lines. +#' +#' @param dose `numeric()` A vector of `log10(dose)` values (or equivalent for +#' the stimuli being modelleled). +#' @param HS `numeric(1)` Hill coefficient (n) which defines the slope of the +#' dose-response curve at the mid-point. This parameter describes the degree +#' of sigmoidicity of the Hill curve. HS = 1 corresponds to the rectangular +#' hyperbola in dose-response space. +#' @param EC50 `numeric(1)` The dose required to produce 50% of the +#' theoretically maximal response in the system, `E_inf`. Should be in the same +#' units as `dose`! +#' @param E_inf `numeric(1)` Theoretical maximal response (minimal viability) +#' in the system as a proportion in the range \\[0, 1\\]. Note that since we are +#' predicting viability (percent of cells alive after treatment) instead of +#' response, this value should be low (i.e., more cell killing). +#' @param E_ninf `numeric(1)` Theoretical minimum response (basal response). +#' Defaults to 1, which should be the case for most viability experiments since +#' we expect no cell killing to occur prior to applying a treatment. +#' +#' @return `numeric()` Vector of predicted viabilities for the Hill curve defined +#' by `EC50`, `E_inf`, `E_ninf` and `HS` for each supplied value of `dose`. +#' +#' @references +#' Gesztelyi, R., Zsuga, J., Kemeny-Beke, A., Varga, B., Juhasz, B., & +#' Tosaki, A. (2012). The Hill equation and the origin of quantitative +#' pharmacology. Archive for History of Exact Sciences, 66(4), 427–438. +#' https://doi.org/10.1007/s00407-012-0098-5 +#' +#' Motulsky, H., & Christopoulos, A. (2004). Fitting models to biological data +#' using linear and nonlinear regression: A practical guide to curve fitting. +#' Oxford University Press. See Chapter 41. +#' +#' @author +#' Feifei Li +#' Petr Smirnov +#' Christopher Eeles +#' +#' @examples +#' (viability <- hillCurve( +#' dose=c(0.1, 0.01, 0.001), +#' HS=1.1, +#' EC50=0.01, +#' E_ninf=1, +#' E_inf=0 +#' )) +#' +#' @export +hillCurve <- function(dose, HS, EC50, E_inf, E_ninf) { + E_inf + (( E_ninf - E_inf ) / ( 1 + ( 10^dose / 10^EC50 )^(HS) )) +} + +## TODO:: If it works well for fitting 2-way Hill curves, move it to CoreGx + +#' @title Compute Logarithm of Hyperbolic Cosine function +#' +#' @description +#' A numerical stable version of `log(cosh(x))` +#' without floating overflow or underflow. +#' Originally implemented in `limma` by Gordon K Smyth. +#' +#' @param x `numeric` vector or matrix. +#' +#' @return `numeric` a vector or matrix with the same dimension as `x`. +#' +#' @references +#' Ritchie ME, Phipson B, Wu D, Hu Y, Law CW, Shi W, Smyth GK (2015). “limma powers differential expression analyses for RNA-sequencing and microarray studies.” Nucleic Acids Research, 43(7), e47. doi: 10.1093/nar/gkv007. +#' +#' @noRd +#' @export +.logcosh <- function(x) { + y <- abs(x) - log(2) + i <- abs(x) < 1e-4 + y[i] <- 0.5*x[i]^2 + i <- !i & (abs(x) < 17) + y[i] <- log(cosh(x[i])) + y +} + + +#' @title Log-cosh loss for fitting projected Hill curves +#' +#' @description +#' Compute the log hyperbolic cosine (log-cosh) loss, +#' which behaves as L2 at small values and as L1 at large values. +#' +#' @param par `numeric` a vector of parameters to optimise in the following order: +#' `c(HS_proj, E_inf_proj, EC50_proj)` +#' @param dose_to `numeric` a vector of concentrations of the drug being added to +#' @param viability `numeric` Observed viability of two treatments; target for fitting curve. +#' @param E_min_proj `numeric` Projected `E_min` given by +#' the viability of the added treatment at a fixed dose. +#' +#' @return `numeric` Log-Cosh loss for fitting a 3-parameter Hill curve. See below. +#' +#' @noRd +.fitProjParamsLoss <- function(par, dose_to, viability, E_min_proj) { + sum( + .logcosh( + hillCurve( + dose = dose_to, + E_ninf = E_min_proj, + HS = par[1], + E_inf = par[2], + EC50 = par[3] + ) - viability + ) + ) +} + +#' @title Log-cosh loss for fitting projected Hill curves +#' +#' @description +#' Compute the log hyperbolic cosine (log-cosh) loss, +#' which behaves as L2 at small values and as L1 at large values. +#' +#' @param par `numeric` a vector of parameters to optimise +#' @param x `numeric` a vector of input values to the model +#' @param y `numeric` a vector of target values +#' @param fn `numeric` model to fit +#' @param ... `pairlist` Fall through arguments to `fn`. +#' +#' @return `numeric` scalar Log-Cosh loss for fitting a curve. +#' +#' @keywords interal +#' @noRd +.logcoshLoss <- function(par, x, y, fn, ...) { + sum(.logcosh(fn(par = par, x) - y)) +} + +#' @title Estimate the projected Hill coefficient, efficacy, and potency +#' +#' @description +#' Estimate the projected shape parameter HS, efficacy `E_inf` and potency `EC50` +#' in the new dose-response curve of a drug after adding another drug to it +#' by fitting a 2-parameter dose-response curve. +#' +#' @param dose_to `numeric` a vector of concentrations of the drug being added to +#' @param combo_viability `numeric` observed viability of two treatments; target for fitting curve. +#' @param dose_add `numeric` a vector of concentrations of the drug added. +#' @param EC50_add `numeric` relative EC50 of the drug added. +#' @param HS_add `numeric` Hill coefficient of the drug added. +#' @param E_inf_add `numeric` Efficacy of the drug added. +#' @param residual `character` Method used to minimise residual in fitting curves. +#' 3 methods available: `logcosh`, `normal`, `Cauchy`. +#' The default method is `logcosh`. +#' It minimises the logarithmic hyperbolic cosine loss of the residuals +#' and provides the fastest estimation among the three methods, +#' with fitting quality in between `normal` and `Cauchy`; +#' recommanded when fitting large-scale datasets. +#' The other two methods minimise residuals by +#' considering the truncated probability distribution (as in their names) for the residual. +#' `Cauchy` provides the best fitting quality but also takes the longest to run. +#' @param show_Rsqr `logical` whether to show goodness-of-fit value in the result. +#' @param conc_as_log `logical` indicates whether input concentrations are in log10 scale. +#' @param loss_args `list` Additional argument to the `loss` function. +#' These get passed to losss via `do.call` analagously to using `...`. +#' @param optim_only `logical(1)` Should the fall back methods when optim fails +#' +#' @references +#' Motulsky, H., & Christopoulos, A. (2004). Fitting dose-response curves. In Fitting models to biological data using linear and nonlinear regression: A practical guide to curve fitting. Oxford University Press. +#' +#' @return `list` +#' * `HS_proj`: Projected Hill coefficient after adding a drug +#' * `E_inf_proj`: Projected efficacy after adding a drug +#' * `EC50_proj`: Projected potency after adding a drug +#' * `E_ninf_proj`: Projected baseline viability by the added drug +#' * `Rsqr`: if `show_Rsqr` is `TRUE`, it will include the R squared value indicating the quality of the fit in the result. +#' +#' @importFrom CoreGx .fitCurve2 .reformatData +#' @importFrom checkmate assertNumeric assertLogical +#' +#' @export +estimateProjParams <- function(dose_to, combo_viability, dose_add, EC50_add, HS_add, + E_inf_add = 0, + residual = c(""logcosh"", ""normal"", ""Cauchy""), + show_Rsqr = TRUE, + conc_as_log = FALSE, + optim_only = FALSE, + loss_args = list() +) { + + len_to <- length(dose_to) + assertNumeric(dose_to, len = len_to) + assertNumeric(combo_viability, len = len_to) + assertNumeric(dose_add, len = 1) + assertNumeric(EC50_add, len = 1) + assertNumeric(HS_add, len = 1) + assertNumeric(E_inf_add, len = 1) + assertLogical(show_Rsqr, len = 1) + assertLogical(conc_as_log, len = 1) + residual <- match.arg(residual) + + ## viability of the drug being added as the minimum baseline response + if (conc_as_log) { + E_ninf_proj <- .Hill(dose_add, c(HS_add, E_inf_add, log10(EC50_add))) + } else { + E_ninf_proj <- .Hill(log10(dose_add), c(HS_add, E_inf_add, log10(EC50_add))) + } + formatted_data <- .reformatData( + x = dose_to, + y = combo_viability, + x_to_log = !conc_as_log, + y_to_frac = FALSE, ## subject to change + y_to_log = FALSE, + trunc = FALSE + ) + log_conc <- formatted_data[[""x""]] + combo_viability <- formatted_data[[""y""]] + + residual_fns <- list( + ""normal"" = CoreGx:::.normal_loss, + ""Cauchy"" = CoreGx:::.cauchy_loss, + ""logcosh"" = .logcoshLoss + ) + ## c(HS, EC50, E_inf, E_ninf) + lower_bounds <- c(0, -6, 0) + upper_bounds <- c(4, 6, 1) + density <- c(2, 5, 10) + step <- 0.5 / density + gritty_guess <- c( + pmin(pmax(1, lower_bounds[1]), upper_bounds[1]), + pmin( + pmax( + log_conc[which.min(abs(combo_viability - 1/2))], + lower_bounds[2] + ), + upper_bounds[2] + ), + pmin(pmax(min(combo_viability), lower_bounds[3]), upper_bounds[3]) + ) + + ## If we have zero or less degrees of freedom, fix the HS parameter to 1 + ## This is as per recommendations in Motulsky & Christopoulos (2004) + insuff_df <- len_to <= 3 + fit_curve_args <- list( + par = if (insuff_df) gritty_guess[-1] else gritty_guess, + x = log_conc, + y = combo_viability, + fn = function(x, HS, EC50, E_inf, E_ninf) { + hillCurve(dose=x, HS, EC50, E_inf, E_ninf) + }, + loss = residual_fns[[residual]], + lower = if (insuff_df) lower_bounds[-1] else lower_bounds, + upper = if (insuff_df) upper_bounds[-1] else upper_bounds, + density = if(insuff_df) density[-1] else density, + step = if (insuff_df) step[-1] else step, + optim_only = optim_only, + loss_args = loss_args, + E_ninf = E_ninf_proj + ) + if (insuff_df) + fit_curve_args <- c(fit_curve_args, HS = 1) + + proj_params <- do.call(.fitCurve2, fit_curve_args) + if (insuff_df) + proj_params <- c(1, proj_params) + + proj_params[2] <- 10^proj_params[2] + + if (show_Rsqr) { + Rsqr <- attr(proj_params, ""Rsquare"") + return(list( + HS_proj = proj_params[1], + EC50_proj = proj_params[2], + E_inf_proj = proj_params[3], + E_ninf_proj = E_ninf_proj, + Rsqr = Rsqr + )) + } else { + return(list( + HS_proj = proj_params[1], + E_inf_proj = proj_params[2], + EC50_proj = proj_params[3], + E_ninf_proj = E_ninf_proj + )) + } +} + +#' @title Two-way fitting for projected dose-response curve. +#' +#' @description +#' Fit projected dose-response curves with `E_min` as the viability +#' of the treatment being added to the other treament at a fixed dose. +#' +#' @examples +#' \dontrun{ +#' combo_profiles <- CoreGx::buildComboProfiles(tre, c(""HS"", ""EC50"", ""E_inf"", ""viability"")) +#' combo_twowayFit <- fitTwowayZIP(combo_profiles) +#' } +#' +#' @param combo_profiles [data.table] contains three parameters of dose-response curves +#' for each single agent in a drug comnbination, +#' and the observed viability of two treatments combined. +#' +#' @param residual `character` Method used to minimise residual in fitting curves. +#' 3 methods available: `c(""logcosh"", ""normal"", ""Cauchy"")`. +#' The default method is `logcosh`. +#' It minimises the logarithmic hyperbolic cosine loss of the residuals +#' and provides the fastest estimation among the three methods, +#' with fitting quality in between `normal` and `Cauchy`; +#' recommanded when fitting large-scale datasets. +#' The other two methods minimise residuals by +#' considering the truncated probability distribution (as in their names) for the residual. +#' `Cauchy` provides the best fitting quality but also takes the longest to run. +#' @param show_Rsqr `logical` whether to show goodness-of-fit value in the result. +#' @param nthread `integer` Number of cores used to perform computation. Default 1. +#' @param loss_args `list` Additional argument to the `loss` function. +#' These get passed to losss via `do.call` analagously to using `...`. +#' @param optim_only `logical(1)` Should the fall back methods when optim fails +#' +#' @return [data.table] contains parameters of projected dose-response curves +#' for adding one treatment to the other. +#' +#' @references +#' Yadav, B., Wennerberg, K., Aittokallio, T., & Tang, J. (2015). Searching for Drug Synergy in Complex Dose–Response Landscapes Using an Interaction Potency Model. Computational and Structural Biotechnology Journal, 13, 504–513. https://doi.org/10.1016/j.csbj.2015.09.001 +#' +#' @importFrom CoreGx aggregate +#' @importFrom checkmate assertLogical assertInt assertDataTable +#' @import data.table +#' @export +fitTwowayZIP <- function( + combo_profiles, + residual = ""logcosh"", + show_Rsqr = TRUE, + nthread = 1L, + optim_only = TRUE, + loss_args = list() +) { + + assertDataTable(combo_profiles, min.rows = 1) + assertLogical(show_Rsqr, len = 1) + assertInt(nthread, lower = 1L) + required_cols <- c( + ""treatment1id"", ""treatment2id"", ""treatment1dose"", ""treatment2dose"", + ""sampleid"", ""combo_viability"", + ""HS_1"", ""HS_2"", ""E_inf_1"", ""E_inf_2"", ""EC50_1"", ""EC50_2"" + ) + + has_cols <- required_cols %in% colnames(combo_profiles) + if (!all(has_cols)) + stop(""Missing required columns of parameters: "", + paste(required_cols[!has_cols], sep = "", ""), + call. = FALSE) + + combo_profiles |> + aggregate( + estimateProjParams( + dose_to = treatment1dose, + combo_viability = combo_viability, + dose_add = unique(treatment2dose), + EC50_add = unique(EC50_2), + HS_add = unique(HS_2), + E_inf_add = unique(E_inf_2), + residual = residual, + show_Rsqr = show_Rsqr, + optim_only = optim_only, + loss_args = loss_args + ), + moreArgs = list( + residual = residual, + show_Rsqr = show_Rsqr, + optim_only = optim_only, + loss_args = loss_args + ), + by = c(""treatment1id"", ""treatment2id"", ""treatment2dose"", ""sampleid""), + nthread = nthread, + enlist = FALSE + ) -> fit_2_to_1 + combo_profiles |> + aggregate( + estimateProjParams( + dose_to = treatment2dose, + combo_viability = combo_viability, + dose_add = unique(treatment1dose), + EC50_add = unique(EC50_1), + HS_add = unique(HS_1), + E_inf_add = unique(E_inf_1), + residual = residual, + show_Rsqr = show_Rsqr, + optim_only = optim_only, + loss_args = loss_args + ), + moreArgs = list( + residual = residual, + show_Rsqr = show_Rsqr, + optim_only = optim_only, + loss_args = loss_args + ), + by = c(""treatment1id"", ""treatment2id"", ""treatment1dose"", ""sampleid""), + nthread = nthread, + enlist = FALSE + ) -> fit_1_to_2 + + combo_twowayFit <- combo_profiles[ + fit_1_to_2, , + on = c( + treatment1id = ""treatment1id"", + treatment2id = ""treatment2id"", + treatment1dose = ""treatment1dose"", + sampleid = ""sampleid"" + ) + ] + + combo_twowayFit <- merge.data.table( + combo_twowayFit, + fit_2_to_1, + by.x = c(""treatment1id"", ""treatment2id"", ""treatment2dose"", ""sampleid""), + by.y = c(""treatment1id"", ""treatment2id"", ""treatment2dose"", ""sampleid""), + suffixes = c(""_1_to_2"", ""_2_to_1"") + ) + + return(combo_twowayFit) +} + +## == Plot the result of two-way fittings for a drug combination experiment === + +#' @title Plot projected Hill curves +#' +#' @description +#' Plot the two-way projected Hill curves of adding one drug to the other. +#' +#' @param combo_twowayFit `data.table` +#' containing two-way fitted parameters for multiple drug combination experiments. +#' +#' @param treatment1 `character` +#' the `treatment1id` to select in `combo_twowayFit` for a drug combination. +#' +#' @param treatment2 +#' the `treatment2id` to select in `combo_twowayFit` for a drug combination. +#' +#' @param cellline +#' the `sampleid` to select in `combo_twowayFit` for a drug combination experiment. +#' +#' @param add_treatment +#' The added treatment in projected Hill curves, either integer 1 or 2. +#' 1 means adding treatment 1 to treatment 2. +#' +#' @return produce a plot with projected Hill curves of adding treatment [add_treatment] +#' +#' @importFrom graphics plot curve points legend +#' @importFrom grDevices palette rainbow +#' @export +#' @noRd +#' @examples +#' \dontrun{ +#' combo_profiles <- CoreGx::buildComboProfiles(tre, c(""HS"", ""EC50"", ""E_inf"", ""viability"")) +#' combo_twowayFit <- fitTwowayZIP(combo_profiles) +#' .plotProjHill(combo_twowayFit, +#' treatment1 = ""Methotrexate"", +#' treatment2 = ""Zolendronic Acid"", +#' cellline = ""UO-31"", +#' add_treatment = 1) +#' } +.plotProjHill <- function(combo_twowayFit, treatment1, treatment2, + cellline, add_treatment = 1, title = NULL) { + + required_cols <- c(""treatment1id"", ""treatment1dose"", ""treatment2id"", ""treatment2dose"", + ""sampleid"", ""combo_viability"", ""HS_1"", ""E_inf_1"", ""EC50_1"", ""HS_2"", ""E_inf_2"", + ""EC50_2"", ""HS_proj_1_to_2"", ""E_inf_proj_1_to_2"", ""EC50_proj_1_to_2"", + ""E_ninf_proj_1_to_2"", ""HS_proj_2_to_1"", ""E_inf_proj_2_to_1"", + ""EC50_proj_2_to_1"", ""E_ninf_proj_2_to_1"") + has_cols <- (required_cols %in% colnames(combo_twowayFit)) + if (!all(has_cols)) + stop(""Missing required columns for plotting: "", + paste(required_cols[!has_cols])) + + select_combo <- combo_twowayFit[treatment1id == treatment1 & + treatment2id == treatment2 & + sampleid == cellline] + if (dim(select_combo)[1] <= 0) + stop(paste(""No such drug combination with treatment1id:"", treatment1, + ""and treatment2id:"", treatment2, ""and sampleid:"", cellline)) + + if (length(add_treatment) > 1) + stop(""Argument `add_treatment` must be of length 1."") + + if (!(add_treatment %in% c(1, 2))) + stop(""Argument `add_treatment` must be either 1 or 2."") + + ## Use variable name as title if not provided + if (is.null(title)) + title <- deparse(substitute(combo_twowayFit)) + + ## Colours for each curve of a fixed concentration of the drug added + + has_Rsqr <- c(""Rsqr_1_to_2"", ""Rsqr_2_to_1"") %in% colnames(combo_twowayFit) + if (add_treatment == 2) { + ## unique treatment 2 concentrations + unique_t2_dose <- unique(select_combo[, treatment2dose]) + cols <- palette(rainbow(length(unique_t2_dose))) + if (has_Rsqr[2]) + Rsqr_2_to_1 <- vector(mode = ""numeric"", length = length(unique_t2_dose)) + ## Initialise an empty background canvas + plot( + NULL, xlim = c(-10, 10), ylim = c(0, 2), + ylab = paste(""Response of adding"", treatment2, ""to"", treatment1), + xlab = paste0(""log10(["", treatment1,""])""), + main = title + ) + for (i in seq_along(unique_t2_dose)) { + dose_add <- unique_t2_dose[i] + EC50_proj <- unique(select_combo[treatment2dose == dose_add, EC50_proj_2_to_1]) + HS_proj <- unique(select_combo[treatment2dose == dose_add, HS_proj_2_to_1]) + EC50_add <- unique(select_combo[treatment2dose == dose_add, EC50_2]) + E_inf_add <- unique(select_combo[treatment2dose == dose_add, E_inf_2]) + E_inf_proj <- unique(select_combo[treatment2dose == dose_add, E_inf_proj_2_to_1]) + HS_add <- unique(select_combo[treatment2dose == dose_add, HS_2]) + dose_to <- select_combo[treatment2dose == dose_add, treatment1dose] + E_ninf_proj <- PharmacoGx:::.Hill(log10(dose_add), c(HS_add, E_inf_add, log10(EC50_add))) + if (has_Rsqr[2]) + Rsqr_2_to_1[i] <- unique(select_combo[treatment2dose == dose_add, Rsqr_2_to_1]) + y <- select_combo[treatment2dose == dose_add, combo_viability] + curve( + PharmacoGx::hillCurve( + E_ninf = E_ninf_proj, + E_inf = E_inf_proj, + HS = HS_proj, + EC50 = log10(EC50_proj), + dose = x + ), + from = -10, to = 10, add = TRUE, col = cols[i] + ) + points(x = log10(dose_to), y = y, col = cols[i]) + } + if (has_Rsqr[2]) { + legend(-10, 2, + legend = paste0(""["", treatment2, ""] = "", unique_t2_dose, + "", R square = "", round(Rsqr_2_to_1, digits = 4)), + col = cols, + lty = 1, + box.lty = 0 + ) + } else { + legend(-10, 2, + legend = paste0(""["", treatment2, ""] = "", unique_t2_dose), + col = cols, + lty = 1, + box.lty = 0 + ) + } + } else { + ## unique treatment 1 concentrations + unique_t1_dose <- unique(select_combo[, treatment1dose]) + cols <- palette(rainbow(length(unique_t1_dose))) + ## TODO: Find a nicer way to extract R squared value + if (has_Rsqr[1]) + Rsqr_1_to_2 <- vector(mode = ""numeric"", length = length(unique_t1_dose)) + + ## Initialise an empty background canvas + plot( + NULL, xlim = c(-10, 10), ylim = c(0, 2), + ylab = paste(""Response of adding"", treatment1, ""to"", treatment2), + xlab = paste0(""log10(["", treatment2,""])""), + main = title + ) + for (i in seq_along(unique_t1_dose)) { + dose_add <- unique_t1_dose[i] + EC50_proj <- unique(select_combo[treatment1dose == dose_add, EC50_proj_1_to_2]) + HS_proj <- unique(select_combo[treatment1dose == dose_add, HS_proj_1_to_2]) + EC50_add <- unique(select_combo[treatment1dose == dose_add, EC50_1]) + HS_add <- unique(select_combo[treatment1dose == dose_add, HS_1]) + E_inf_add <- unique(select_combo[treatment1dose == dose_add, E_inf_1]) + E_ninf_proj <- PharmacoGx:::.Hill(log10(dose_add), c(HS_add, E_inf_add, log10(EC50_add))) + E_inf_proj <- unique(select_combo[treatment1dose == dose_add, E_inf_proj_1_to_2]) + dose_to <- select_combo[treatment1dose == dose_add, treatment2dose] + if (has_Rsqr[1]) + Rsqr_1_to_2[i] <- unique(select_combo[treatment1dose == dose_add, Rsqr_1_to_2]) + y <- select_combo[treatment1dose == dose_add, combo_viability] + curve( + PharmacoGx::hillCurve( + E_ninf = E_ninf_proj, + E_inf = E_inf_proj, + HS = HS_proj, + EC50 = log10(EC50_proj), + dose = x + ), + from = -10, to = 10, add = TRUE, col = cols[i] + ) + points(x = log10(dose_to), y = y, col = cols[i]) + } + if (has_Rsqr[1]) { + legend(-10, 2, + legend = paste0(""["", treatment1, ""] = "", unique_t1_dose, + "", R square = "", round(Rsqr_1_to_2, digits = 4)), + col = cols, + lty = 1, + box.lty = 0 + ) + } else { + legend(-10, 2, + legend = paste0(""["", treatment1, ""] = "", unique_t1_dose), + col = cols, + lty = 1, + box.lty = 0 + ) + } + } + +} + +#' Generic to compute ZIP delta scores from an S4 object +#' +#' @examples +#' print(""Generics shouldn't need examples?"") +#' +#' @param object `S4` An object to compute delta scores from. +#' @param ... Allow new arguments to this generic. +#' +#' @return Depends on the implemented method. +#' +#' @exportMethod computeZIPdelta +setGeneric(name = ""computeZIPdelta"", + def = function(object, ...) standardGeneric(""computeZIPdelta"")) + +#' @title Compute ZIP delta score +#' +#' @description +#' Following the calculation of ZIP delta score as in Appendix A3. +#' See reference for details. +#' +#' @description Compute ZIP delta score as described in the original paper. +#' +#' @param object [TreatmentResponseExperiment] +#' The `TreatmentResponseExperiment` from which to extract assays +#' `mono_profile` and `combo_viability` to compute ZIP delta scores. +#' @param residual `character` Method used to minimise residual in fitting curves. +#' 3 methods available: `c(""logcosh"", ""normal"", ""Cauchy"")`. +#' The default method is `logcosh`. +#' It minimises the logarithmic hyperbolic cosine loss of the residuals +#' and provides the fastest estimation among the three methods, +#' with fitting quality in between `normal` and `Cauchy`; +#' recommanded when fitting large-scale datasets. +#' The other two methods minimise residuals by +#' considering the truncated probability distribution (as in their names) for the residual. +#' `Cauchy` provides the best fitting quality but also takes the longest to run. +#' @param nthread `integer` Number of cores used to perform computation. +#' Default 1. +#' @param show_Rsqr `logical` Whether to show the 2-way curve fitting quality in the result. +#' Default FALSE. +#' +#' @return [TreatmentResponseExperiment] with assay `combo_scores` containing `delta_scores` +#' +#' @examples +#' \dontrun{ +#' tre <- computeZIPdelta(tre, residual = ""Cauchy"", nthread = 2L) +#' } +#' +#' @references +#' Yadav, B., Wennerberg, K., Aittokallio, T., & Tang, J. (2015). Searching for Drug Synergy in Complex Dose–Response Landscapes Using an Interaction Potency Model. Computational and Structural Biotechnology Journal, 13, 504–513. https://doi.org/10.1016/j.csbj.2015.09.001 +#' +#' @importFrom CoreGx buildComboProfiles aggregate +#' @importFrom checkmate assertInt assertLogical +#' @import data.table +#' @export +#' @docType methods +setMethod(""computeZIPdelta"", signature(object = ""TreatmentResponseExperiment""), + function(object, residual = ""logcosh"", nthread = 1L, + show_Rsqr = FALSE) { + + if (!is.character(residual)) { + stop(""argument `residual` must be type of logical"") + } else if (length(residual) != 1) { + stop(""argument `residual` must be of length 1"") + } + + assertInt(nthread, lower = 1L) + assertLogical(show_Rsqr, len = 1) + + combo_keys <- c(""treatment1id"", ""treatment2id"", + ""treatment1dose"", ""treatment2dose"", ""sampleid"") + combo_profiles <- tryCatch({ + buildComboProfiles(object, c(""HS"", ""EC50"", ""E_inf"", ""ZIP"", ""combo_viability"")) + }, warning = function(w) { + message(paste(""ZIP reference values have not been pre-computed."", + ""They will be computed in during delta score calculation."")) + buildComboProfiles(object, c(""HS"", ""EC50"", ""E_inf"", ""combo_viability"")) + }) + required_params <- c(""HS_1"", ""HS_2"", ""E_inf_1"", ""E_inf_2"", ""EC50_1"", ""EC50_2"") + missing_params <- !(required_params %in% colnames(combo_profiles)) + if (any(missing_params)) + stop(""Missing required paramters for two-way Hill curve fitting: "", + paste(required_params[missing_params])) + has_ZIP <- ""ZIP"" %in% colnames(combo_profiles) + if (has_ZIP) { + combo_ZIP <- combo_profiles[, c(combo_keys, ""ZIP""), with = FALSE] + combo_profiles[, ZIP := NULL] + setkeyv(combo_ZIP, combo_keys) + } + + combo_twowayFit <- fitTwowayZIP(combo_profiles = combo_profiles, + residual = residual, + nthread = nthread, + show_Rsqr = show_Rsqr) + setkeyv(combo_twowayFit, combo_keys) + if (has_ZIP) { + combo_twowayFit <- combo_twowayFit[combo_ZIP, on = combo_keys] + if (show_Rsqr) { + combo_twowayFit |> + aggregate( + delta_score = .deltaScore( + EC50_1_to_2 = EC50_proj_1_to_2, + EC50_2_to_1 = EC50_proj_2_to_1, + EC50_1 = EC50_1, EC50_2 = EC50_2, + HS_1_to_2 = HS_proj_1_to_2, + HS_2_to_1 = HS_proj_2_to_1, + HS_1 = HS_1, HS_2 = HS_2, + E_inf_1 = E_inf_1, E_inf_2 = E_inf_2, + E_inf_2_to_1 = E_inf_proj_2_to_1, + E_inf_1_to_2 = E_inf_proj_1_to_2, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose, + ZIP = ZIP + ), + delta_Rsqr_1_to_2 = Rsqr_1_to_2, + delta_Rsqr_2_to_1 = Rsqr_2_to_1, + by = combo_keys, + nthread = nthread + ) -> delta_scores + } else { + combo_twowayFit |> + aggregate( + delta_score = .deltaScore( + EC50_1_to_2 = EC50_proj_1_to_2, + EC50_2_to_1 = EC50_proj_2_to_1, + EC50_1 = EC50_1, EC50_2 = EC50_2, + HS_1_to_2 = HS_proj_1_to_2, + HS_2_to_1 = HS_proj_2_to_1, + HS_1 = HS_1, HS_2 = HS_2, + E_inf_1 = E_inf_1, E_inf_2 = E_inf_2, + E_inf_2_to_1 = E_inf_proj_2_to_1, + E_inf_1_to_2 = E_inf_proj_1_to_2, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose, + ZIP = ZIP + ), + by = combo_keys, + nthread = nthread + ) -> delta_scores + } + } else { + if (show_Rsqr) { + combo_twowayFit |> + aggregate( + delta_score = .deltaScore( + EC50_1_to_2 = EC50_proj_1_to_2, + EC50_2_to_1 = EC50_proj_2_to_1, + EC50_1 = EC50_1, EC50_2 = EC50_2, + HS_1_to_2 = HS_proj_1_to_2, + HS_2_to_1 = HS_proj_2_to_1, + HS_1 = HS_1, HS_2 = HS_2, + E_inf_1 = E_inf_1, E_inf_2 = E_inf_2, + E_inf_2_to_1 = E_inf_proj_2_to_1, + E_inf_1_to_2 = E_inf_proj_1_to_2, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose + ), + delta_Rsqr_1_to_2 = Rsqr_1_to_2, + delta_Rsqr_2_to_1 = Rsqr_2_to_1, + by = combo_keys, + nthread = nthread + ) -> delta_scores + } else { + combo_twowayFit |> + aggregate( + delta_score = .deltaScore( + EC50_1_to_2 = EC50_proj_1_to_2, + EC50_2_to_1 = EC50_proj_2_to_1, + EC50_1 = EC50_1, EC50_2 = EC50_2, + HS_1_to_2 = HS_proj_1_to_2, + HS_2_to_1 = HS_proj_2_to_1, + HS_1 = HS_1, HS_2 = HS_2, + E_inf_1 = E_inf_1, E_inf_2 = E_inf_2, + E_inf_2_to_1 = E_inf_proj_2_to_1, + E_inf_1_to_2 = E_inf_proj_1_to_2, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose + ), + by = combo_keys, + nthread = nthread + ) -> delta_scores + } + } + setkeyv(delta_scores, combo_keys) + ## Add delta scores to combo_scores in input TRE + combo_scores <- tryCatch({ + object$combo_scores + }, error = function(e) { + NULL + }) + if (is.null(combo_scores)) { + ## create a new combo_score assay and save delta scores + object$combo_scores <- delta_scores + } else { + object$combo_scores <- combo_scores[delta_scores, , on = combo_keys] + } + + return(object) +}) + +#' @title Vector-based version of [computeZIPdelta] +#' +#' @description +#' Following the calculation of ZIP delta score as in Appendix A3. +#' See reference for details. +#' +#' @param treatment1id `character` a vector of identifiers for treatment 1 +#' @param treatment2id `character` a vector of identifiers for treatment 2 +#' @param treatment1dose `numeric` a vector of concentrations for treatment 1 +#' @param treatment2dose `numeric` a vector of concentrations for treatment 2 +#' @param sampleid `character` Cell-line ID of a drug combination screening experiment. +#' @param HS_1 `numeric` Hill coefficient of treatment 1 +#' @param HS_2 `numeric` Hill coefficient of treatment 2 +#' @param EC50_1 `numeric` relative EC50 of treatment 1. +#' @param EC50_2 `numeric` relative EC50 of treatment 2. +#' @param E_inf_1 `numeric` viability produced by the maximum attainable effect of treatment 1. +#' @param E_inf_2 `numeric` viability produced by the maximum attainable effect of treatment 2. +#' @param combo_viability `numeric` observed viability of the two treatments combined. +#' @param ZIP `numeric` pre-computed ZIP reference values. +#' If not provided, it will be computed during delta score calculation. +#' @param residual `character` Method used to minimise residual in fitting curves. +#' 3 methods available: `c(""logcosh"", ""normal"", ""Cauchy"")`. +#' The default method is `logcosh`. +#' It minimises the logarithmic hyperbolic cosine loss of the residuals +#' and provides the fastest estimation among the three methods, +#' with fitting quality in between `normal` and `Cauchy`; +#' recommanded when fitting large-scale datasets. +#' The other two methods minimise residuals by +#' considering the truncated probability distribution (as in their names) for the residual. +#' `Cauchy` provides the best fitting quality but also takes the longest to run. +#' @param nthread `integer` Number of cores used to perform computation. +#' Default 1. +#' @param show_Rsqr `logical` Whether to show the 2-way curve fitting quality in the result. +#' Default FALSE. +#' +#' @return `numeric` delta scores of every dose combinations for any given treatment combinations. +#' +#' @examples +#' \dontrun{ +#' ## ZIP is optional. Will be recomputed if not provided. +#' combo_profiles <- CoreGx::buildComboProfiles( +#' tre, +#' c(""HS"", ""EC50"", ""E_inf"", ""ZIP"", ""combo_viability"")) +#' combo_profiles[, +#' .computeZIPdelta( +#' treatment1id = treatment1id, +#' treatment2id = treatment2id, +#' treatment1dose = treatment1dose, +#' treatment2dose = treatment2dose, +#' sampleid = sampleid, +#' HS_1 = HS_1, HS_2 = HS_2, +#' EC50_1 = EC50_1, EC50_2 = EC50_2, +#' E_inf_1 = E_inf_1, E_inf_2 = E_inf_2, +#' combo_viability = combo_viability, +#' ZIP = ZIP, +#' nthread = 4, +#' show_Rsqr = TRUE +#' ) +#' ] -> delta_scores +#' } +#' +#' @references +#' Yadav, B., Wennerberg, K., Aittokallio, T., & Tang, J. (2015). Searching for Drug Synergy in Complex Dose–Response Landscapes Using an Interaction Potency Model. Computational and Structural Biotechnology Journal, 13, 504–513. https://doi.org/10.1016/j.csbj.2015.09.001 +#' +#' @importFrom CoreGx aggregate +#' @importFrom checkmate assertNumeric assertInt assertLogical +#' @import data.table +#' @keywords internal +#' @export +.computeZIPdelta <- function( + treatment1id, treatment2id, treatment1dose, treatment2dose, sampleid, + HS_1, HS_2, EC50_1, EC50_2, E_inf_1, E_inf_2, combo_viability, ZIP = NULL, + residual = ""logcosh"", nthread = 1L, show_Rsqr = FALSE) { + + assertInt(nthread, lower = 1L) + assertLogical(show_Rsqr, len = 1) + len <- length(treatment1dose) + assertNumeric(treatment1dose, len = len) + assertNumeric(treatment2dose, len = len) + assertNumeric(HS_1, len = len) + assertNumeric(HS_2, len = len) + assertNumeric(E_inf_1, len = len) + assertNumeric(E_inf_2, len = len) + assertNumeric(EC50_1, len = len) + assertNumeric(EC50_2, len = len) + assertNumeric(combo_viability, len = len) + if (!is.null(ZIP)) + assertNumeric(ZIP, len = len) + + combo_keys <- c(""treatment1id"", ""treatment2id"", + ""treatment1dose"", ""treatment2dose"", ""sampleid"") + + combo_profiles <- data.table( + treatment1id = treatment1id, + treatment2id = treatment2id, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose, + sampleid = sampleid, + combo_viability = combo_viability, + HS_1 = HS_1, + HS_2 = HS_2, + EC50_1 = EC50_1, + EC50_2 = EC50_2, + E_inf_1 = E_inf_1, + E_inf_2 = E_inf_2 + ) + + if (!is.null(ZIP)) { + combo_ZIP <- data.table( + treatment1id = treatment1id, + treatment2id = treatment2id, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose, + sampleid = sampleid, + ZIP = ZIP + ) + setkeyv(combo_ZIP, combo_keys) + } + + combo_twowayFit <- fitTwowayZIP(combo_profiles = combo_profiles, + residual = residual, + nthread = nthread, + show_Rsqr = show_Rsqr) + setkeyv(combo_twowayFit, combo_keys) + if (is.null(ZIP)) { + if (show_Rsqr) { + combo_twowayFit |> + aggregate( + delta_score = .deltaScore( + EC50_1_to_2 = EC50_proj_1_to_2, + EC50_2_to_1 = EC50_proj_2_to_1, + EC50_1 = EC50_1, EC50_2 = EC50_2, + HS_1_to_2 = HS_proj_1_to_2, + HS_2_to_1 = HS_proj_2_to_1, + HS_1 = HS_1, HS_2 = HS_2, + E_inf_1 = E_inf_1, E_inf_2 = E_inf_2, + E_inf_2_to_1 = E_inf_proj_2_to_1, + E_inf_1_to_2 = E_inf_proj_1_to_2, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose + ), + delta_Rsqr_1_to_2 = Rsqr_1_to_2, + delta_Rsqr_2_to_1 = Rsqr_2_to_1, + by = combo_keys, + nthread = nthread + ) -> delta_scores + } else { + combo_twowayFit |> + aggregate( + delta_score = .deltaScore( + EC50_1_to_2 = EC50_proj_1_to_2, + EC50_2_to_1 = EC50_proj_2_to_1, + EC50_1 = EC50_1, EC50_2 = EC50_2, + HS_1_to_2 = HS_proj_1_to_2, + HS_2_to_1 = HS_proj_2_to_1, + HS_1 = HS_1, HS_2 = HS_2, + E_inf_1 = E_inf_1, E_inf_2 = E_inf_2, + E_inf_2_to_1 = E_inf_proj_2_to_1, + E_inf_1_to_2 = E_inf_proj_1_to_2, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose + ), + by = combo_keys, + nthread = nthread + ) -> delta_scores + } + } else { + combo_twowayFit <- combo_twowayFit[combo_ZIP, on = combo_keys] + if (show_Rsqr) { + combo_twowayFit |> + aggregate( + delta_score = .deltaScore( + EC50_1_to_2 = EC50_proj_1_to_2, + EC50_2_to_1 = EC50_proj_2_to_1, + EC50_1 = EC50_1, EC50_2 = EC50_2, + HS_1_to_2 = HS_proj_1_to_2, + HS_2_to_1 = HS_proj_2_to_1, + HS_1 = HS_1, HS_2 = HS_2, + E_inf_1 = E_inf_1, E_inf_2 = E_inf_2, + E_inf_2_to_1 = E_inf_proj_2_to_1, + E_inf_1_to_2 = E_inf_proj_1_to_2, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose, + ZIP = ZIP + ), + delta_Rsqr_1_to_2 = Rsqr_1_to_2, + delta_Rsqr_2_to_1 = Rsqr_2_to_1, + by = combo_keys, + nthread = nthread + ) -> delta_scores + } else { + combo_twowayFit |> + aggregate( + delta_score = .deltaScore( + EC50_1_to_2 = EC50_proj_1_to_2, + EC50_2_to_1 = EC50_proj_2_to_1, + EC50_1 = EC50_1, EC50_2 = EC50_2, + HS_1_to_2 = HS_proj_1_to_2, + HS_2_to_1 = HS_proj_2_to_1, + HS_1 = HS_1, HS_2 = HS_2, + E_inf_1 = E_inf_1, E_inf_2 = E_inf_2, + E_inf_2_to_1 = E_inf_proj_2_to_1, + E_inf_1_to_2 = E_inf_proj_1_to_2, + treatment1dose = treatment1dose, + treatment2dose = treatment2dose, + ZIP = ZIP + ), + by = combo_keys, + nthread = nthread + ) -> delta_scores + } + } + if (show_Rsqr) { + return(as.list(delta_scores[, + c(combo_keys, ""delta_score"", ""delta_Rsqr_1_to_2"", ""delta_Rsqr_2_to_1""), + with = FALSE + ])) + } else { + return(as.list(delta_scores[, c(combo_keys, ""delta_score""), with = FALSE])) + } +} + + +#' @title Calculate ZIP delta score for a drug combination +#' +#' @description +#' Following the calculation of ZIP delta score as in Appendix A3. +#' See reference for details. +#' +#' @param EC50_1_to_2 `numeric` projected EC50 of treatment 2 after adding treatment 1. +#' @param EC50_2_to_1 `numeric` projected EC50 of treatment 1 after adding treatment 2. +#' @param EC50_1 `numeric` relative EC50 of treatment 1. +#' @param EC50_2 `numeric` relative EC50 of treatment 2. +#' @param HS_1_to_2 `numeric` projected Hill coefficient of treatment 2 +#' after adding treatment 1. +#' @param HS_2_to_1 `numeric` projected Hill coefficient of treatment 1 +#' after adding treatment 2. +#' @param HS_1 `numeric` Hill coefficient of treatment 1 +#' @param HS_2 `numeric` Hill coefficient of treatment 2 +#' @param E_inf_2_to_1 `numeric` projected maximum attainable effect of +#' adding treatment 2 to treatment 1. +#' @param E_inf_1_to_2 `numeric` projected maximum attainable effect of +#' adding treatment 1 to treatment 2. +#' @param E_inf_1 `numeric` viability produced by the maximum attainable effect of treatment 1. +#' @param E_inf_2 `numeric` viability produced by the maximum attainable effect of treatment 2. +#' @param treatment1dose `numeric` a vector of concentrations for treatment 1 +#' @param treatment2dose `numeric` a vector of concentrations for treatment 2 +#' @param ZIP `numeric` pre-computed ZIP reference values. +#' If not provided, it will be computed during delta score calculation. +#' +#' @return `numeric` a ZIP delta score to quantify synergy for the drug combination. +#' +#' @noRd +#' @references +#' Yadav, B., Wennerberg, K., Aittokallio, T., & Tang, J. (2015). Searching for Drug Synergy in Complex Dose–Response Landscapes Using an Interaction Potency Model. Computational and Structural Biotechnology Journal, 13, 504–513. https://doi.org/10.1016/j.csbj.2015.09.001 +#' @export +.deltaScore <- function(EC50_1_to_2, EC50_2_to_1, EC50_1, EC50_2, + HS_1_to_2, HS_2_to_1, HS_1, HS_2, + E_inf_2_to_1, E_inf_1_to_2, E_inf_1, E_inf_2, + treatment1dose, treatment2dose, ZIP = NULL) { + + viability_1 <- .Hill(log10(treatment1dose), c(HS_1, E_inf_1, log10(EC50_1))) + viability_2 <- .Hill(log10(treatment2dose), c(HS_2, E_inf_2, log10(EC50_2))) + viability_2_to_1 <- hillCurve( + dose = treatment1dose, + HS = HS_2_to_1, + EC50 = EC50_2_to_1, + E_ninf = viability_2, + E_inf = E_inf_2_to_1 + ) + viability_1_to_2 <- hillCurve( + dose = treatment2dose, + HS = HS_1_to_2, + EC50 = EC50_1_to_2, + E_ninf = viability_1, + E_inf = E_inf_1_to_2 + ) + ## avoid re-calculating ZIP references + if (is.null(ZIP)) { + viability_ZIP <- computeZIP(treatment1dose = treatment1dose, + treatment2dose = treatment2dose, + HS_1 = HS_1, HS_2 = HS_2, + EC50_1 = EC50_1, EC50_2 = EC50_2, + E_inf_1 = E_inf_1, E_inf_2 = E_inf_2) + } else { + viability_ZIP <- ZIP + } + delta <- viability_ZIP - (1/2) * (viability_2_to_1 + viability_1_to_2) + + return(delta) +} + +# ==== Bliss Independence + +#' @title Compute Bliss Null References +#' +#' @description +#' Given two `numeric` containing viability of two monotherapy respectively, +#' Compute Bliss null reference values for the expected response +#' of the two treatments combined. +#' +#' @param viability_1 `numeric` monotherapeutic response of treatment 1. +#' @param viability_2 `numeric` monotherapeutic response of treatment 2. +#' +#' @return `numeric` expected response of the two treatments combined +#' under Bliss null assumption. +#' +#' @examples +#' (bliss <- computeBliss(0.75, 0.65)) +#' +#' @export +computeBliss <- function(viability_1, viability_2) { + bliss_ref <- (viability_1 * viability_2) + return(bliss_ref) +} + +# ==== Highest Single Agent (HSA) + +#' @title Compute HSA Null References +#' +#' @description +#' Given two `numeric` containing viability of two monotherapy respectively, +#' Compute highest single-agent (HSA) values as the expected response +#' of the two treatments combined. +#' +#' @param viability_1 `numeric` monotherapeutic response of treatment 1. +#' @param viability_2 `numeric` monotherapeutic response of treatment 2. +#' +#' @return `numeric` expected response of the two treatments combined +#' using the highest response of the two (lower viability). +#' +#' @examples +#' (hsa <- computeHSA(0.75, 0.65)) +#' +#' @export +computeHSA <- function(viability_1, viability_2) { + HSA_ref <- min(viability_1, viability_2) + return(HSA_ref) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/globals.R",".R","220","4","# Define global variables for ggplot/dplyr columns +utils::globalVariables(c(""X"", ""Y"", ""Cutoff"", 'rn', ""treatmentid"", ""sampleid"", 'rn', + 'rowKey', 'colKey', 'drug_cell_rep', 'value', 'max.conc', + 'drug_cell_rep.x'))","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/drugDoseResponseCurve.R",".R","16798","349","#' Plot drug response curve of a given drug and a given cell for a list of pSets (objects of the PharmacoSet class). +#' +#' Given a list of PharmacoSets, the function will plot the drug_response curve, +#' for a given drug/cell pair. The y axis of the plot is the viability percentage +#' and x axis is the log transformed concentrations. If more than one pSet is +#' provided, a light gray area would show the common concentration range between pSets. +#' User can ask for type of sensitivity measurment to be shown in the plot legend. +#' The user can also provide a list of their own concentrations and viability values, +#' as in the examples below, and it will be treated as experiments equivalent to values coming +#' from a pset. The names of the concentration list determine the legend labels. +#' +#' @examples +##TODO:: How do you pass PSets to this? +#' if (interactive()) { +#' # Manually enter the plot parameters +#' drugDoseResponseCurve(concentrations=list(""Experiment 1""=c(.008, .04, .2, 1)), +#' viabilities=list(c(100,50,30,1)), plot.type=""Both"") +#' +#' # Generate a plot from one or more PSets +#' data(GDSCsmall) +#' drugDoseResponseCurve(drug=""Doxorubicin"", cellline=""22RV1"", pSets=GDSCsmall) +#' } +#' +#' @param drug `character(1)` A drug name for which the drug response curve should be +#' plotted. If the plot is desirable for more than one pharmaco set, A unique drug id +#' should be provided. +#' @param cellline `character(1)` A cell line name for which the drug response curve should be +#' plotted. If the plot is desirable for more than one pharmaco set, A unique cell id +#' should be provided. +#' @param pSets `list` a list of PharmacoSet objects, for which the function +#' should plot the curves. +#' @param concentrations,viabilities `list` A list of concentrations and viabilities to plot, the function assumes that +#' `concentrations[[i]]` is plotted against `viabilities[[i]]`. The names of the concentration list are used to create the legend labels +#' @param conc_as_log `logical`, if true, assumes that log10-concentration data has been given rather than concentration data, +#' and that log10(ICn) should be returned instead of ICn. Applies only to the concentrations parameter. +#' @param viability_as_pct `logical`, if false, assumes that viability is given as a decimal rather +#' than a percentage, and that E_inf passed in as decimal. Applies only to the viabilities parameter. +#' @param legends.label `numeric` A vector of sensitivity measurment types which could +#' be any combination of ic50_published, auc_published, auc_recomputed and auc_recomputed_star. +#' A legend will be displayed on the top right of the plot which each line of the legend is +#' the values of requested sensitivity measerments for one of the requested pSets. +#' If this parameter is missed no legend would be provided for the plot. +#' @param ylim `numeric` A vector of two numerical values to be used as ylim of the plot. +#' If this parameter would be missed c(0,100) would be used as the ylim of the plot. +#' @param xlim `numeric` A vector of two numerical values to be used as xlim of the plot. +#' If this parameter would be missed the minimum and maximum comncentrations between all +#' the pSets would be used as plot xlim. +#' @param mycol `numeric` A vector with the same lenght of the pSets parameter which +#' will determine the color of the curve for the pharmaco sets. If this parameter is +#' missed default colors from Rcolorbrewer package will be used as curves color. +#' @param plot.type `character` Plot type which can be the actual one (""Actual"") or +#' the one fitted by logl logistic regression (""Fitted"") or both of them (""Both""). +#' If this parameter is missed by default actual curve is plotted. +#' @param summarize.replicates `character` If this parameter is set to true replicates +#' are summarized and replicates are plotted individually otherwise +#' @param title `character` The title of the graph. If no title is provided, then it defaults to +#' 'Drug':'Cell Line'. +#' @param lwd `numeric` The line width to plot with +#' @param cex `numeric` The cex parameter passed to plot +#' @param cex.main `numeric` The cex.main parameter passed to plot, controls the size of the titles +#' @param legend.loc And argument passable to xy.coords for the position to place the legend. +#' @param trunc `logical(1)` Should the viability values be truncated to lie in \[0-100\] before doing the fitting +#' @param verbose `logical(1)` Should warning messages about the data passed in be printed? +#' @param sample_col `character(1)` The name of the column in the profiles assay that contains the sample IDs. +#' @param treatment_col `character(1)` The name of the column in the profiles assay that contains the treatment IDs. +#' +#' @return Plots to the active graphics device and returns an invisible NULL. +#' +#' @import RColorBrewer +#' +#' @importFrom graphics plot rect points lines legend +#' @importFrom grDevices rgb +# # ' @importFrom magicaxis magaxis +#' @importFrom CoreGx .getSupportVec +#' +#' @export +drugDoseResponseCurve <- +function(drug, + cellline, + pSets=list(), + concentrations=list(), + viabilities=list(), + conc_as_log = FALSE, + viability_as_pct = TRUE, + trunc=TRUE, + legends.label = c(""ic50_published"", ""gi50_published"",""auc_published"",""auc_recomputed"",""ic50_recomputed""), + ylim=c(0,100), + xlim, mycol, + title, + plot.type=c(""Fitted"",""Actual"", ""Both""), + summarize.replicates=TRUE, + lwd = 0.5, + cex = 0.7, + cex.main = 0.9, + legend.loc = ""topright"", + verbose=TRUE, + sample_col = ""sampleid"", + treatment_col = ""treatmentid"") { + if(!missing(pSets)){ + if (!is(pSets, ""list"")) { + if (is(pSets, ""PharmacoSet"")) { + temp <- name(pSets) + pSets <- list(pSets) + names(pSets) <- temp + } else { + stop(""Type of pSets parameter should be either a pSet or a list of pSets."") + } + } + } + if(!missing(pSets) && (missing(drug) || missing(cellline))){ + stop(""If you pass in a pSet then drug and cellline must be set"") } + # } else { + # if(missing(drug)){ + # drug <- ""Drug""} + # if(missing(cellline)) + # cellline <- ""Cell Line"" + # } + if(!missing(concentrations)){ + if(missing(viabilities)){ + + stop(""Please pass in the viabilities to Plot with the concentrations."") + + } + if (!is(concentrations, ""list"")) { + if (mode(concentrations) == ""numeric"") { + if(mode(viabilities)!=""numeric""){ + stop(""Passed in 1 vector of concentrations but the viabilities are not numeric!"") + } + cleanData <- sanitizeInput(concentrations, + viabilities, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + concentrations <- 10^cleanData[[""log_conc""]] + concentrations <- list(concentrations) + viabilities <- 100*cleanData[[""viability""]] + viabilities <- list(viabilities) + names(concentrations) <- ""Exp1"" + names(viabilities) <- ""Exp1"" + } else { + stop(""Mode of concentrations parameter should be either numeric or a list of numeric vectors"") + } + } else{ + if(length(viabilities)!= length(concentrations)){ + stop(""The number of concentration and viability vectors passed in differs"") + } + if(is.null(names(concentrations))){ + names(concentrations) <- paste(""Exp"", seq_len(length(concentrations))) + } + for(i in seq_len(length(concentrations))){ + + if (mode(concentrations[[i]]) == ""numeric"") { + if(mode(viabilities[[i]])!=""numeric""){ + stop(sprintf(""concentrations[[%d]] are numeric but the viabilities[[%d]] are not numeric!"",i,i)) + } + cleanData <- sanitizeInput(concentrations[[i]], + viabilities[[i]], + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + concentrations[[i]] <- 10^cleanData[[""log_conc""]] + viabilities[[i]] <- 100*cleanData[[""viability""]] + } else { + stop(sprintf(""Mode of concentrations[[%d]] parameter should be numeric"",i)) + } + + } + + } + } + + if (missing(plot.type)) { + plot.type <- ""Actual"" + } + + if(is(treatmentResponse(pSets[[1]]), ""LongTable"")){ + pSets[[1]] <- subsetByTreatment(pSets[[1]], treatments=drug) + } + pSets[[1]] <- subsetBySample(pSets[[1]], samples=cellline) + + doses <- list(); responses <- list(); legend.values <- list(); j <- 0; pSetNames <- list() + if(!missing(pSets)){ + for(i in seq_len(length(pSets))) { + exp_i <- which(sensitivityInfo(pSets[[i]])[ ,sample_col] == cellline & sensitivityInfo(pSets[[i]])[ ,treatment_col] == drug) + if(length(exp_i) > 0) { + if (summarize.replicates) { + pSetNames[[i]] <- name(pSets[[i]]) + drug.responses <- as.data.frame(cbind(""Dose""=as.numeric(as.vector(sensitivityRaw(pSets[[i]])[exp_i, , ""Dose""])), + ""Viability""=as.numeric(as.vector(sensitivityRaw(pSets[[i]])[exp_i, , ""Viability""]))), stringsAsFactors=FALSE) + drug.responses <- drug.responses[complete.cases(drug.responses), ] + # tryCatch( + # drug.responses <- as.data.frame(cbind(""Dose""=as.numeric(as.vector(sensitivityRaw(pSets[[i]])[exp_i, , ""Dose""])), + # ""Viability""=as.numeric(as.vector(sensitivityRaw(pSets[[i]])[exp_i, , ""Viability""]))), stringsAsFactors=FALSE) + # drug.responses <- drug.responses[complete.cases(drug.responses), ] + # , error = function(e) { + # if (length(exp_i) == 1) { + # drug.responses <- as.data.frame(cbind(""Dose""=as.numeric(as.vector(sensitivityRaw(pSets[[i]])[exp_i, , ""Dose""])), + # ""Viability""=as.numeric(as.vector(sensitivityRaw(pSets[[i]])[exp_i, , ""Viability""]))), stringsAsFactors=FALSE) + # drug.responses <- drug.responses[complete.cases(drug.responses), ] + # }else{ + # drug.responses <- as.data.frame(cbind(""Dose""=apply(sensitivityRaw(pSets[[i]])[exp_i, , ""Dose""], 1, function(x){median(as.numeric(x), na.rm=TRUE)}), + # ""Viability""=apply(sensitivityRaw(pSets[[i]])[exp_i, , ""Viability""], 2, function(x){median(as.numeric(x), na.rm=TRUE)})), stringsAsFactors=FALSE) + # drug.responses <- drug.responses[complete.cases(drug.responses), ] + # } + # }) + + + doses[[i]] <- drug.responses$Dose + responses[[i]] <- drug.responses$Viability + names(doses[[i]]) <- names(responses[[i]]) <- seq_len(length(doses[[i]])) + if (!missing(legends.label)) { + if (length(legends.label) > 1) { + legend.values[[i]] <- paste(unlist(lapply(legends.label, function(x){ + sprintf(""%s = %s"", x, round(as.numeric(sensitivityProfiles(pSets[[i]])[exp_i,x]), digits=2)) + })), collapse = "", "") + } else { + legend.values[[i]] <- sprintf(""%s = %s"", legends.label, round(as.numeric(sensitivityProfiles(pSets[[i]])[exp_i, legends.label]), digits=2)) + } + } else { + legend.values[i] <- """" + } + }else { + for (exp in exp_i) { + j <- j + 1 + pSetNames[[j]] <- name(pSets[[i]]) + + drug.responses <- as.data.frame(cbind(""Dose""=as.numeric(as.vector(sensitivityRaw(pSets[[i]])[exp, , ""Dose""])), + ""Viability""=as.numeric(as.vector(sensitivityRaw(pSets[[i]])[exp, , ""Viability""]))), stringsAsFactors=FALSE) + drug.responses <- drug.responses[complete.cases(drug.responses), ] + doses[[j]] <- drug.responses$Dose + responses[[j]] <- drug.responses$Viability + names(doses[[j]]) <- names(responses[[j]]) <- seq_len(length(doses[[j]])) + if (!missing(legends.label)) { + if (length(legends.label) > 1) { + legend.values[[j]] <- paste(unlist(lapply(legends.label, function(x){ + sprintf(""%s = %s"", x, round(as.numeric(sensitivityProfiles(pSets[[i]])[exp, x]), digits=2)) + })), collapse = "", "") + } else { + legend.values[[j]] <- sprintf("" Exp %s %s = %s"", rownames(sensitivityInfo(pSets[[i]]))[exp], legends.label, round(as.numeric(sensitivityProfiles(pSets[[i]])[exp, legends.label]), digits=2)) + } + } else { + tt <- unlist(strsplit(rownames(sensitivityInfo(pSets[[i]]))[exp], split=""_"")) + if (tt[1] == treatment_col) { + legend.values[[j]] <- tt[2] + }else{ + legend.values[[j]] <- rownames(sensitivityInfo(pSets[[i]]))[exp] + } + } + } + } + } else { + warning(""The cell line and drug combo were not tested together. Aborting function."") + return() + } + } + } + + if(!missing(concentrations)){ + doses2 <- list(); responses2 <- list(); legend.values2 <- list(); j <- 0; pSetNames2 <- list(); + for (i in seq_len(length(concentrations))){ + doses2[[i]] <- concentrations[[i]] + responses2[[i]] <- viabilities[[i]] + if(length(legends.label)>0){ + if(any(grepl(""AUC"", x=toupper(legends.label)))){ + legend.values2[[i]] <- paste(legend.values2[i][[1]],sprintf(""%s = %s"", ""AUC"", round(computeAUC(concentrations[[i]],viabilities[[i]], conc_as_log=FALSE, viability_as_pct=TRUE)/100, digits=2)), sep="", "") + } + if(any(grepl(""IC50"", x=toupper(legends.label)))){ + legend.values2[[i]] <- paste(legend.values2[i][[1]],sprintf(""%s = %s"", ""IC50"", round(computeIC50(concentrations[[i]],viabilities[[i]], conc_as_log=FALSE, viability_as_pct=TRUE), digits=2)), sep="", "") + } + + } else{ legend.values2[[i]] <- """"} + + pSetNames2[[i]] <- names(concentrations)[[i]] + } + doses <- c(doses, doses2) + responses <- c(responses, responses2) + legend.values <- c(legend.values, legend.values2) + pSetNames <- c(pSetNames, pSetNames2) + } + + if (missing(mycol)) { + # require(RColorBrewer) || stop(""Library RColorBrewer is not available!"") + mycol <- RColorBrewer::brewer.pal(n=7, name=""Set1"") + } + + dose.range <- c(10^100 , 0) + viability.range <- c(0 , 10) + for(i in seq_len(length(doses))) { + dose.range <- c(min(dose.range[1], min(doses[[i]], na.rm=TRUE), na.rm=TRUE), max(dose.range[2], max(doses[[i]], na.rm=TRUE), na.rm=TRUE)) + viability.range <- c(0, max(viability.range[2], max(responses[[i]], na.rm=TRUE), na.rm=TRUE)) + } + x1 <- 10 ^ 10; x2 <- 0 + + if(length(doses) > 1) { + common.ranges <- .getCommonConcentrationRange(doses) + + for(i in seq_len(length(doses))) { + x1 <- min(x1, min(common.ranges[[i]])) + x2 <- max(x2, max(common.ranges[[i]])) + } + } + if (!missing(xlim)) { + dose.range <- xlim + } + if (!missing(ylim)) { + viability.range <- ylim + } + if(missing(title)){ + if(!missing(drug)&&!missing(cellline)){ + title <- sprintf(""%s:%s"", drug, cellline) + } else { + title <- ""Drug Dose Response Curve"" + } + + } + plot(NA, xlab=""Concentration (uM)"", ylab=""% Viability"", axes =FALSE, main=title, log=""x"", ylim=viability.range, xlim=dose.range, cex=cex, cex.main=cex.main) + magicaxis::magaxis(side=seq_len(2), frame.plot=TRUE, tcl=-.3, majorn=c(5,3), minorn=c(5,2)) + legends <- NULL + legends.col <- NULL + if (length(doses) > 1) { + rect(xleft=x1, xright=x2, ybottom=viability.range[1] , ytop=viability.range[2] , col=rgb(240, 240, 240, maxColorValue = 255), border=FALSE) + } + + for (i in seq_len(length(doses))) { + points(doses[[i]],responses[[i]],pch=20,col = mycol[i], cex=cex) + + switch(plot.type , ""Actual""={ + lines(doses[[i]], responses[[i]], lty=1, lwd=lwd, col=mycol[i]) + }, ""Fitted""={ + log_logistic_params <- logLogisticRegression(conc=doses[[i]], viability=responses[[i]]) + log10_x_vals <- .getSupportVec(log10(doses[[i]])) + lines(10 ^ log10_x_vals, .Hill(log10_x_vals, pars=c(log_logistic_params$HS, log_logistic_params$E_inf/100, log10(log_logistic_params$EC50))) * 100 ,lty=1, lwd=lwd, col=mycol[i]) + },""Both""={ + lines(doses[[i]],responses[[i]],lty=1,lwd=lwd,col = mycol[i]) + log_logistic_params <- logLogisticRegression(conc = doses[[i]], viability = responses[[i]]) + log10_x_vals <- .getSupportVec(log10(doses[[i]])) + lines(10 ^ log10_x_vals, .Hill(log10_x_vals, pars=c(log_logistic_params$HS, log_logistic_params$E_inf/100, log10(log_logistic_params$EC50))) * 100 ,lty=1, lwd=lwd, col=mycol[i]) + }) + legends<- c(legends, sprintf(""%s%s"", pSetNames[[i]], legend.values[[i]])) + legends.col <- c(legends.col, mycol[i]) + } + + legend(legend.loc, legend=legends, col=legends.col, bty=""n"", cex=cex, pch=c(15,15)) + return(invisible(NULL)) +} + +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/rankGeneDrugSensitivity.R",".R","6686","162","#' @importFrom stats complete.cases +#' @importFrom stats p.adjust + +################################################# +## Rank genes based on drug effect in the Connectivity Map +## +## inputs: +## - data: gene expression data matrix +## - drugpheno: sensititivity values fo thr drug of interest +## - type: cell or tissue type for each experiment +## - duration: experiment duration in hours +## - batch: experiment batches +## - single.type: Should the statitsics be computed for each cell/tissue type separately? +## - nthread: number of parallel threads (bound to the maximum number of cores available) +## +## outputs: +## list of datafraes with the statistics for each gene, for each type +## +## Notes: duration is not taken into account as only 4 perturbations lasted 12h, the other 6096 lasted 6h +################################################# + +rankGeneDrugSensitivity <- function (data, drugpheno, type, batch, + single.type=FALSE, standardize = ""SD"", + nthread=1, verbose=FALSE, + modeling.method = c(""anova"", ""pearson""), + inference.method = c(""analytic"", ""resampling""), req_alpha = 0.05) { + + if (nthread != 1) { + availcore <- parallel::detectCores() + if ((missing(nthread) || nthread < 1 || nthread > availcore) && verbose) { + warning(""nthread undefined, negative or larger than available cores. Resetting to maximum number of cores."") + nthread <- availcore + } + } + + modeling.method <- match.arg(modeling.method) + inference.method <- match.arg(inference.method) + + if(modeling.method == ""anova"" && inference.method == ""resampling"") { + stop(""Resampling based inference for anova model is not yet implemented."") + } + + if(is.null(dim(drugpheno))){ + + drugpheno <- data.frame(drugpheno) + + } else if(!is(drugpheno, ""data.frame"")) { + drugpheno <- as.data.frame(drugpheno) + + } + + if (missing(type) || all(is.na(type))) { + type <- array(""other"", dim=nrow(data), dimnames=list(rownames(data))) + } + if (missing(batch) || all(is.na(batch))) { + batch <- array(1, dim=nrow(data), dimnames=list(rownames(data))) + } + if (any(c(nrow(drugpheno), length(type), length(batch)) != nrow(data))) { + stop(""length of drugpheno, type, duration, and batch should be equal to the number of rows of data!"") + } + rownames(drugpheno) <- names(type) <- names(batch) <- rownames(data) + + res <- NULL + utype <- sort(unique(as.character(type))) + ltype <- list(""all""=utype) + if (single.type) { + ltype <- c(ltype, as.list(utype)) + names(ltype)[-1] <- utype + } + res <- NULL + ccix <- complete.cases(data, type, batch, drugpheno) + nn <- sum(ccix) + + + if(modeling.method == ""anova""){ + if(!any(unlist(lapply(drugpheno,is.factor)))){ + if(ncol(drugpheno)>1){ + ##### FIX NAMES!!! This is important + nc <- lapply(seq_len(ncol(drugpheno)), function(i){ + + est <- paste(""estimate"", i, sep=""."") + se <- paste(""se"", i, sep=""."") + tstat <- paste(""tstat"", i, sep=""."") + + nc <- c(est, se, tstat) + return(nc) + + }) + nc <- c(nc, n=nn, ""fstat""=NA, ""pvalue""=NA, ""fdr"") + } else { + nc <- c(""estimate"", ""se"", ""n"", ""tstat"", ""fstat"", ""pvalue"", ""df"", ""fdr"") + } + } else { + nc <- c(""estimate"", ""se"", ""n"", ""tstat"", ""fstat"", ""pvalue"", ""df"", ""fdr"") + } + } else if (modeling.method == ""pearson"") { + nc <- c(""estimate"", ""n"", ""df"", ""significant"", ""pvalue"", ""lower"", ""upper"") + } + + for (ll in seq_len(length(ltype))) { + iix <- !is.na(type) & is.element(type, ltype[[ll]]) + # ccix <- complete.cases(data[iix, , drop=FALSE], drugpheno[iix,,drop=FALSE], type[iix], batch[iix]) ### HACK??? + + ccix <- rowSums(!is.na(data)) > 0 | rowSums(!is.na(drugpheno)) > 0 | is.na(type) | is.na(batch) + ccix <- ccix[iix] + # ccix <- !vapply(seq_len(NROW(data[iix,,drop=FALSE])), function(x) { + # return(all(is.na(data[iix,,drop=FALSE][x,])) || all(is.na(drugpheno[iix,,drop=FALSE][x,])) || all(is.na(type[iix][x])) || all(is.na(batch[iix][x]))) + # }, FUN.VALUE=logical(1)) + + if (sum(ccix) < 3) { + ## not enough experiments + rest <- list(matrix(NA, nrow=ncol(data), ncol=length(nc), dimnames=list(colnames(data), nc))) + res <- c(res, rest) + } else { + # splitix <- parallel::splitIndices(nx=ncol(data), ncl=nthread) + # splitix <- splitix[vapply(splitix, length, FUN.VALUE=numeric(1)) > 0] + mcres <- parallel::mclapply(seq_len(ncol(data)), function(x, data, type, batch, drugpheno, standardize, modeling.method, inference.method, req_alpha) { + if(modeling.method == ""anova""){ + res <- t(apply(data[ , x, drop=FALSE], 2, geneDrugSensitivity, type=type, batch=batch, drugpheno=drugpheno, verbose=verbose, standardize=standardize)) + } else if(modeling.method == ""pearson"") { + if(!is.character(data)){ + res <- t(apply(data[ , x, drop=FALSE], 2, geneDrugSensitivityPCorr, + type=type, + batch=batch, + drugpheno=drugpheno, + verbose=verbose, + test=inference.method, + req_alpha = req_alpha)) + } else { + res <- t(apply(data[ , x, drop=FALSE], 2, function(dataIn) { + geneDrugSensitivityPBCorr(as.factor(dataIn), + type=type, + batch=batch, + drugpheno=drugpheno, + verbose=verbose, + test=inference.method, + req_alpha = req_alpha)})) + } + + } + + + return(res) + }, data=data[iix, , drop=FALSE], + type=type[iix], batch=batch[iix], + drugpheno=drugpheno[iix,,drop=FALSE], + standardize=standardize, + modeling.method = modeling.method, + inference.method = inference.method, + req_alpha = req_alpha, mc.cores = nthread, mc.preschedule = TRUE) + rest <- do.call(rbind, mcres) + rest <- cbind(rest, ""fdr""=p.adjust(rest[ , ""pvalue""], method=""fdr"")) + # rest <- rest[ , nc, drop=FALSE] + res <- c(res, list(rest)) + } + } + names(res) <- names(ltype) + return(res) +} + +## End +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/filterNoisyCurves.R",".R","2916","74","#' Viability measurements in dose-reponse curves must remain stable or decrease +#' monotonically reflecting response to the drug being tested. +#' filterNoisyCurves flags dose-response curves that strongly violate these +#' assumptions. +#' +#' @examples +#' data(GDSCsmall) +#' filterNoisyCurves(GDSCsmall) +#' +#' @param pSet [PharmacoSet] a PharmacoSet object +#' @param epsilon `numeric` a value indicates assumed threshold for the +#' distance between to consecutive viability values on the drug-response curve +#' in the analysis, out of dna, rna, rnaseq, snp, cnv +#' @param positive.cutoff.percent `numeric` This value indicates that function +#' may violate epsilon rule for how many points on drug-response curve +#' @param mean.viablity `numeric` average expected viability value +#' @param nthread `numeric` if multiple cores are available, how many cores +#' should the computation be parallelized over? +#' +#' @return a list with two elements 'noisy' containing the rownames of the +#' noisy curves, and 'ok' containing the rownames of the non-noisy curves +#' +#' @export +filterNoisyCurves <- function(pSet, epsilon=25 , positive.cutoff.percent=.80, + mean.viablity=200, nthread=1) { + + acceptable <- mclapply(rownames(sensitivityInfo(pSet)), function(xp) { + #for(xp in rownames(sensitivityInfo(pSet))){ + drug.responses <- as.data.frame(apply(sensitivityRaw(pSet)[xp , ,], 2, as.numeric), stringsAsFactors=FALSE) + drug.responses <- drug.responses[complete.cases(drug.responses), ] + doses.no <- nrow(drug.responses) + + drug.responses[, ""delta""] <- .computeDelta(drug.responses$Viability) + + delta.sum <- sum(drug.responses$delta, na.rm = TRUE) + + max.cum.sum <- .computeCumSumDelta(drug.responses$Viability) + + if ( + (table(drug.responses$delta < epsilon)[""TRUE""] >= + (doses.no * positive.cutoff.percent)) & + (delta.sum < epsilon) & + (max.cum.sum < (2 * epsilon)) & + (mean(drug.responses$Viability) < mean.viablity) + ) { + return (xp) + } + }, mc.cores=nthread) + acceptable <- unlist(acceptable) + noisy <- setdiff(rownames(sensitivityInfo(pSet)), acceptable) + return(list(""noisy""=noisy, ""ok""=acceptable)) +} + +.computeDelta <- function(xx, trunc = TRUE) { + xx <- as.numeric(xx) + if (trunc) { + return(c(pmin(100, xx[seq(2,length(xx))]) - pmin(100, xx[seq_along(xx)-1]), 0)) + } else { + return(c(xx[seq(2, length(xx))] - xx[seq_along(xx) - 1]), 0) + } +} + +#' @importFrom utils combn +.computeCumSumDelta <- function(xx, trunc = TRUE) { + xx <- as.numeric(xx) + if(trunc) { + xx <- pmin(xx, 100) + } + tt <- t(combn(seq_along(xx), 2 , simplify = TRUE)) + tt <- tt[which(((tt[,2] - tt[,1]) >= 2) == TRUE),] + cum.sum <- unlist(lapply(seq_len(nrow(tt)), function(x) { xx[tt[x, 2]] - xx[tt[x, 1]]})) + return(max(cum.sum)) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/RcppExports.R",".R","2705","41","# Generated by using Rcpp::compileAttributes() -> do not edit by hand +# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 + +#' QUICKSTOP significance testing for partial correlation +#' +#' This function will test whether the observed partial correlation is significant +#' at a level of req_alpha, doing up to MaxIter permutations. Currently, it +#' supports only grouping by discrete categories when calculating a partial correlation. +#' Currenlty, only does two sided tests. +#' +#' @param pin_x one of the two vectors to correlate. +#' @param pin_y the other vector to calculate +#' @param pobsCor the observed (partial) correlation between these varaiables +#' @param pGroupFactor an integer vector labeling group membership, to correct +#' for in the partial correlation. NEEDS TO BE ZERO BASED! +#' @param pGroupSize an integer vector of size length(unique(pGroupFactor)), counting +#' the number of members of each group (basically table(pGroupFactor)) as integer vector +#' @param pnumGroup how many groups are there (len(pGroupSize)) +#' @param pMaxIter maximum number of iterations to do, as a REAL NUMBER +#' @param pn length of x and y, as a REAL NUMBER +#' @param preq_alpha the required alpha for significance +#' @param ptolerance_par the tolerance region for quickstop. Suggested to be 1/100th of req_alpha' +#' @param plog_decision_boundary log (base e) of 1/probability of incorrectly calling significance, as +#' per quickstop paper (used to determine the log-odds) +#' @param pseed A numeric vector of length 2, used to seed the internal xoroshiro128+ 1.0 +#' random number generator. Note that currently, these values get modified per call, so pass in a copy +#' if you wish to keep a seed for running same simulation twice +#' +#' @return a double vector of length 4, entry 1 is either 0, 1 (for TRUE/FALSE) or NA_REAL_ for significance determination +#' NA_REAL_ is returned when the MaxIter were reached before a decision is made. Usually, this occurs when the real p value is close to, or +#' falls within the tolerance region of (req_alpha, req_alpha+tolerance_par). Entry 2 is the current p value estimate. entry 3 is the total +#' number of iterations performed. Entry 4 is the number of time a permuted value was larger in absolute value than the observed cor. +#' +#' @useDynLib PharmacoGx _PharmacoGx_partialCorQUICKSTOP +#' +#' +partialCorQUICKSTOP <- function(pin_x, pin_y, pobsCor, pGroupFactor, pGroupSize, pnumGroup, pMaxIter, pn, preq_alpha, ptolerance_par, plog_decision_boundary, pseed) { + .Call('_PharmacoGx_partialCorQUICKSTOP', PACKAGE = 'PharmacoGx', pin_x, pin_y, pobsCor, pGroupFactor, pGroupSize, pnumGroup, pMaxIter, pn, preq_alpha, ptolerance_par, plog_decision_boundary, pseed) +} + +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/geneDrugSensitivityPCorr.R",".R","12114","321"," +cor.boot <- function(data, w){ + ddd <- data[w,] + ## A question here is what to do when our bootstrap sample has 0 variance in one of + ## the two variables (usually the molecular feature) + ## If we return NA, we effectively condition on a sampling procedure that samples at least + ## one expressor. If we return near 0 (the default of coop::pcor), then we effectively say that conditioned + ## on not sampling any expressors, there is no association. Neither is correct, but the latter is certainly more + ## conservative. We probably want to use a completely different model to discover ""rare"" biomarkers + ## We will go with the later conservative option, however we will set it to zero exactly instead of relying on + ## the behaviour of coop. + + if(length(unique(ddd[,1]))<2 || length(unique(ddd[,2]))<2){ + return(0) + } + + return(coop::pcor(ddd[,1], ddd[,2])) +} + + +#' Calculate The Gene Drug Sensitivity +#' +#' This version of the function uses a partial correlation instead of standardized linear models. +#' +#' @param x A \code{numeric} vector of gene expression values +#' @param type A \code{vector} of factors specifying the cell lines or type types +#' @param batch A \code{vector} of factors specifying the batch +#' @param drugpheno A \code{numeric} vector of drug sensitivity values (e.g., +#' IC50 or AUC) +#' @param test A \code{character} string indicating whether resampling or analytic based tests should be used +#' @param req_alpha \code{numeric}, number of permutations for p value calculation +#' @param nBoot \code{numeric}, number of bootstrap resamplings for confidence interval estimation +#' @param conf.level \code{numeric}, between 0 and 1. Size of the confidence interval required +#' @param max_perm \code{numeric} the maximum number of permutations that QUICKSTOP can do before giving up and returning NA. +#' Can be set globally by setting the option ""PharmacoGx_Max_Perm"", or left at the default of \code{ceiling(1/req_alpha*100)}. +#' @param verbose \code{boolean} Should the function display messages? +#' +#' @return A \code{vector} reporting the effect size (estimateof the coefficient +#' of drug concentration), standard error (se), sample size (n), t statistic, +#' and F statistics and its corresponding p-value. +#' +#' @examples +#' print(""TODO::"") +#' +#' @importFrom stats sd complete.cases lm glm anova pf formula var pt qnorm cor residuals runif +#' @importFrom boot boot boot.ci +#' @importFrom coop pcor +geneDrugSensitivityPCorr <- function(x, type, batch, drugpheno, + test = c(""resampling"", ""analytic""), + req_alpha = 0.05, + nBoot = 1e3, + conf.level = 0.95, + max_perm = getOption(""PharmacoGx_Max_Perm"", ceiling(1/req_alpha*100)), + verbose=FALSE) { + + test <- match.arg(test) + + colnames(drugpheno) <- paste(""drugpheno"", seq_len(ncol(drugpheno)), sep=""."") + + drugpheno <- data.frame(vapply(drugpheno, function(x) { + if (!is.factor(x)) { + x[is.infinite(x)] <- NA + } + return(list(x)) + }, USE.NAMES=TRUE, + FUN.VALUE=list(1)), check.names=FALSE) + + + ccix <- complete.cases(x, type, batch, drugpheno) + nn <- sum(ccix) + + rest <- c(""estimate""=NA_real_, ""n""=as.numeric(nn), ""df""=NA_real_, significant = NA_real_,""pvalue""=NA_real_, ""lower"" = NA_real_, ""upper"" = NA_real_) + + if(nn <= 3 || isTRUE(all.equal(var(x[ccix], na.rm=TRUE), 0))) { + ## not enough samples with complete information or no variation in gene expression + return(rest) + } + + drugpheno <- drugpheno[ccix,,drop=FALSE] + + + xx <- x[ccix] + + if(ncol(drugpheno)>1){ + stop(""Partial Correlations not implemented for multiple output"") + } else { + ffd <- ""drugpheno.1 ~ . - x"" + ffx <- ""x ~ . - drugpheno.1"" + } + + # ff1 <- sprintf(""%s + x"", ff0) + + dd <- data.frame(drugpheno, ""x""=xx) + + ## control for tissue type + if(length(sort(unique(type[ccix]))) > 1) { + dd <- cbind(dd, type=type[ccix]) + } + ## control for batch + if(length(sort(unique(batch[ccix]))) > 1) { + dd <- cbind(dd, batch=batch[ccix]) + } + ## control for duration + # if(length(sort(unique(duration))) > 1){ + # ff0 <- sprintf(""%s + duration"", ff0) + # ff <- sprintf(""%s + duration"", ff) + # } + + # if(is.factor(drugpheno[,1])){ + + # drugpheno <- drugpheno[,1] + + # } else { + + # drugpheno <- as.matrix(drugpheno) + + # } + if(any(unlist(lapply(drugpheno,is.factor)))){ + + stop(""Currently only continous output allowed for partial correlations"") + + + } else { + + if(ncol(dd) > 2){ + lm1 <- lm(formula(ffd), dd) + var1 <- residuals(lm1) + var2 <- residuals(lm(formula(ffx), dd)) + df <- lm1$df - 2L # taking the residual degrees of freedom minus 2 parameters estimated for pearson cor. + } else { ## doing this if statement in the case there are some numerical differences between mean centred values and raw values + var1 <- dd[,""drugpheno.1""] + var2 <- dd[,""x""] + df <- nn - 2L + } + + obs.cor <- coop::pcor(var1, var2, use=""complete.obs"") + + + ## NB: just permuting the residuals would leads to Type I error inflation, + ## from an underestimation due to ignoring variance in the effects of the covariates. + ## See: https://www.tandfonline.com/doi/abs/10.1080/00949650008812035 + ## Note that the above paper does not provide a single method recommended in all cases + ## We apply the permutation of raw data method, as it is most robust to small sample sizes + if(test == ""resampling""){ + ## While the logic is equivalent regardless of if there are covariates for calculating the point estimate, + ## (correlation is a subcase of partial correlation), for computational efficency in permuation testing we + ## split here and don't do extranous calls to lm if it is unnecessay. + + if(ncol(dd) > 2){ + + if(!getOption(""PharmacoGx_useC"")|| ncol(dd)!=3){ ## currently implementing c code only for 1 single grouping variable + + ## implementing a much more efficient method for the particular case where we have 3 columns with assumption that + ## column 3 is the tissue. + if(ncol(dd)==3){ + sample_function <- function(){ + + partial.dp <- sample(dd[,1], nrow(dd)) + partial.x <- sample(dd[,2], nrow(dd)) + + for(gp in unique(dd[,3])){ + partial.x[dd[,3]==gp] <- partial.x[dd[,3]==gp]-mean(partial.x[dd[,3]==gp]) + partial.dp[dd[,3]==gp] <- partial.dp[dd[,3]==gp]-mean(partial.dp[dd[,3]==gp]) + } + + perm.cor <- coop::pcor(partial.dp, partial.x, use=""complete.obs"") + return(abs(obs.cor) < abs(perm.cor)) + } + } else { + sample_function <- function(){ + # browser() + dd2 <- dd + dd2[,1] <- sample(dd[,1], nrow(dd)) + dd2[,2] <- sample(dd[,2], nrow(dd)) + + partial.dp <- residuals(lm(formula(ffd), dd2)) + partial.x <- residuals(lm(formula(ffx), dd2)) + + perm.cor <- coop::pcor(partial.dp, partial.x, use=""complete.obs"") + return(abs(obs.cor) < abs(perm.cor)) + } + } + + p.value <- corPermute(sample_function, req_alpha = req_alpha, max_iter=max_perm) + significant <- p.value$significant + p.value <- p.value$p.value + + + } else { + + x <- dd[,1] + y <- dd[,2] + GR <- as.integer(factor(dd[,3]))-1L + GS <- as.integer(table(factor(dd[,3]))) + NG <- length(table(factor(dd[,3]))) + N <- as.numeric(length(x)) + + p.value <-PharmacoGx:::partialCorQUICKSTOP(x, y, obs.cor, GR, GS, NG, max_perm, N, req_alpha, req_alpha/100, 10L, runif(2)) + significant <- p.value[[1]] + p.value <- p.value[[2]] + } + + + pcor.boot <- function(ddd, w){ + ddd <- ddd[w,] + ## Taking care of an edge case where only one factor level is left after resampling + ## However, we need to keep the first two numeric columns to properly return a value, otherwise + ## if we remove gene expression because there were only non-detected samples, for example, + ## we will try to take the correlation against a character vector. + ddd <- ddd[,c(TRUE, TRUE, apply(ddd[,-c(1,2),drop=FALSE], 2, function(x) return(length(unique(x))))>=2)] + + + ## A question here is what to do when our bootstrap sample has 0 variance in one of + ## the two variables (usually the molecular feature) + ## If we return NA, we effectively condition on a sampling procedure that samples at least + ## one expressor. If we return near 0 (the default of coop::pcor), then we effectively say that conditioned + ## on not sampling any expressors, there is no association. Neither is correct, but the latter is certainly more + ## conservative. We probably want to use a completely different model to discover ""rare"" biomarkers + ## We will go with the later conservative option, however we will set it to zero exactly instead of relying on + ## the behaviour of coop. + + if(length(unique(ddd[,1]))<2 || length(unique(ddd[,2]))<2){ + return(0) + } + + if(ncol(ddd)==3){ + partial.dp <- ddd[,1] + partial.x <- ddd[,2] + for(gp in unique(ddd[,3])){ + partial.x[ddd[,3]==gp] <- partial.x[ddd[,3]==gp]-mean(partial.x[ddd[,3]==gp]) + partial.dp[ddd[,3]==gp] <- partial.dp[ddd[,3]==gp]-mean(partial.dp[ddd[,3]==gp]) + } + + } else if(ncol(ddd)==2){ + partial.dp <- ddd[,1] + partial.x <- ddd[,2] + } else { + + partial.dp <- residuals(lm(formula(ffd), ddd)) + partial.x <- residuals(lm(formula(ffx), ddd)) + + } + + return(coop::pcor(partial.dp, partial.x, use=""complete.obs"")) + } + + boot.out <- boot(dd, pcor.boot, R=nBoot) + cint <- tryCatch(boot.ci(boot.out, conf = conf.level, type=""bca"")$bca[,4:5], + error = function(e) { + if(e$message == ""estimated adjustment 'w' is infinite""){ + warning(""estimated adjustment 'w' is infinite for some features"") + return(c(NA_real_,NA_real_)) + } else { + stop(e) + } + }) + } else { + if(!getOption(""PharmacoGx_useC"")){ + sample_function <- function(){ + v1 <- sample(var1) + return(abs(obs.cor) < abs(coop::pcor(v1, var2, use=""complete.obs""))) + } + + p.value <- corPermute(sample_function, req_alpha = req_alpha, max_iter=max_perm) + significant <- p.value$significant + p.value <- p.value$p.value + } else { + + x <- as.numeric(var1) + y <- as.numeric(var2) + GR <- rep(0L, length(x)) + GS <- as.integer(length(x)) + NG <- 1L + N <- as.numeric(length(x)) + + p.value <-PharmacoGx:::partialCorQUICKSTOP(x, y, obs.cor, GR, GS, NG, max_perm, N, req_alpha, req_alpha/100, 10L, runif(2)) + significant <- p.value[[1]] + p.value <- p.value[[2]] + } + + + + + boot.out <- boot(data.frame(var1, var2), cor.boot, R=nBoot) + cint <- tryCatch(boot.ci(boot.out, conf = conf.level, type=""bca"")$bca[,4:5], + error = function(e) { + if(e$message == ""estimated adjustment 'w' is infinite"" || e$message == ""Error in if (const(t, min(1e-08, mean(t, na.rm = TRUE)/1e+06))) { : \n missing value where TRUE/FALSE needed\n""){ + warning(""estimated adjustment 'w' is infinite for some features"") + return(c(NA_real_,NA_real_)) + } else { + stop(e) + } + }) + } + + +} else if(test == ""analytic""){ + # if(ncol(dd) > 2){ + # df <- nn - 2L - controlled.var + + # } else { + # df <- nn - 2L + # # cor.test.res <- cor.test(dd[,""drugpheno.1""], dd[,""x""], method=""pearson"", use=""complete.obs"") + # } + stat <- sqrt(df) * obs.cor/sqrt(1-obs.cor^2) ## Note, this is implemented in same order of operations as cor.test + p.value <- 2*min(pt(stat, df=df), pt(stat, df=df, lower.tail = FALSE)) + ## Implementing with fisher transform and normal dist for consistency with R's cor.test + z <- atanh(obs.cor) + sigma <- 1/sqrt(df - 1) + cint <- tanh(z + c(-1, 1) * sigma * qnorm((1 + conf.level)/2)) + significant <- p.value < req_alpha +} + +} + +rest <- c(""estimate""=obs.cor, ""n""=nn, df=df, significant = as.numeric(significant), ""pvalue""=p.value, ""lower"" = cint[1], ""upper"" = cint[2]) + + +return(rest) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeABC.R",".R","5029","119","#' Fits dose-response curves to data given by the user +#' and returns the ABC of the fitted curves. +#' +#' @examples +#' dose1 <- c(0.0025,0.008,0.025,0.08,0.25,0.8,2.53,8) +#' viability1 <- c(108.67,111,102.16,100.27,90,87,74,57) +#' dose2 <- c(0.0025,0.008,0.025,0.08,0.25,0.8,2.53,8) +#' viability2 <- c(100.94,112.5,86,104.16,75,68,48,29) +#' computeABC(dose1, dose2, viability1, viability2) +#' +#' @param conc1 `numeric` is a vector of drug concentrations. +#' @param conc2 `numeric` is a vector of drug concentrations. +#' @param viability1 `numeric` is a vector whose entries are the viability values observed in the presence of the +#' drug concentrations whose logarithms are in the corresponding entries of conc1, expressed as percentages +#' of viability in the absence of any drug. +#' @param viability2 `numeric` is a vector whose entries are the viability values observed in the presence of the +#' drug concentrations whose logarithms are in the corresponding entries of conc2, expressed as percentages +#' of viability in the absence of any drug. +#' @param Hill_fit1 `list` or `vector` In the order: c(""Hill Slope"", ""E_inf"", ""EC50""), the parameters of a Hill Slope +#' as returned by logLogisticRegression. If conc_as_log is set then the function assumes logEC50 is passed in, and if +#' viability_as_pct flag is set, it assumes E_inf is passed in as a percent. Otherwise, E_inf is assumed to be a decimal, +#' and EC50 as a concentration. +#' @param Hill_fit2 `lis` or `vector` In the order: c(""Hill Slope"", ""E_inf"", ""EC50""), the parameters of a Hill Slope +#' as returned by logLogisticRegression. If conc_as_log is set then the function assumes logEC50 is passed in, and if +#' viability_as_pct flag is set, it assumes E_inf is passed in as a percent. Otherwise, E_inf is assumed to be a decimal, +#' and EC50 as a concentration. +#' @param conc_as_log `logical`, if true, assumes that log10-concentration data has been given rather than concentration data. +#' @param viability_as_pct `logical`, if false, assumes that viability is given as a decimal rather +#' than a percentage, and returns ABC as a decimal. Otherwise, viability is interpreted as percent, and AUC is returned 0-100. +#' @param verbose `logical`, if true, causes warnings thrown by the function to be printed. +#' @param trunc `logical`, if true, causes viability data to be truncated to lie between 0 and 1 before +#' curve-fitting is performed. +#' +#' @author Mark Freeman +#' +#' @return The numeric area of the absolute difference between the two hill slopes +#' +#' @importFrom CoreGx .getSupportVec +#' @export +computeABC <- function(conc1, conc2, viability1, viability2, + Hill_fit1, + Hill_fit2, + conc_as_log = FALSE, + viability_as_pct = TRUE, + trunc = TRUE, + verbose=TRUE) { + +if (missing(conc1) | missing(conc2)){ + + stop(""Both Concentration vectors the drugs were tested on must always be provided."") + +} +if (missing(Hill_fit1) | missing(Hill_fit2)) { + + Hill_fit1 <- logLogisticRegression(conc1, + viability1, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + cleanData <- sanitizeInput(conc=conc1, + Hill_fit=Hill_fit1, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + pars1 <- cleanData[[""Hill_fit""]] + log_conc1 <- cleanData[[""log_conc""]] + Hill_fit2 <- logLogisticRegression(conc2, + viability2, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + cleanData <- sanitizeInput(conc=conc2, + Hill_fit=Hill_fit2, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + pars2 <- cleanData[[""Hill_fit""]] + log_conc2 <- cleanData[[""log_conc""]] + +} else { + + cleanData <- sanitizeInput(conc = conc1, + viability = viability1, + Hill_fit = Hill_fit1, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + pars1 <- cleanData[[""Hill_fit""]] + log_conc1 <- cleanData[[""log_conc""]] + cleanData <- sanitizeInput(conc = conc2, + viability = viability2, + Hill_fit = Hill_fit2, + conc_as_log = conc_as_log, + viability_as_pct = viability_as_pct, + trunc = trunc, + verbose = verbose) + pars2 <- cleanData[[""Hill_fit""]] + log_conc2 <- cleanData[[""log_conc""]] +} + + #FIT CURVE AND CALCULATE IC50 + if (max(log_conc1) < min(log_conc2) | max(log_conc2) < min(log_conc1)) { + return(NA) + } else { + extrema <- sort(c(min(log_conc1), max(log_conc1), min(log_conc2), max(log_conc2))) + support <- .getSupportVec(c(extrema[2], extrema[3])) + ABC <- as.numeric(caTools::trapz(support, abs(.Hill(support, pars1) - .Hill(support, pars2))) / (extrema[3] - extrema[2])) + if(viability_as_pct){ + ABC <- ABC*100 + } + return(ABC) + } +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/methods-subsetTo.R",".R","9362","217","# ==== PharmacoSet Class + +## FIXED? TODO:: Subset function breaks if it doesnt find cell line in sensitivity info +#' A function to subset a PharmacoSet to data containing only specified drugs, cells and genes +#' +#' This is the prefered method of subsetting a PharmacoSet. This function allows +#' abstraction of the data to the level of biologically relevant objects: drugs +#' and cells. The function will automatically go through all of the +#' combined data in the PharmacoSet and ensure only the requested drugs +#' and cell lines are found in any of the slots. This allows quickly picking out +#' all the experiments for a drug or cell of interest, as well removes the need +#' to keep track of all the metadata conventions between different datasets. +#' +#' @examples +#' data(CCLEsmall) +#' CCLEdrugs <- treatmentNames(CCLEsmall) +#' CCLEcells <- sampleNames(CCLEsmall) +#' pSet <- subsetTo(CCLEsmall, drugs = CCLEdrugs[1], cells = CCLEcells[1]) +#' pSet +#' +#' @param object A \code{PharmacoSet} to be subsetted +#' @param cells A list or vector of cell names as used in the dataset to which +#' the object will be subsetted. If left blank, then all cells will be left in +#' the dataset. +#' @param drugs A list or vector of drug names as used in the dataset to which +#' the object will be subsetted. If left blank, then all drugs will be left in +#' the dataset. +#' @param molecular.data.cells A list or vector of cell names to keep in the +#' molecular data +#' @param keep.controls If the dataset has perturbation type experiments, should +#' the controls be kept in the dataset? Defaults to true. +#' @param ... Other arguments passed by other function within the package +#' +#' @return A PharmacoSet with only the selected drugs and cells +#' +#' @importMethodsFrom CoreGx subsetTo +#' @export +setMethod('subsetTo', signature(object='PharmacoSet'), function(object, + cells=NULL, drugs=NULL, molecular.data.cells=NULL, keep.controls=TRUE, ...) +{ + .subsetToPharmacoSet(object, cells=cells, drugs=drugs, + molecular.data.cells=molecular.data.cells, keep.controls=keep.controls) +}) + + +#' @importFrom CoreGx .intersectList +#' @keywords internal +.subsetToPharmacoSet <- function(object, cells=NULL, drugs=NULL, + molecular.data.cells=NULL, keep.controls=TRUE, ...) +{ + drop=FALSE #TODO:: Is this supposed to be here? + + adArgs = list(...) + if ('exps' %in% names(adArgs)) { + exps <- adArgs[['exps']] + if(is(exps, 'data.frame')) { + exps2 <- exps[[name(object)]] + names(exps2) <- rownames(exps) + exps <- exps2 + } else{ + exps <- exps[[name(object)]] + } + }else { + exps <- NULL + } + if(!missing(cells)){ + cells <- unique(cells) + } + + if(!missing(drugs)){ + drugs <- unique(drugs) + } + + if(!missing(molecular.data.cells)){ + molecular.data.cells <- unique(molecular.data.cells) + } + + ### TODO:: implement strict subsetting at this level!!!! + ### TODO:: refactor this monstrosity of a function into helpers + + ### the function missing does not work as expected in the context below, because the arguments are passed to the anonymous + ### function in lapply, so it does not recognize them as missing + + molecularProfilesSlot(object) <- lapply(molecularProfilesSlot(object), function(SE, cells, drugs, molecular.data.cells){ + + molecular.data.type <- ifelse(length(grep('rna', S4Vectors::metadata(SE)$annotation) > 0), 'rna', S4Vectors::metadata(SE)$annotation) + if (length(grep(molecular.data.type, names(molecular.data.cells))) > 0) { + cells <- molecular.data.cells[[molecular.data.type]] + } + + column_indices <- NULL + + if (length(cells)==0 && length(drugs)==0) { + column_indices <- seq_len(ncol(SE)) # This still returns the number of samples in an SE, but without a label + } + if(length(cells)==0 && datasetType(object)=='sensitivity') { + column_indices <- seq_len(ncol(SE)) + } + + cell_line_index <- NULL + if(length(cells)!=0) { + if (!all(cells %in% sampleNames(object))) { + stop('Some of the cell names passed to function did not match to names in the PharmacoSet. Please ensure you are using cell names as returned by the cellNames function') + } + cell_line_index <- which(SummarizedExperiment::colData(SE)[[""sampleid""]] %in% cells) + # if (length(na.omit(cell_line_index))==0){ + # stop('No cell lines matched') + # } + } + drugs_index <- NULL + if(datasetType(object)=='perturbation' || datasetType(object)=='both'){ + if(length(drugs) != 0) { + if (!all(drugs %in% treatmentNames(object))){ + stop('Some of the drug names passed to function did not match to names in the PharmacoSet. Please ensure you are using drug names as returned by the drugNames function') + } + drugs_index <- which(SummarizedExperiment::colData(SE)[[""treatmentid""]] %in% drugs) + # if (length(drugs_index)==0){ + # stop('No drugs matched') + # } + if(keep.controls) { + control_indices <- which(SummarizedExperiment::colData(SE)[['xptype']]=='control') + drugs_index <- c(drugs_index, control_indices) + } + } + } + + if(length(drugs_index) != 0 && length(cell_line_index) != 0) { + if(length(intersect(drugs_index, cell_line_index)) == 0) { + stop('This Drug - Cell Line combination was not tested together.') + } + column_indices <- intersect(drugs_index, cell_line_index) + } else { + if(length(drugs_index) !=0) { + column_indices <- drugs_index + } + if(length(cell_line_index) !=0) { + column_indices <- cell_line_index + } + } + + row_indices <- seq_len(nrow(SummarizedExperiment::assay(SE, 1))) + + SE <- SE[row_indices, column_indices] + return(SE) + + }, cells=cells, drugs=drugs, molecular.data.cells=molecular.data.cells) + + if ((datasetType(object) == 'sensitivity' | datasetType(object) == 'both') & length(exps) != 0) { + sensitivityInfo(object) <- sensitivityInfo(object)[exps, , drop=drop] + rownames(sensitivityInfo(object)) <- names(exps) + if(length(sensitivityRaw(object)) > 0) { + sensitivityRaw(object) <- sensitivityRaw(object)[exps, , , drop=drop] + dimnames(sensitivityRaw(object))[[1]] <- names(exps) + } + sensitivityProfiles(object) <- sensitivityProfiles(object)[exps, , drop=drop] + rownames(sensitivityProfiles(object)) <- names(exps) + + sensNumber(object) <- .summarizeSensitivityNumbers(object) + } + else if ((datasetType(object) == 'sensitivity' | datasetType(object) == 'both') & (length(drugs) != 0 | length(cells) != 0)) { + + drugs_index <- which(sensitivityInfo(object)[, ""treatmentid""] %in% drugs) + cell_line_index <- which(sensitivityInfo(object)[,""sampleid""] %in% cells) + if (length(drugs_index) !=0 & length(cell_line_index) !=0 ) { + if (length(intersect(drugs_index, cell_line_index)) == 0) { + stop('This Drug - Cell Line combination was not tested together.') + } + row_indices <- intersect(drugs_index, cell_line_index) + } else { + if(length(drugs_index)!=0 & length(cells)==0) { + row_indices <- drugs_index + } else { + if(length(cell_line_index)!=0 & length(drugs)==0){ + row_indices <- cell_line_index + } else { + row_indices <- vector() + } + } + } + treatmentResponse(object)[names(treatmentResponse(object))[names(treatmentResponse(object))!='n']] <- lapply(treatmentResponse(object)[names(treatmentResponse(object))[names(treatmentResponse(object))!='n']], function(x,i, drop){ + #browser() + if (length(dim(x))==2){ + return(x[i,,drop=drop]) + } + if (length(dim(x))==3){ + return(x[i,,,drop=drop]) + } + }, i=row_indices, drop=drop) + } + + if (length(drugs)==0) { + if(datasetType(object) == 'sensitivity' | datasetType(object) == 'both'){ + drugs <- unique(sensitivityInfo(object)[[""treatmentid""]]) + } + if(datasetType(object) == 'perturbation' | datasetType(object) == 'both'){ + drugs <- union(drugs, na.omit(CoreGx::.unionList(lapply(molecularProfilesSlot(object), function(SE){unique(colData(SE)[[""treatmentid""]])})))) + } + } + if (length(cells)==0) { + cells <- union(cells, na.omit(CoreGx::.unionList(lapply(molecularProfilesSlot(object), function(SE){unique(colData(SE)[[""sampleid""]])})))) + if (datasetType(object) =='sensitivity' | datasetType(object) == 'both'){ + cells <- union(cells, sensitivityInfo(object)[[""sampleid""]]) + } + } + treatmentInfo(object) <- treatmentInfo(object)[drugs, , drop=drop] + sampleInfo(object) <- sampleInfo(object)[cells, , drop=drop] + curation(object)$treatment <- curation(object)$treatment[drugs, , drop=drop] + curation(object)$sample <- curation(object)$sample[cells, , drop=drop] + curation(object)$tissue <- curation(object)$tissue[cells, , drop=drop] + if (datasetType(object) == 'sensitivity' | datasetType(object) == 'both' & length(exps) == 0) { + sensNumber(object) <- sensNumber(object)[cells, drugs, drop=drop] + } + if (datasetType(object) == 'perturbation' | datasetType(object) == 'both') { + pertNumber(object) <- pertNumber(object)[cells, drugs, , drop=drop] + } + return(object) +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/class-SignatureClass.R",".R","3424","86","setOldClass('sessionInfo', sessionInfo) + +#' @importFrom utils sessionInfo +.PharmacoSig <- setClass('PharmacoSig', slots=list( + Arguments = ""list"", + PSetName='character', + DateCreated = 'character', + SigType = 'character', + SessionInfo = 'sessionInfo', + Call = 'character'), contains='array') + + +#' Contructor for the PharmacoSig S4 class +#' +#' @param Data of data to build the signature from +#' @param PSetName `character` vector containing name of PSet, defaults to '' +#' @param DateCreated `date` date the signature was created, defaults to `date()` +#' @param SigType `character` vector specifying whether the signature is sensitivity or perturbation, defaults to 'sensitivity' +#' @param SessionInfo `sessionInfo` object as retuned by `sesssionInfo()` function, defaults to `sessionInfo()` +#' @param Call `character` or `call` specifying the constructor call used to make the object, defaults to 'No Call Recorded' +#' @param Arguments `list` a list of additional arguments to the constructure +#' +#' @return A `PharmacoSig` object build from the provided signature data +#' +#' @examples +#' PharmacoSig() +#' +#' @export +PharmacoSig <- function(Data=array(NA, dim=c(0,0,0)), PSetName='', DateCreated=date(), SigType='sensitivity', + SessionInfo=sessionInfo(), Call='No Call Recorded', Arguments = list()){ + return(.PharmacoSig(Data, Arguments = Arguments, PSetName=PSetName, DateCreated=DateCreated, SigType=SigType, + SessionInfo=SessionInfo, Call=Call)) +} + + +#' Show PharmacoGx Signatures +#' +#' @examples +#' data(GDSCsmall) +#' drug.sensitivity <- drugSensitivitySig(GDSCsmall, mDataType=""rna"", +#' nthread=1, features = fNames(GDSCsmall, ""rna"")[1]) +#' drug.sensitivity +#' +#' @param object \code{PharmacoSig} +#' @return Prints the PharmacoGx Signatures object to the output stream, and returns invisible NULL. +#' @export +setMethod(""show"", signature=signature(object='PharmacoSig'), + function(object) { + cat('PharmacoSet Name: ', attr(object, 'PSetName'), ""\n"") + cat('Signature Type: ', attr(object, 'SigType'), ""\n"") + cat(""Date Created: "", attr(object, 'DateCreated'), ""\n"") + cat(""Number of Drugs: "", dim(object)[[2]], ""\n"") + cat(""Number of Genes/Probes: "", dim(object)[[1]], ""\n"") + }) + + +#' Show the Annotations of a signature object +#' +#' This funtion prints out the information about the call used to compute the drug signatures, and the session info +#' for the session in which the computation was done. Useful for determining the exact conditions used to generate signatures. +#' +#' @examples +#' data(GDSCsmall) +#' drug.sensitivity <- drugSensitivitySig(GDSCsmall, mDataType=""rna"", +#' nthread=1, features = fNames(GDSCsmall, ""rna"")[1]) +#' showSigAnnot(drug.sensitivity) +#' +#' @param object An object of the \code{PharmacoSig} Class, as +#' returned by \code{drugPerturbationSig} or \code{drugSensitivitySig} +#' +#' @return Prints the PharmacoGx Signatures annotations to the output stream, and returns invisible NULL. +#' +#' @importMethodsFrom CoreGx showSigAnnot +#' @export +setMethod(""showSigAnnot"", signature(object=""PharmacoSig""), function(object){ + .showSigAnnotPharmacoSig(object) +}) + + +#' @keywords internal +.showSigAnnotPharmacoSig <- function(object){ + print(object@Call) + print(object@SessionInfo) + return(invisible(NULL)) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/getRawSensitivityMatrix.R",".R","2433","49","##TODO:: Add function documentation +getRawSensitivityMatrix <- + function(pSet, cell.id, drug.id, max.conc, quality) { + cond <- ""sensitivityInfo(pSet)$sampleid == cell.id"" + if(!missing(quality)) { + if(is.element(""quality"", colnames(sensitivityInfo(pSet)))) { + cond <- paste(cond, ""sensitivityInfo(pSet)$quality == quality"", sep="" & "") + } + } + if(!missing(max.conc)) { + if(is.element(""max.conc"", colnames(sensitivityInfo(pSet)))) { + if(length(max.conc) > 1) { + max.conc <- paste(max.conc, collapse=""///"") + } + cond <- paste(cond, ""sensitivityInfo(pSet)$max.conc == max.conc"", sep="" & "") + } + } + if(length(drug.id) > 1) { + drug.id <- paste(drug.id, collapse=""///"") + } + cond <- paste(cond, ""sensitivityInfo(pSet)$treatmentid == drug.id"", sep="" & "") + + exp.id <- which(eval(parse(text=cond))) + + sensitivity.raw.matrix <- list() + if(length(exp.id) > 0) { + for(i in seq_len(length(exp.id))){ + if(length(grep(""///"", drug.id)) > 0) { + all.exp.id <- which(sensitivityInfo(pSet)$combination.exp.id == sensitivityInfo(pSet)[exp.id[i], ""combination.exp.id""]) + drug.1 <- which(sensitivityInfo(pSet)[all.exp.id, ""treatmentid""] == unlist(strsplit(drug.id, split=""///""))[1]) + drug.2 <- which(sensitivityInfo(pSet)[all.exp.id, ""treatmentid""] == unlist(strsplit(drug.id, split=""///""))[2]) + drug.1.doses <- length(which(!is.na(sensitivityRaw(pSet)[all.exp.id[drug.1], , ""Dose""]))) + drug.2.doses <- length(which(!is.na(sensitivityRaw(pSet)[all.exp.id[drug.2], , ""Dose""]))) + + tt <- matrix(NA, ncol=drug.2.doses, nrow=drug.1.doses) + colnames(tt) <- sensitivityRaw(pSet)[all.exp.id[drug.2], seq_len(drug.2.doses), ""Dose""] + rownames(tt) <- sensitivityRaw(pSet)[all.exp.id[drug.1], seq_len(drug.1.doses), ""Dose""] + tt[ ,1] <- sensitivityRaw(pSet)[all.exp.id[drug.1], seq_len(drug.1.doses), ""Viability""] + tt[1, ] <- sensitivityRaw(pSet)[all.exp.id[drug.2], seq_len(drug.2.doses), ""Viability""] + tt[2:nrow(tt), 2:ncol(tt)] <- sensitivityRaw(pSet)[exp.id[i], , ""Viability""] + sensitivity.raw.matrix[[rownames(sensitivityInfo(pSet))[exp.id[i]]]] <- tt + }else{ + sensitivity.raw.matrix[[rownames(sensitivityInfo(pSet))[exp.id[i]]]] <- sensitivityRaw(pSet)[exp.id[i], , ] + } + } + } + return(sensitivity.raw.matrix) + } +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/adaptiveMatthewCor.R",".R","265","11","#' Adaptive Matthews Correlation Coefficient +#' +#' @inherit CoreGx::amcc +#' +#' @examples +#' amcc(0.6^(1:5), 0.5^(1:5)) +#' +#' @export +amcc <- function(x, y, step.prct=0, min.cat=3, nperm=1000, nthread=1) { + CoreGx::amcc(x, y, step.prct, min.cat, nperm, nthread) +}","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/geneDrugSensitivityPBCorr.R",".R","14721","425","log_denom <- function(suc, total, p){ + tmp <- 0; + # if(log10(p)>-32) + # { + tmp <- (suc)*log(p) + # } else { + # warning(""p reached precision threshold"") + # } + # if(log10(1.0-p)>-32) + # { + tmp <- tmp + (total - suc)*log(1 - p) + # } else { + # warning(""1-p reached precision threshold"") + # } + return(tmp) + +} +log_denom <- function(suc, total, p){ + return((suc)*log(p) + (total - suc)*log(1 - p)) + +} + +### Implementing algorithm from quick stop paper + +## decision boundary is inverse of error prob +## do everything in log scale because of numerical precision. +corPermute <- function(sample_function, req_alpha=0.05, tolerance_par = req_alpha*0.001, log_decision_boundary = 10, max_iter = 1/req_alpha*100){ + + num.larger <- 0 + + cur_success <- 0 + cur_iter <- 1 + + log_cur_PiN <- log(1) # Initialization so the logic can stay the same through all loops + + p1 <- req_alpha + p2 <- p1 + tolerance_par + + pr_min_1 <- 1/2 + + while(cur_iter < max_iter){ + # vec1 <- sample(vec1) + # perm.cor <- cor(vec1, vec2, use=""complete.obs"") + + # success <- abs(perm.cor) > abs(obs.cor) + + success <- sample_function() + + if(success){ + cur_success <- cur_success + 1 + log_cur_PiN <- log_cur_PiN + log_denom(1,1,pr_min_1) + } else { + log_cur_PiN <- log_cur_PiN + log_denom(0,1,pr_min_1) + } + # if(pr_min_1 >= p2){ + # log_cur_suph1 <- log_denom(cur_success, cur_iter, p1) + # log_cur_suph2 <- log_denom(cur_success, cur_iter, pr_min_1) + # } else if(pr_min_1 <= p1){ + # log_cur_suph1 <- log_denom(cur_success, cur_iter, pr_min_1) + # log_cur_suph2 <- log_denom(cur_success, cur_iter, p2) + # } else { + # log_cur_suph1 <- log_denom(cur_success, cur_iter, p1) + # log_cur_suph2 <- log_denom(cur_success, cur_iter, p2) + # } + if(pr_min_1p2) { + log_cur_suph2 <- log_denom(cur_success, cur_iter, pr_min_1) + } else { + log_cur_suph2 <- log_denom(cur_success, cur_iter, p2) + } + + cur_iter <- cur_iter + 1 + pr_min_1 <- (cur_success + 1/2)/cur_iter + + # if(cur_success == 0){ + # next + # } + + if(log_cur_PiN - log_cur_suph2 > log_decision_boundary){ + return(list(significant = TRUE, ""p.value"" = pr_min_1, num_iter=cur_iter, num_larger=cur_success)) + } + if(log_cur_PiN - log_cur_suph1 > log_decision_boundary){ + return(list(significant = FALSE, ""p.value"" = pr_min_1, num_iter=cur_iter, num_larger=cur_success)) + } + } + return(list(significant = NA, ""p.value"" = pr_min_1, num_iter=cur_iter, num_larger=cur_success)) +} + + + +## Helper Functions +##TODO:: Add function documentation +#' @importFrom stats quantile +.rescale <- function(x, na.rm=FALSE, q=0) +{ + if(q == 0) { + ma <- max(x, na.rm=na.rm) + mi <- min(x, na.rm=na.rm) + } else { + ma <- quantile(x, probs=1-(q/2), na.rm=na.rm) + mi <- quantile(x, probs=q/2, na.rm=na.rm) + } + xx <- (x - mi) / (ma - mi) + return(xx) +} + +## TODO: decide better what to do with no variance cases. +cor.boot <- function(data, w){ + return(cor(data[w,1], data[w,2])) +} + + +#' Calculate The Gene Drug Sensitivity +#' +#' This version of the function uses a partial correlation instead of standardized linear models, for discrete predictive features +#' Requires at least 3 observations per group. +#' +#' @param x A \code{numeric} vector of gene expression values +#' @param type A \code{vector} of factors specifying the cell lines or type types +#' @param batch A \code{vector} of factors specifying the batch +#' @param drugpheno A \code{numeric} vector of drug sensitivity values (e.g., +#' IC50 or AUC) +#' @param test A \code{character} string indicating whether resampling or analytic based tests should be used +#' @param req_alpha \code{numeric}, number of permutations for p value calculation +#' @param nBoot \code{numeric}, number of bootstrap resamplings for confidence interval estimation +#' @param conf.level \code{numeric}, between 0 and 1. Size of the confidence interval required +#' @param max_perm \code{numeric} the maximum number of permutations that QUICKSTOP can do before giving up and returning NA. +#' Can be set globally by setting the option ""PharmacoGx_Max_Perm"", or left at the default of \code{ceiling(1/req_alpha*100)}. +#' @param verbose \code{boolean} Should the function display messages? +#' +#' @return A \code{vector} reporting the effect size (estimateof the coefficient +#' of drug concentration), standard error (se), sample size (n), t statistic, +#' and F statistics and its corresponding p-value. +#' +#' @examples +#' print(""TODO::"") +#' +#' @importFrom stats sd complete.cases lm glm anova pf formula var +#' @importFrom boot boot boot.ci +geneDrugSensitivityPBCorr <- function(x, type, batch, drugpheno, + test = c(""resampling"", ""analytic""), + req_alpha = 0.05, + nBoot = 1e3, + conf.level = 0.95, + max_perm = getOption(""PharmacoGx_Max_Perm"", ceiling(1/req_alpha*100)), + verbose=FALSE) { + + test <- match.arg(test) + + colnames(drugpheno) <- paste(""drugpheno"", seq_len(ncol(drugpheno)), sep=""."") + + drugpheno <- data.frame(vapply(drugpheno, function(x) { + if (!is.factor(x)) { + x[is.infinite(x)] <- NA + } + return(list(x)) + }, USE.NAMES=TRUE, + FUN.VALUE=list(1)), check.names=FALSE) + + + ccix <- complete.cases(x, type, batch, drugpheno) + nn <- sum(ccix) + + rest <- c(""estimate""=NA_real_, ""n""=as.numeric(nn), ""df""=NA_real_, significant = NA_real_,""pvalue""=NA_real_, ""lower"" = NA_real_, ""upper"" = NA_real_) + + if(nn <= 3 || all(duplicated(x)[-1L])) { + ## not enough samples with complete information or no variation in gene expression + return(rest) + } + + ## taking at least 5 times the number of boot samples as number of observations, as with binary data many boot samples + ## tend to be NA, and if the number of non-NA drops below number of obs, the emperical influence cannot be determined + ## for BCA interval calculation + + if(test==""resampling""){ + nBoot <- max(nBoot, nn*5) + } + + + drugpheno <- drugpheno[ccix,,drop=FALSE] + + + xx <- x[ccix] + + if(ncol(drugpheno)>1){ + stop(""Partial Correlations not implemented for multiple output"") + } else { + ffd <- ""drugpheno.1 ~ . - x"" + ffx <- ""x ~ . - drugpheno.1"" + } + + # ff1 <- sprintf(""%s + x"", ff0) + + dd <- data.frame(drugpheno, ""x""=xx) + + ## control for tissue type + if(length(sort(unique(type[ccix]))) > 1) { + dd <- cbind(dd, type=type[ccix]) + } + ## control for batch + if(length(sort(unique(batch[ccix]))) > 1) { + dd <- cbind(dd, batch=batch[ccix]) + } + + + if(!is.factor(dd[[2]])){ + stop(""Molecular Feature is not discrete, but point biserial correlation was requested"") + } else if(length(unique(dd[[2]]))>2) { + + stop('More than two discrete settings for moleuclar feature not currently supported') + + } else if(length(unique(dd[[2]]))==1 || min(table(dd[[2]]))<3) { + warning(""Some features had less than 3 observations per category, returning NA."") + return(rest) + + } else{ + dd[[2]] <- as.numeric(dd[[2]]) ## converting to numeric codings for downstream modeling + } + + + if(any(unlist(lapply(drugpheno,is.factor)))){ + + stop(""Currently only continous output allowed for point biserial correlations"") + + + } else{ + + if(ncol(dd) > 2){ + lm1 <- lm(formula(ffd), dd) + var1 <- residuals(lm1) + var2 <- residuals(lm(formula(ffx), dd)) + df <- lm1$df - 2L # taking the residual degrees of freedom minus 2 parameters estimated for pearson cor. + } else { ## doing this if statement in the case there are some numerical differences between mean centred values and raw values + var1 <- dd[,""drugpheno.1""] + var2 <- dd[,""x""] + df <- nn - 2L + } + + obs.cor <- cor(var1, var2, use=""complete.obs"") + + + ## NB: just permuting the residuals would leads to Type I error inflation, + ## from an underestimation due to ignoring variance in the effects of the covariates. + ## See: https://www.tandfonline.com/doi/abs/10.1080/00949650008812035 + ## Note that the above paper does not provide a single method recommended in all cases + ## We apply the permutation of raw data method, as it is most robust to small sample sizes + if(test == ""resampling""){ + ## While the logic is equivalent regardless of if there are covariates for calculating the point estimate, + ## (correlation is a subcase of partial correlation), for computational efficency in permuation testing we + ## split here and don't do extranous calls to lm if it is unnecessay. + + if(ncol(dd) > 2){ + + # if(!getOption(""PharmacoGx_useC"")|| ncol(dd)!=3){ ## not yet implemented + + ## implementing a much more efficient method for the particular case where we have 3 columns with assumption that + ## column 3 is the tissue. + if(ncol(dd)==3){ + sample_function <- function(){ + + partial.dp <- sample(dd[,1], nrow(dd)) + partial.x <- sample(dd[,2], nrow(dd)) + + for(gp in unique(dd[,3])){ + partial.x[dd[,3]==gp] <- partial.x[dd[,3]==gp]-mean(partial.x[dd[,3]==gp]) + partial.dp[dd[,3]==gp] <- partial.dp[dd[,3]==gp]-mean(partial.dp[dd[,3]==gp]) + } + + perm.cor <- cor(partial.dp, partial.x, use=""complete.obs"") + return(abs(obs.cor) < abs(perm.cor)) + } + } else { + sample_function <- function(){ + + dd2 <- dd + dd2[,1] <- sample(dd[,1], nrow(dd)) + dd2[,2] <- sample(dd[,2], nrow(dd)) + + partial.dp <- residuals(lm(formula(ffd), dd2)) + partial.x <- residuals(lm(formula(ffx), dd2)) + + perm.cor <- cor(partial.dp, partial.x, use=""complete.obs"") + return(abs(obs.cor) < abs(perm.cor)) + } + } + + p.value <- corPermute(sample_function, req_alpha = req_alpha, max_iter=max_perm) + significant <- p.value$significant + p.value <- p.value$p.value + + + # } else { + + # x <- dd[,1] + # y <- dd[,2] + # GR <- as.integer(factor(dd[,3]))-1L + # GS <- as.integer(table(factor(dd[,3]))) + # NG <- length(table(factor(dd[,3]))) + # N <- as.numeric(length(x)) + + # p.value <-PharmacoGx:::partialCorQUICKSTOP(x, y, obs.cor, GR, GS, NG, 1e7,N, req_alpha, req_alpha/100, 10L, runif(2)) + # significant <- p.value[[1]] + # p.value <- p.value[[2]] + # } + + + pcor.boot <- function(ddd, w){ + ddd <- ddd[w,] + ## Taking care of an edge case where only one covariate factor level is left after resampling + ddd[,-c(1,2)] <- ddd[,-c(1,2),drop=FALSE][,apply(ddd[,-c(1,2),drop=FALSE], 2, function(x) return(length(unique(x))))>=2] + + if(ncol(ddd)==3){ + partial.dp <- ddd[,1] + partial.x <- ddd[,2] + for(gp in unique(ddd[,3])){ + partial.x[ddd[,3]==gp] <- partial.x[ddd[,3]==gp]-mean(partial.x[ddd[,3]==gp]) + partial.dp[ddd[,3]==gp] <- partial.dp[ddd[,3]==gp]-mean(partial.dp[ddd[,3]==gp]) + } + + } else if(ncol(ddd)==2){ + partial.dp <- ddd[,1] + partial.x <- ddd[,2] + } else { + + partial.dp <- residuals(lm(formula(ffd), ddd)) + partial.x <- residuals(lm(formula(ffx), ddd)) + + } + + return(cor(partial.dp, partial.x, use=""complete.obs"")) + } + + boot.out <- boot(dd, pcor.boot, R=nBoot) + + cint <- tryCatch(boot.ci(boot.out, conf = conf.level, type=""bca"")$bca[,4:5], + error = function(e) { + if(e$message == ""estimated adjustment 'w' is infinite""){ + warning(""estimated adjustment 'w' is infinite for some features"") + return(c(NA_real_,NA_real_)) + } else { + stop(e) + } + }) + } else { + # if(!getOption(""PharmacoGx_useC"")){ + + ## At this point we have verified that we are doing the normal (nor partial) PBCC, + ## and we also verified that only 2 unique values of var2 exist. Therefore, diff + ## should return a single result. + ## Note that the PBCC permutation only depends on the mean differences, the + ## denominator is proprtional to the total variance + ## in var1 and inverse of the sqrt of the proportions between groups, + ## both of which stay constant through the permutation. Therefore, we skip + ## the needless normalization step in this permutation procedure. + ## Note that this does not apply to bootstrapping. + + obs.mean.diff <- diff(tapply(var1, var2, mean)) + sample_function <- function(){ + v1 <- sample(var1) + return(abs(obs.mean.diff) < abs(diff(tapply(v1, var2, mean)))) + } + + p.value <- corPermute(sample_function, req_alpha = req_alpha, max_iter=max_perm) + significant <- p.value$significant + p.value <- p.value$p.value + # } else { + + # x <- as.numeric(var1) + # y <- as.numeric(var2) + # GR <- rep(0L, length(x)) + # GS <- as.integer(length(x)) + # NG <- 1 + # N <- as.numeric(length(x)) + + # p.value <-PharmacoGx:::partialCorQUICKSTOP(x, y, obs.cor, GR, GS, NG, 1e7,N, req_alpha, req_alpha/100, 10L, runif(2)) + # significant <- p.value[[1]] + # p.value <- p.value[[2]] + # } + + + + + boot.out <- boot(data.frame(var1, var2), cor.boot, R=nBoot) + cint <- tryCatch(boot.ci(boot.out, conf = conf.level, type=""bca"")$bca[,4:5], + error = function(e) { + if(e$message == ""estimated adjustment 'w' is infinite"" || e$message == ""Error in if (const(t, min(1e-08, mean(t, na.rm = TRUE)/1e+06))) { : \n missing value where TRUE/FALSE needed\n""){ + warning(""estimated adjustment 'w' is infinite for some features"") + return(c(NA_real_,NA_real_)) + } else { + stop(e) + } + }) + } + + ## Think about if the partial cor should also be refit for each (Probably, different lines would be fit if points are missing...) + + } else if(test == ""analytic""){ + # if(ncol(dd) > 2){ + # df <- nn - 2L - controlled.var + + # } else { + # df <- nn - 2L + # # cor.test.res <- cor.test(dd[,""drugpheno.1""], dd[,""x""], method=""pearson"", use=""complete.obs"") + # } + stat <- sqrt(df) * obs.cor/sqrt(1-obs.cor^2) ## Note, this is implemented in same order of operations as cor.test + p.value <- 2*min(pt(stat, df=df), pt(stat, df=df, lower.tail = FALSE)) + ## Implementing with fisher transform and normal dist for consistency with R's cor.test + z <- atanh(obs.cor) + sigma <- 1/sqrt(df - 1) + cint <- tanh(z + c(-1, 1) * sigma * qnorm((1 + conf.level)/2)) + significant <- p.value < req_alpha + } + +} + +rest <- c(""estimate""=obs.cor, ""n""=nn, df=df, significant = as.numeric(significant), ""pvalue""=p.value, ""lower"" = cint[1], ""upper"" = cint[2]) + + +return(rest) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/sanityCheck.R",".R","5298","205","sanitizeInput <- function(conc, + viability, + Hill_fit, + conc_as_log = FALSE, + viability_as_pct = TRUE, + trunc = TRUE, + verbose = TRUE # Set to 2 to see debug printouts + ) { + + + + if (is.logical(conc_as_log) == FALSE) { + print(conc_as_log) + stop(""'conc_as_log' is not a logical."") + } + + if (is.logical(viability_as_pct) == FALSE) { + print(viability_as_pct) + stop(""'viability_as_pct' is not a logical."") + } + + if (is.logical(trunc) == FALSE) { + print(trunc) + stop(""'trunc' is not a logical."") + } + if(!is.finite(verbose)){ + stop(""'verbose' should be a logical (or numerical) argument."") + } + if(!missing(viability)&&!missing(conc)&&missing(Hill_fit)) + { + if (length(conc) != length(viability)) { + if(verbose==2){ + print(conc) + print(viability) + } + stop(""Log concentration vector is not of same length as viability vector."") + } + if( any(is.na(conc)&(!is.na(viability)))){ + warning(""Missing concentrations with non-missing viability values encountered. Removing viability values correspoding to those concentrations"") + + myx <- !is.na(conc) + conc <- as.numeric(conc[myx]) + viability <- as.numeric(viability[myx]) + + } + if(any((!is.na(conc))&is.na(viability))){ + + warning(""Missing viability with non-missing concentrations values encountered. Removing concentrations values correspoding to those viabilities"") + myx <- !is.na(viability) + conc <- as.numeric(conc[myx]) + viability <- as.numeric(viability[myx]) + + } + conc <- as.numeric(conc[!is.na(conc)]) + viability <- as.numeric(viability[!is.na(viability)]) + + #CHECK THAT FUNCTION INPUTS ARE APPROPRIATE + if (prod(is.finite(conc)) != 1) { + print(conc) + stop(""Concentration vector contains elements which are not real numbers."") + } + + if (prod(is.finite(viability)) != 1) { + print(viability) + stop(""Viability vector contains elements which are not real numbers."") + } + + + if (min(viability) < 0) { + if (verbose) { + + warning(""Warning: Negative viability data."") + } + } + + if (max(viability) > (1 + 99 * viability_as_pct)) { + if (verbose) { + warning(""Warning: Viability data exceeds negative control."") + } + } + + + if (conc_as_log == FALSE && min(conc) < 0) { + if (verbose == 2) { + print(conc) + print(conc_as_log) + } + stop(""Negative concentrations encountered. Concentration data may be inappropriate, or 'conc_as_log' flag may be set incorrectly."") + } + + if (viability_as_pct == TRUE && max(viability) < 5) { + warning(""Warning: 'viability_as_pct' flag may be set incorrectly."") + if (verbose == 2) { + + print(viability) + print(viability_as_pct) + } + } + + if (viability_as_pct == FALSE && max(viability) > 5) { + warning(""Warning: 'viability_as_pct' flag may be set incorrectly."") + if (verbose == 2) { + print(viability) + print(viability_as_pct) + } + } + + if(is.unsorted(conc)){ + warning(""Concentration Values were unsorted. Sorting concentration and ordering viability in same order"") + myx <- order(conc) + conc <- conc[myx] + viability <- viability[myx] + } + + #CONVERT DOSE-RESPONSE DATA TO APPROPRIATE INTERNAL REPRESENTATION + if (conc_as_log == FALSE ) { + ii <- which(conc == 0) + if(length(ii) > 0) { + conc <- conc[-ii] + viability <- viability[-ii] + } + + log_conc <- log10(conc) + } else { + log_conc <- conc + } + + if (viability_as_pct == TRUE) { + viability <- viability / 100 + } + if (trunc) { + viability = pmin(as.numeric(viability), 1) + viability = pmax(as.numeric(viability), 0) + } + + return(list(""log_conc""=log_conc, ""viability""=viability)) + } + if(!missing(Hill_fit) && missing(viability)){ + if(is.list(Hill_fit)){ + + Hill_fit <- unlist(Hill_fit) + } + if (conc_as_log == FALSE && Hill_fit[[3]] < 0) { + print(""EC50 passed in as:"") + print(Hill_fit[[3]]) + stop(""'conc_as_log' flag may be set incorrectly, as the EC50 is negative when positive value is expected."") + } + + + if (viability_as_pct == FALSE && Hill_fit[[2]] > 1) { + print(""Einf passed in as:"") + print(Hill_fit[[2]]) + + warning(""Warning: 'viability_as_pct' flag may be set incorrectly."") + + } + if (conc_as_log == FALSE){ + Hill_fit[[3]] <- log10(Hill_fit[[3]]) + } + if (viability_as_pct == TRUE){ + Hill_fit[[2]] <- Hill_fit[[2]]/100 + } + if(missing(conc)){ + return(list(""Hill_fit""=Hill_fit)) + } else { + conc <- as.numeric(conc[!is.na(conc)]) + + if (prod(is.finite(conc)) != 1) { + print(conc) + stop(""Concentration vector contains elements which are not real numbers."") + } + if (conc_as_log == FALSE && min(conc) < 0) { + print(conc) + print(conc_as_log) + stop(""Negative concentrations encountered. Concentration data may be inappropriate, or 'conc_as_log' flag may be set incorrectly."") + } + + if (conc_as_log == FALSE ) { + ii <- which(conc == 0) + if(length(ii) > 0) { + conc <- conc[-ii] + } + log_conc <- log10(conc) + } else { + log_conc <- conc + } + if(is.unsorted(conc)){ + myx <- order(conc) + conc <- conc[myx] + } + return(list(""Hill_fit""=Hill_fit, ""log_conc"" = log_conc)) + } + + + } + if(!missing(Hill_fit)&&!missing(viability)){ + + stop(""Please pass in only one of 'Hill_fit' and 'viability', it is unclear which to use in the computation."") + } + if(missing(Hill_fit)&&missing(viability)){ + + stop(""Both 'Hill_fit' and 'viability' missing, please pass in some data!"") + } +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/mergePSets.R",".R","3985","62","#' @include PharmacoSet-class.R +NULL + +mergePSets <- function(mDataPSet, sensDataPSet, commonCellsOnly=FALSE, ...){ + + if(commonCellsOnly){ + common <- intersectPSet(list(mDataPSet, sensDataPSet), intersectOn=c(""celllines"")) + mDataPSet <- common[[1]] + sensDataPSet <- common[[2]] + } + + ### union of cell lines + ucell <- union(sampleNames(sensDataPSet), sampleNames(mDataPSet)) + + ### molecular profiles + mergePSet <- sensDataPSet + molecularProfilesSlot(mergePSet) <- molecularProfilesSlot(mDataPSet) + + ### number of sensitivity experiments + #acell <- setdiff(rownames(sampleInfo(mDataPSet)), rownames(sampleInfo(sensDataPSet))) + + ### cell line annotations + new.cell.info <- c(union(colnames(sampleInfo(sensDataPSet)), colnames(sampleInfo(mDataPSet))), ""dataset"") + cell.info.df <- data.frame(matrix(NA, nrow=length(ucell), ncol=length(new.cell.info), dimnames=list(ucell, new.cell.info)), check.names=FALSE) + cell.info.df[rownames(sampleInfo(mDataPSet)), colnames(sampleInfo(mDataPSet))] <- sampleInfo(mDataPSet) + cell.info.df[rownames(sampleInfo(sensDataPSet)), colnames(sampleInfo(sensDataPSet))] <- sampleInfo(sensDataPSet) + cell.info.df[setdiff(rownames(sampleInfo(sensDataPSet)), rownames(sampleInfo(mDataPSet))), ""dataset""] <- name(sensDataPSet) + cell.info.df[setdiff(rownames(sampleInfo(mDataPSet)), rownames(sampleInfo(sensDataPSet))), ""dataset""] <- name(mDataPSet) + cell.info.df[intersect(rownames(sampleInfo(mDataPSet)), rownames(sampleInfo(sensDataPSet))), ""dataset""] <- paste0(name(sensDataPSet), ""///"", name(mDataPSet)) + sampleInfo(mergePSet) <- cell.info.df + + ### curation of cell line names + new.cell.curation <- c(union(colnames(curation(sensDataPSet)$sample), colnames(curation(mDataPSet)$sample)), ""dataset"") + cell.curation.df <- data.frame(matrix(NA, nrow=length(ucell), ncol=length(new.cell.curation), dimnames=list(ucell, new.cell.curation)), check.names=FALSE) + cell.curation.df[rownames(curation(mDataPSet)$sample), colnames(curation(mDataPSet)$sample)] <- curation(mDataPSet)$sample + cell.curation.df[rownames(curation(sensDataPSet)$sample), colnames(curation(sensDataPSet)$sample)] <- curation(sensDataPSet)$sample + cell.curation.df[setdiff(rownames(curation(sensDataPSet)$sample), rownames(curation(mDataPSet)$sample)), ""dataset""] <- name(sensDataPSet) + cell.curation.df[setdiff(rownames(curation(mDataPSet)$sample), rownames(curation(sensDataPSet)$sample)), ""dataset""] <- name(mDataPSet) + cell.curation.df[intersect(rownames(curation(mDataPSet)$sample), rownames(curation(sensDataPSet)$sample)), ""dataset""] <- paste0(name(sensDataPSet), ""///"", name(mDataPSet)) + curation(mergePSet)$sample <- cell.curation.df + + ### curation of tissue names + new.tissue.curation <- c(union(colnames(curation(sensDataPSet)$tissue), colnames(curation(mDataPSet)$tissue)), ""dataset"") + tissue.curation.df <- data.frame(matrix(NA, nrow=length(ucell), ncol=length(new.tissue.curation), dimnames=list(ucell, new.tissue.curation)), check.names=FALSE) + tissue.curation.df[rownames(curation(mDataPSet)$tissue), colnames(curation(mDataPSet)$tissue)] <- curation(mDataPSet)$tissue + tissue.curation.df[rownames(curation(sensDataPSet)$tissue), colnames(curation(sensDataPSet)$tissue)] <- curation(sensDataPSet)$tissue + tissue.curation.df[setdiff(rownames(curation(sensDataPSet)$tissue), rownames(curation(mDataPSet)$tissue)), ""dataset""] <- name(sensDataPSet) + tissue.curation.df[setdiff(rownames(curation(mDataPSet)$tissue), rownames(curation(sensDataPSet)$tissue)), ""dataset""] <- name(mDataPSet) + tissue.curation.df[intersect(rownames(curation(mDataPSet)$tissue), rownames(curation(sensDataPSet)$tissue)), ""dataset""] <- paste0(name(sensDataPSet), ""///"", name(mDataPSet)) + curation(mergePSet)$tissue <- tissue.curation.df + + sensNumber(mergePSet) <- PharmacoGx:::.summarizeSensitivityNumbers(mergePSet) + + annotation(mergePSet)$name <- paste(name(mDataPSet), name(sensDataPSet), sep=""."") + + annotation(mergePSet)$dateCreated <- date() + + checkPSetStructure(mergePSet) + + return(mergePSet) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/PharmacoSet-class.R",".R","15435","386","#' @importClassesFrom MultiAssayExperiment MultiAssayExperiment +#' @export +NULL + +setClassUnion('list_OR_MAE', c('list', 'MultiAssayExperiment')) + +# #' @importClassesFrom CoreGx LongTable TreatmentResponseExperiment +# setClassUnion('list_OR_LongTable', c('list', 'LongTable')) + +.local_class=""PharmacoSet"" + +#' A Class to Contain PharmacoGenomic datasets together with their curations +#' +#' The PharmacoSet (pSet) class was developed to contain and organise large +#' PharmacoGenomic datasets, and aid in their metanalysis. It was designed +#' primarily to allow bioinformaticians and biologists to work with data at the +#' level of genes, drugs and cell lines, providing a more naturally intuitive +#' interface and simplifying analyses between several datasets. As such, it was +#' designed to be flexible enough to hold datasets of two different natures +#' while providing a common interface. The class can accomidate datasets +#' containing both drug dose response data, as well as datasets contaning +#' genetic profiles of cell lines pre and post treatement with compounds, known +#' respecitively as sensitivity and perturbation datasets. +#' +#' @param object A \code{PharmacoSet} object +#' @param mDataType A \code{character} with the type of molecular data to +#' return/update +#' @param value A replacement value +#' +#' @slot annotation A \code{list} of annotation data about the PharmacoSet, +#' including the \code{$name} and the session information for how the object +#' was creating, detailing the exact versions of R and all the packages used +#' @slot molecularProfiles A \code{list} containing \code{SummarizedExperiment} +#' type object for holding data for RNA, DNA, SNP and CNV +#' measurements, with associated \code{fData} and \code{pData} +#' containing the row and column metadata +#' @slot sample A \code{data.frame} containing the annotations for all the cell +#' lines profiled in the data set, across all data types +#' @slot treatment A \code{data.frame} containg the annotations for all the drugs +#' profiled in the data set, across all data types +#' @slot treatmentResponse A \code{list} containing all the data for the +#' sensitivity experiments, including \code{$info}, a \code{data.frame} +#' containing the experimental info,\code{$raw} a 3D \code{array} containing +#' raw data, \code{$profiles}, a \code{data.frame} containing sensitivity +#' profiles statistics, and \code{$n}, a \code{data.frame} detailing the +#' number of experiments for each cell-drug pair +#' @slot perturbation A \code{list} containting \code{$n}, a \code{data.frame} +#' summarizing the available perturbation data, +#' @slot curation A \code{list} containing mappings for \code{$treatment}, +#' \code{cell}, \code{tissue} names used in the data set to universal +#' identifiers used between different PharmacoSet objects +#' @slot datasetType A \code{character} string of 'sensitivity', +#' 'perturbation', or both detailing what type of data can be found in the +#' PharmacoSet, for proper processing of the data +#' +#' @importClassesFrom CoreGx CoreSet +#' @importClassesFrom CoreGx LongTable +#' @importClassesFrom CoreGx TreatmentResponseExperiment +#' +#' @return An object of the PharmacoSet class +.PharmacoSet <- setClass('PharmacoSet', + contains='CoreSet') + + +# The default constructor above does a poor job of explaining the required +# structure of a PharmacoSet. The constructor function defined below guides the +# user into providing the required components of the curation and senstivity +# lists and hides the annotation slot which the user does not need to manually +# fill. This also follows the design of the Expression Set class. + +##### +# CONSTRUCTOR ----- +##### + +#' PharmacoSet constructor +#' +#' A constructor that simplifies the process of creating PharmacoSets, as well +#' as creates empty objects for data not provided to the constructor. Only +#' objects returned by this constructor are expected to work with the PharmacoSet +#' methods. For a much more detailed instruction on creating PharmacoSets, please +#' see the ""CreatingPharmacoSet"" vignette. +#' +#' @examples +#' ## For help creating a PharmacoSet object, please see the following vignette: +#' browseVignettes(""PharmacoGx"") +#' +#' @inheritParams CoreGx::CoreSet +#' +#' @return An object of class `PharmacoSet` +# +#' @import methods +#' @importFrom utils sessionInfo +#' @importFrom stats na.omit +#' @importFrom SummarizedExperiment rowData colData assay assays assayNames Assays +#' @importFrom S4Vectors DataFrame SimpleList metadata +#' @importFrom CoreGx CoreSet +#' +#' @export +PharmacoSet <- function(name, molecularProfiles=list(), sample=data.frame(), + treatment=data.frame(), sensitivityInfo=data.frame(), + sensitivityRaw=array(dim=c(0,0,0)), sensitivityProfiles=matrix(), + sensitivityN=matrix(nrow=0, ncol=0), perturbationN=array(NA, dim=c(0,0,0)), + curationTreatment=data.frame(), curationSample = data.frame(), + curationTissue = data.frame(), datasetType=c(""sensitivity"", ""perturbation"", ""both""), + verify = TRUE, ...) { + + #.Deprecated(""PharmacoSet2"", ) + + cSet <- CoreGx::CoreSet( + name=name, + molecularProfiles = molecularProfiles, + sample=sample, + treatment=treatment, + sensitivityInfo=sensitivityInfo, + sensitivityRaw=sensitivityRaw, + sensitivityProfiles=sensitivityProfiles, + sensitivityN=sensitivityN, + perturbationN=perturbationN, + curationTreatment=curationTreatment, + curationSample=curationSample, + curationTissue=curationTissue, + datasetType=datasetType, + verify=verify, + ... + ) + + pSet <- .PharmacoSet( + annotation=cSet@annotation, + molecularProfiles=cSet@molecularProfiles, + sample=cSet@sample, + treatment=cSet@treatment, + datasetType=cSet@datasetType, + treatmentResponse=cSet@treatmentResponse, + perturbation=cSet@perturbation, + curation=cSet@curation + ) + if (verify) checkPsetStructure(pSet) + if (length(sensitivityN) == 0 && datasetType %in% c(""sensitivity"", ""both"")) { + pSet@treatmentResponse$n <- .summarizeSensitivityNumbers(pSet) + } + if (!length(perturbationN) && + datasetType %in% c(""perturbation"", ""both"")) { + pSet@perturbation$n <- .summarizePerturbationNumbers(pSet) + } + return(pSet) +} + +#' @eval CoreGx:::.docs_CoreSet2_constructor(class_=.local_class, +#' sx_=""Samples in a `PharmacoSet` represent cancer cell-lines."", +#' tx_=""Treatments in a `PharmacoSet` represent pharmaceutical compounds."", +#' cx_=""This class requires an additional curation item, tissue, which maps +#' from published to standardized tissue idenifiers."", +#' data_=.local_data) +#' @importFrom CoreGx CoreSet2 LongTable TreatmentResponseExperiment +#' @export +PharmacoSet2 <- function(name=""emptySet"", treatment=data.frame(), + sample=data.frame(), molecularProfiles=MultiAssayExperiment(), + treatmentResponse=TreatmentResponseExperiment(), + perturbation=list(), + curation=list(sample=data.frame(), treatment=data.frame(), + tissue=data.frame()), datasetType=""sensitivity"" +) { + # -- Leverage existing checks in CoreSet constructor + cSet <- CoreSet2(name=name, treatment=treatment, + sample=sample, treatmentResponse=treatmentResponse, + molecularProfiles=molecularProfiles, curation=curation, + perturbation=perturbation, datasetType=datasetType) + + ## -- data integrity + # treatment + ## TODO + + .PharmacoSet( + annotation=cSet@annotation, + sample=cSet@sample, + treatment=cSet@treatment, + molecularProfiles=cSet@molecularProfiles, + treatmentResponse=cSet@treatmentResponse, + datasetType=cSet@datasetType, + curation=cSet@curation, + perturbation=cSet@perturbation + ) +} + +# Constructor Helper Functions ---------------------------------------------- + +#' @keywords internal +#' @importFrom CoreGx idCols . .errorMsg .collapse +.summarizeSensitivityNumbers <- function(object) { + ## TODO:: Checks don't like assigning to global evnironment. Can we return this? + assign('object_sumSenNum', object) # Removed envir=.GlobalEnv + if (datasetType(object) != 'sensitivity' && datasetType(object) != 'both') { + stop ('Data type must be either sensitivity or both') + } + ## consider all drugs + drugn <- treatmentNames(object) + ## consider all cell lines + celln <- sampleNames(object) + sensitivity.info <- matrix(0, nrow=length(celln), ncol=length(drugn), + dimnames=list(celln, drugn)) + drugids <- sensitivityInfo(object)[ , ""treatmentid""] + sampleids <- sensitivityInfo(object)[ , ""sampleid""] + sampleids <- sampleids[grep('///', drugids, invert=TRUE)] + drugids <- drugids[grep('///', drugids, invert=TRUE)] + tt <- table(sampleids, drugids) + sensitivity.info[rownames(tt), colnames(tt)] <- tt + + return(sensitivity.info) +} + +#' @importFrom CoreGx .summarizeMolecularNumbers +.summarizeMolecularNumbers <- function(object) { + CoreGx::.summarizeMolecularNumbers(object) +} + +#' @importFrom CoreGx treatmentNames sampleNames +.summarizePerturbationNumbers <- function(object) { + + if (datasetType(object) != 'perturbation' && datasetType(object) != 'both') { + stop('Data type must be either perturbation or both') + } + + ## consider all drugs + drugn <- treatmentNames(object) + + ## consider all cell lines + celln <- sampleNames(object) + + mprof <- molecularProfilesSlot(object) + perturbation.info <- array(0, dim=c(length(celln), length(drugn), + length(mprof)), + dimnames=list(celln, drugn, names(mprof)) + ) + for (i in seq_len(length(mprof))) { + if (nrow(colData(mprof[[i]])) > 0 && + all(c(""sampleid"", ""treatmentid"") %in% + colnames(mprof[[i]]))) { + tt <- table( + colData(mprof[[i]])[, ""sampleid""], + colData(mprof[[i]])[, ""treatmentid""] + ) + perturbation.info[rownames(tt), colnames(tt), names(mprof)[i]] <- tt + } + } + + return(perturbation.info) +} + +### ------------------------------------------------------------------------- +### Class Validity ---------------------------------------------------------- +### ------------------------------------------------------------------------- + +#' A function to verify the structure of a PharmacoSet +#' +#' This function checks the structure of a PharamcoSet, ensuring that the +#' correct annotations are in place and all the required slots are filled so +#' that matching of cells and drugs can be properly done across different types +#' of data and with other studies. +#' +#' @examples +#' data(CCLEsmall) +#' checkPsetStructure(CCLEsmall) +#' +#' @param object A \code{PharmacoSet} to be verified +#' @param plotDist Should the function also plot the distribution of molecular data? +#' @param result.dir The path to the directory for saving the plots as a string +#' +#' @return Prints out messages whenever describing the errors found in the +#' structure of the object object passed in. +#' +#' @importFrom graphics hist +#' @importFrom grDevices dev.off pdf +#' +#' @export +checkPsetStructure <- + function(object, plotDist=FALSE, result.dir='.') { + + # Make directory to store results if it doesn't exist + if(!file.exists(result.dir) & plotDist) { dir.create(result.dir, showWarnings=FALSE, recursive=TRUE) } + + ##### + # Checking molecularProfiles + ##### + # Can this be parallelized or does it mess with the order of printing warnings? + mprof <- molecularProfilesSlot(object) + for( i in seq_along(mprof)) { + profile <- mprof[[i]] + nn <- names(mprof)[i] + + # Testing plot rendering for rna and rnaseq + if((S4Vectors::metadata(profile)$annotation == 'rna' || S4Vectors::metadata(profile)$annotation == 'rnaseq') && plotDist) + { + pdf(file=file.path(result.dir, sprintf('%s.pdf', nn))) + hist(assays(profile)[[1]], breaks = 100) + dev.off() + } + + ## Test if sample and feature annotations dimensions match the assay + warning(ifelse(nrow(rowData(profile)) != nrow(assays(profile)[[1]]), + sprintf('%s: number of features in fData is different from + SummarizedExperiment slots', nn), + sprintf('%s: rowData dimension is OK', nn) + ) + ) + warning(ifelse(nrow(colData(profile)) != ncol(assays(profile)[[1]]), + sprintf('%s: number of cell lines in pData is different + from expression slots', nn), + sprintf('%s: colData dimension is OK', nn) + ) + ) + + + # Checking sample metadata for required columns + warning(ifelse(""sampleid"" %in% colnames(colData(profile)), '', + sprintf('%s: sampleid does not exist in colData (samples) + columns', nn))) + warning(ifelse('batchid' %in% colnames(colData(profile)), '', + sprintf('%s: batchid does not exist in colData (samples) + columns', nn))) + + # Checking mDataType of the SummarizedExperiment for required columns + if(S4Vectors::metadata(profile)$annotation == 'rna' | + S4Vectors::metadata(profile)$annotation == 'rnaseq') + { + warning(ifelse('BEST' %in% colnames(rowData(profile)), 'BEST is OK', + sprintf('%s: BEST does not exist in rowData (features) + columns', nn))) + warning(ifelse('Symbol' %in% colnames(rowData(profile)), 'Symbol is OK', + sprintf('%s: Symbol does not exist in rowData (features) + columns', nn))) + } + + # Check that all sampleids from the object are included in molecularProfiles + if(""sampleid"" %in% colnames(colData(profile))) { + if (!all(colData(profile)[,""sampleid""] %in% sampleNames(object))) { + warning(sprintf('%s: not all the cell lines in this profile are in + cell lines slot', nn)) + } + }else { + warning(sprintf('%s: sampleid does not exist in colData (samples)', nn)) + } + } + +} + + +### ------------------------------------------------------------------------- +### Method Definitions ------------------------------------------------------ +### ------------------------------------------------------------------------- + +#' Show a PharamcoSet +#' +#' @param object \code{PharmacoSet} +#' +#' @examples +#' data(CCLEsmall) +#' CCLEsmall +#' +#' @return Prints the PharmacoSet object to the output stream, and returns +#' invisible NULL. +#' +#' @importFrom CoreGx show +#' @importFrom methods callNextMethod +#' +#' @export +setMethod('show', signature=signature(object='PharmacoSet'), function(object) { + callNextMethod(object) +}) + +#' Get the dimensions of a PharmacoSet +#' +#' @param x PharmacoSet +#' @return A named vector with the number of Cells and Drugs in the PharmacoSet +#' @export +setMethod('dim', signature=signature(x='PharmacoSet'), function(x){ + return(c(Cells=length(sampleNames(x)), Drugs=length(treatmentNames(x)))) +}) + + +### TODO:: Add updating of sensitivity Number tables +#' @importFrom CoreGx updateSampleId +#' @aliases updateCellId +updateSampleId <- updateCellId <- function(object, new.ids = vector('character')){ + CoreGx::updateSampleId(object, new.ids) +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/computeAmax.R",".R","2787","84","#' Fits dose-response curves to data given by the user +#' and returns the Amax of the fitted curve. +#' Amax: 100 - viability at maximum concentarion (in fitted curve) +#' +#' @examples +#' dose <- c(0.0025,0.008,0.025,0.08,0.25,0.8,2.53,8) +#' viability <- c(108.67,111,102.16,100.27,90,87,74,57) +#' computeAmax(dose, viability) +#' +#' @param concentration `numeric` is a vector of drug concentrations. +#' +#' @param viability `numeric` is a vector whose entries are the viability values observed in the presence of the +#' drug concentrations whose logarithms are in the corresponding entries of the log_conc, expressed as percentages +#' of viability in the absence of any drug. +#' +#' @param trunc `logical`, if true, causes viability data to be truncated to lie between 0 and 1 before +#' curve-fitting is performed. +#' @param verbose `logical` should warnings be printed +#' @return The numerical Amax +#' @export +computeAmax <- function(concentration, viability, trunc = TRUE, verbose=FALSE) { + concentration <- as.numeric(concentration[!is.na(concentration)]) + viability <- as.numeric(viability[!is.na(viability)]) + ii <- which(concentration == 0) + if(length(ii) > 0) { + concentration <- concentration[-ii] + viability <- viability[-ii] + } + + #CHECK THAT FUNCTION INPUTS ARE APPROPRIATE + if (!all(is.finite(concentration))) { + print(concentration) + stop(""Concentration vector contains elements which are not real numbers."") + } + + if (!all(is.finite(viability))) { + print(viability) + stop(""Viability vector contains elements which are not real numbers."") + } + + if (is.logical(trunc) == FALSE) { + print(trunc) + stop(""'trunc' is not a logical."") + } + + if (length(concentration) != length(viability)) { + print(concentration) + print(viability) + stop(""Concentration vector is not of same length as viability vector."") + } + + if (min(concentration) < 0) { + stop(""Concentration vector contains negative data."") + } + + if (min(viability) < 0 & verbose) { + warning(""Warning: Negative viability data."") + } + + if (max(viability) > 100 & verbose) { + warning(""Warning: Viability data exceeds negative control."") + } + + #CONVERT DOSE-RESPONSE DATA TO APPROPRIATE INTERNAL REPRESENTATION + log_conc <- log10(concentration) + viability <- viability / 100 + + if (trunc == TRUE) { + viability[which(viability < 0)] <- 0 + viability[which(viability > 1)] <- 1 + } + + #FIT CURVE AND CALCULATE IC50 + pars <- unlist(logLogisticRegression(log_conc, + viability, + conc_as_log = TRUE, + viability_as_pct = FALSE, + trunc = trunc)) + x <- 100 - .Hill(max(log_conc), pars) * 100 + names(x) <- ""Amax"" + return(x) + +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/intersectPSets.R",".R","8862","223","#' Intersects objects of the PharmacoSet class, subsetting them to the common +#' drugs and/or cell lines as selected by the user. +#' +#' Given a list of PharmacoSets, the function will find the common drugs, +#' and/or cell lines, and return PharmacoSets that contain data only pertaining +#' to the common drugs, and/or cell lines. The mapping between dataset +#' drug and cell names is done using annotations found in the +#' PharmacoSet object's internal curation slot +#' +#' @examples +#' data(GDSCsmall) +#' data(CCLEsmall) +#' common <- intersectPSet(list('GDSC'=GDSCsmall,'CCLE'=CCLEsmall), +#' intersectOn = c(""drugs"", ""cell.lines"")) +#' common$CGP +#' common$CCLE +#' +#' @param pSets \code{list} a list of PharmacoSet objects, of which the function +#' should find the intersection +#' @param intersectOn \code{character} which identifiers to intersect on, +#' drugs, cell lines, or concentrations +#' @param drugs a \code{character} vector of common drugs between pSets. +#' In case user is intersted on getting intersection on certain drugs, +#' they can provide their list of drugs. +#' @param cells a \code{character}vector of common cell lines between pSets. +#' In case user is intersted on getting intersection on certain cell lines, +#' they can provide their list of cell lines +#' @param strictIntersect \code{boolean} Should the intersection keep only the drugs +#' and cell lines that have been tested on together? +#' @param verbose \code{boolean} Should the function announce its key steps? +#' @param nthread \code{numeric} The number of cores to use to run intersection on +#' concentrations +#' +#' @return A \code{list} of pSets, contatining only the intersection +#' +#' @importFrom S4Vectors metadata +#' @importFrom SummarizedExperiment colData +#' @importFrom CoreGx .intersectList +#' +#' @export +intersectPSet <- function(pSets, + intersectOn=c(""drugs"", ""cell.lines"", ""concentrations""), + cells, + drugs, + strictIntersect=FALSE, verbose=TRUE, nthread=1) +{ + if (verbose) { + message(""Intersecting large PSets may take a long time ..."") + } + + if(""concentrations"" %in% intersectOn && anyNA(sapply(pSets, function(x) return(sensitivityRaw(x))))) { + stop(""Intersecting on concentrations requires all PSets to have raw data included."") + } + ## TODO: Fix the strict intersection!!!!!! + if (length(pSets) == 1) { + return(pSets) + } + if (length(pSets) > 1) { + if(is.null(names(pSets)) ){ + + names(pSets) <- sapply(pSets, name) + + } + if (""drugs"" %in% intersectOn){ + common.drugs <- .intersectList(lapply(pSets, function(x) return(treatmentNames(x)))) + if(!missing(drugs)) { + common.drugs <- intersect(common.drugs, drugs) + } + if (length(common.drugs) == 0) { + stop(""No drugs is in common between pSets!"") + } + } + if (""cell.lines"" %in% intersectOn){ + common.cells <- .intersectList(lapply(pSets, function(x){return(sampleNames(x))})) + if(!missing(cells)) { + common.cells <- intersect(common.cells, cells) + } + if (length(common.cells) == 0) { + stop(""No cell lines is in common between pSets!"") + } + } + if ((""drugs"" %in% intersectOn) & (""cell.lines"" %in% intersectOn)) { + common.exps <- .intersectList(lapply(pSets, function (x){ + if (""sampleid"" %in% colnames(sensitivityInfo(x)) & ""treatmentid"" %in% colnames(sensitivityInfo(x))) { + paste(sensitivityInfo(x)$sampleid, sensitivityInfo(x)$treatmentid, sep = ""_"") + } else { NULL } + })) + # expMatch <- data.frame(lapply(pSets, + # function (x, common.exps){ + # if (""sampleid"" %in% colnames(sensitivityInfo(x)) & ""treatmentid"" %in% colnames(sensitivityInfo(x))){ + + # myx <- match(paste(sensitivityInfo(x)$sampleid, sensitivityInfo(x)$treatmentid, sep = ""_"") ,common.exps) + + # res <- rownames(sensitivityInfo(x))[!is.na(myx)] + + # names(res) <- common.exps[na.omit(myx)] + + # res <- res[common.exps] + + # return(res) + + # } else { NULL } + # }, common.exps=common.exps)) + expMatch <- lapply(pSets, + function (x, common.exps){ + if (""sampleid"" %in% colnames(sensitivityInfo(x)) & ""treatmentid"" %in% colnames(sensitivityInfo(x))){ + + myx <- match(paste(sensitivityInfo(x)$sampleid, sensitivityInfo(x)$treatmentid, sep = ""_"") ,common.exps) + + res <- rownames(sensitivityInfo(x))[!is.na(myx)] + + names(res) <- common.exps[na.omit(myx)] + + res <- res[common.exps] + + return(res) + + } else { NULL } + }, common.exps=common.exps) + # }, common.exps=common.exps) + + if(strictIntersect){ + if(length(unique(sapply(expMatch, length)))>1){ + stop(""Strict Intersecting works only when each PSet has 1 replicate per cell-drug pair. Use collapseSensitvityReplicates to reduce the sensitivity data as required"") + } + expMatch <- data.frame(expMatch, stringsAsFactors=FALSE) + # expMatch2 <- as.matrix(expMatch2) + rownames(expMatch) <- common.exps + colnames(expMatch) <- names(pSets) + + } else { + + expMatch <- lapply(expMatch, function(x){names(x) <- x; return(x)}) + } + } + if ((""drugs"" %in% intersectOn) & (""cell.lines"" %in% intersectOn) & (""concentrations"" %in% intersectOn)) { + + if(length(unique(sapply(expMatch, length)))>1){ + stop(""Intersecting on concentrations works only when each PSet has 1 replicate per cell-drug pair. Use collapseSensitvityReplicates to reduce the sensitivity data as required"") + } + + expMatch <- data.frame(expMatch, stringsAsFactors=FALSE) + # expMatch2 <- as.matrix(expMatch2) + rownames(expMatch) <- common.exps + colnames(expMatch) <- names(pSets) + + pSets <- .calculateSensitivitiesStar(pSets, exps=expMatch, cap=100, nthread=nthread) + } + if (""cell.lines"" %in% intersectOn) + { + molecular.types <- NULL + for (pSet in pSets) + { + for (SE in molecularProfilesSlot(pSet)) { + molecular.types <- union(molecular.types, ifelse ( + length(grep(""rna"", S4Vectors::metadata(SE)$annotation) > 0), + ""rna"", S4Vectors::metadata(SE)$annotation)) + } + } + common.molecular.cells <- list() + for (molecular.type in molecular.types) + { + if(strictIntersect){ + common.molecular.cells[[molecular.type]] <- + .intersectList(lapply(pSets, function (pSet) + { + SEs <- names(unlist(sapply(molecularProfilesSlot(pSet), function(SE) + { + grep(molecular.type, S4Vectors::metadata(SE)$annotation)}))) + if(length(SEs) > 0) + { + return(.intersectList(sapply(SEs, function(SE) + { + if (length(grep( + molecular.type, S4Vectors::metadata( + molecularProfilesSlot(pSet)[[SE]])$annotation)) > 0) + { + intersect(colData(molecularProfilesSlot(pSet)[[SE]])$sampleid, common.cells) + } + }))) + } + })) + }else{ + common.molecular.cells[[molecular.type]] <- + .intersectList(lapply(pSets, function (pSet) { + SEs <- names(unlist(sapply(molecularProfilesSlot(pSet), function(SE) + { + grep(molecular.type, S4Vectors::metadata(SE)$annotation)}))) + return(CoreGx::.unionList(sapply(SEs, function(SE) + { + if (length(grep(molecular.type, S4Vectors::metadata(molecularProfilesSlot(pSet)[[SE]])$annotation)) > 0) + { + intersect(SummarizedExperiment::colData(molecularProfilesSlot(pSet)[[SE]])$sampleid, common.cells) + } + }))) + })) + } + } + } + + + + + for (i in seq_along(pSets)) { + if((""drugs"" %in% intersectOn) & (""cell.lines"" %in% intersectOn)){ + if(strictIntersect){ + pSets[[i]] <- subsetTo(pSets[[i]], drugs=common.drugs, cells=common.cells, exps=expMatch, molecular.data.cells=common.molecular.cells) + + } else { + pSets[[i]] <- subsetTo(pSets[[i]], drugs=common.drugs, cells=common.cells, molecular.data.cells=common.molecular.cells) + } + } else if((""cell.lines"" %in% intersectOn)) { + pSets[[i]] <- subsetTo(pSets[[i]], cells=common.cells, molecular.data.cells=common.molecular.cells) + + } else if((""drugs"" %in% intersectOn)) { + pSets[[i]] <- subsetTo(pSets[[i]], drugs=common.drugs) + + } + } + return(pSets) + } +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/plotPSig.R",".R","4295","126","#' Plots a PharmacoSig object into a Volcano Plot +#' +#' Given a PharmacoSig, this will plot a volcano plot, with parameters to set cutoffs +#' for a significant effect size, p value, to pick multiple testing correction strategy, +#' and to change point colors. Built on top of ggplot, it will return the plot object which +#' can be easily customized as any other ggplot. +#' +#' @examples +#' data(GDSCsmall) +#' drug.sensitivity <- drugSensitivitySig(GDSCsmall, mDataType=""rna"", +#' nthread=1, features = fNames(GDSCsmall, ""rna"")[1]) +#' plot(drug.sensitivity) +#' +#' @param x `PharmacoSig` a PharmacoSig object, result of drugSensitivitySig +#' or drugPerturbationSig +#' @param adjust.method `character(1)` or `logical(1)` either FALSE for no adjustment, +#' or one of the methods implemented by p.adjust. Defaults to FALSE for no +#' correction +#' @param drugs `character` a vector of drug names for which to plot the estimated +#' associations with gene expression +#' @param features `character` a vector of features for which to plot the estimated +#' associations with drug treatment +#' @param effect_cutoff the cutoff to use for coloring significant effect sizes. +#' @param signif_cutoff the cutoff to use for coloring significance by p value or +#' adjusted p values. Not on log scale. +#' @param color one color if no cutoffs set for plotting. A vector of colors otherwise +#' used to color points the in three categories above. +#' @param ... additional arguments, not currently used, but left here for consistency with plot +#' @return returns a ggplot object, which by default will be evaluated and the plot displayed, or +#' can be saved to a variable for further customization by adding ggplot elements to the returned +#' graph +#' +#' @export +#' @import ggplot2 +#' @include class-SignatureClass.R +#' @method plot PharmacoSig +plot.PharmacoSig <- function(x, adjust.method, drugs, features, effect_cutoff, signif_cutoff, color, ...){ + dots <- list(...) + ndots <- length(dots) + + # if(length(dim(x))==2){ + # dim(x) <- c(1, dim(x)) + # } else if(length(dim(x)) == 1) { + # dim(x) <- c(1, 1, dim(x)) + # } + + if(missing(adjust.method)){ + adjust.method <- FALSE + } + + if(missing(drugs)){ + drugs <- colnames(x) + } + + if(missing(features)){ + features <- rownames(x) + } + + if(!missing(color)){ + if(!is.null(dots[[""colour""]])){ + warning(""Both color and colour parameters provided. Will take union of both. This is probably a mistake."") + color <- union(color, dots[[""colour""]]) + } + } else if (!is.null(dots[[""colour""]])){ + color <- dots[[""colour""]] + } ## Case if both missing handled in logic below + + + if(isFALSE(adjust.method)){ + p.adjust.f <- function(x) return(x) + } else { + p.adjust.f <- function(x) return(p.adjust(x, method=adjust.method)) + } + + x.m <- data.frame(X = as.vector(x[features,drugs,c(""estimate"")]), + Y = -log10(p.adjust.f(as.vector(x[features,drugs,c(""pvalue"")])))) + axis.labs <- c(""Estimate"", ifelse(isFALSE(adjust.method) || adjust.method == ""none"", ""-Log10 P Value"", ""-Log10 Corrected P Value"")) + + + plot.elements <- ggplot() + xlab(axis.labs[1]) + ylab(axis.labs[2]) + + + if(!missing(effect_cutoff) | !missing(signif_cutoff)) { + x.m$Cutoff <- ""Not Significant"" + + if(!missing(signif_cutoff)){ + x.m$Cutoff[x.m$Y >= -log10(signif_cutoff)] <- ""Significant P Value"" + + if(!missing(effect_cutoff)){ + x.m$Cutoff[(x.m$Y >= -log10(signif_cutoff)) & (abs(x.m$X) >= effect_cutoff)] <- ""Significant P Value and Effect"" + } + + } else { + x.m$Cutoff[(abs(x.m$X) >= effect_cutoff)] <- ""Significant Effect"" + } + + plot.elements <- plot.elements + geom_point(aes(X, Y, color = Cutoff), data=x.m) + + if(!missing(color)){ ## this is handled here because we want different behaviour based on if we have significance based coloring or not + plot.elements <- plot.elements + scale_colour_manual(values = color) + } + + } else { + + if(missing(color)){ ## this is handled here because we want different behaviour based on if we have significance based coloring or not + color <- ""black"" + } + + x.m$Cutoff <- NA_character_ + + plot.elements <- plot.elements + geom_point(aes(X, Y), color = color, data=x.m) + } + + + plot.elements +} + +# Plots a PharmacoSig object into a Volcano Plot +# +# +# @S3method plot PharmacoSig +setMethod(""plot"", ""PharmacoSig"", plot.PharmacoSig) + + + +","R" +"Pharmacogenomics","bhklab/PharmacoGx","R/downloadPSet.R",".R","4925","127","#' Return a table of PharmacoSets available for download +#' +#' The function fetches a table of all PharmacoSets available for download. +#' The table includes the dataset names, version information for the data in the PSet, +#' the date of last update, the name of the PSet, and references for the data contained within, +#' a DOI for the data, and a direct download link. Download can also be done using the downloadPSet +#' function. +#' +#' Much more information on the processing of the data and data provenance can be found at: +#' www.orcestra.ca +#' +#' +#' @examples +#' if (interactive()){ +#' availablePSets() +#' } +#' +#' @param canonical `logical(1)` Should available PSets show only official +#' PSets, or should user generated PSets be included? +#' +#' @return A `data.frame` with details about the available PharmacoSet objects +#' @export +#' @import jsonlite +availablePSets <- function(canonical=TRUE){ + + if (canonical) { + avail.psets <- fromJSON(""http://www.orcestra.ca/api/pset/canonical"") + } else { + avail.psets <- fromJSON(""http://www.orcestra.ca/api/pset/available"") + } + + + pSetTable <- data.frame(""Dataset Name"" = avail.psets$dataset$name, + ""Date Created"" = avail.psets$dateCreated, + ""PSet Name"" = avail.psets$name, + avail.psets$dataset$versionInfo, + ""DOI"" = avail.psets$doi, + ""Download"" = avail.psets$downloadLink, stringsAsFactors = FALSE, check.names = FALSE) + + return(pSetTable) +} + +#' Download a PharmacoSet object +#' +#' This function allows you to download a \code{PharmacoSet} object for use with this +#' package. The \code{PharmacoSets} have been extensively curated and organised within +#' a PharacoSet class, enabling use with all the analysis tools provided in +#' \code{PharmacoGx}. User \code{availablePSets} to discover which PSets are available. +#' +#' @examples +#' \dontrun{ +#' if (interactive()) downloadPSet(""CTRPv2_2015"") +#' } +#' +#' @section Warning: +#' BREAKING CHANGES - this function now defaults to `tempdir()` as the download +#' path! You must specify a saveDir or manually save the PSet if you want +#' your download to persist past your current R session.` +#' +#' @param name \code{Character} string, the name of the PhamracoSet to download. +#' Note that this is not the dataset name, but the PSet name - dataset names are +#' not guaranteed to be unique. +#' @param saveDir \code{Character} string with the folder path where the +#' PharmacoSet should be saved. Defaults to `tempdir()`. Will create +#' directory if it does not exist. +#' @param pSetFileName \code{character} string, the file name to save the +#' dataset under +#' @param verbose \code{bool} Should status messages be printed during download. +#' Defaults to TRUE. +#' @param timeout \code{numeric} Parameter that lets you extend R's default timeout for +#' downloading large files. Defaults for this function to 600. +#' @return A PSet object with the dataset +#' +#' @export +#' @importFrom downloader download +downloadPSet <- function(name, saveDir=tempdir(), pSetFileName=NULL, + verbose=TRUE, timeout=600) { + + # change the download timeout since the files are big + opts <- options() + options(timeout=timeout) + on.exit(options(opts)) + + pSetTable <- availablePSets(canonical=FALSE) + + whichx <- match(name, pSetTable[, ""PSet Name""]) + if (is.na(whichx)) { + stop('Unknown Dataset. Please use the availablePSets() function for the table of available PharamcoSets.') + } + + if (!file.exists(saveDir)) { + dir.create(saveDir, recursive=TRUE) + } + + if (is.null(pSetFileName)){ + pSetFileName <- paste(pSetTable[whichx,""PSet Name""], "".rds"", sep="""") + } + if (!file.exists(file.path(saveDir, pSetFileName))) { + downloader::download(url = as.character(pSetTable[whichx,""Download""]), + destfile=file.path(saveDir, pSetFileName), + quiet=!verbose, + mode='wb') + } + pSet <- readRDS(file.path(saveDir, pSetFileName)) + pSet <- updateObject(pSet) + saveRDS(pSet, file=file.path(saveDir, pSetFileName)) + return(pSet) +} + +#' @importFrom utils read.table write.table +.createPSetEntry <- function(pSet, outfn) { + + if(file.exists(outfn)){ + pSetTable <- read.table(outfn, as.is=TRUE) + newrow <- c(name(pSet), pSet@datasetType, paste(names(pSet@molecularProfiles), collapse=""/""), pSet@annotation$dateCreated, NA) + pSetTable <- rbind(pSetTable, newrow) + rownames(pSetTable) <- pSetTable[,1] + write.table(pSetTable, file=outfn) + } else { + newrow <- c(name(pSet), pSet@datasetType, paste(names(pSet@molecularProfiles), collapse=""/""), pSet@annotation$dateCreated, NA) + pSetTable <- t(matrix(newrow)) + colnames(pSetTable) <- c(""PSet.Name"",""Dataset.Type"",""Available.Molecular.Profiles"",""Date.Updated"",""URL"") + rownames(pSetTable) <- pSetTable[,1] + write.table(pSetTable, file=outfn) + } +} +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat.R",".R","89","7","Sys.unsetenv(""R_TESTS"") + +library(testthat) +library(PharmacoGx) + +test_check(""PharmacoGx"") +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_summarizeSensitivityProfiles.R",".R","2883","60","library(PharmacoGx) + +context(""Checking summarizeSensitivityProfiles function."") + +data(""GDSCsmall"") + +## FIXME:: No S4 method for summarizeSensitivityProfiles with class 'missing' +#test_that(""Summarize Sensitivity Profiles fails gracefully."", { +# expect_error(summarizeSensitivityProfiles(), ""argument \""pSet\"" is missing"") +#}) + + +test_that(""Summarize Sensitivity Profiles function outputs data with right dimensions and dimnames, class"", { + testSummary <- summarizeSensitivityProfiles(GDSCsmall) + expect_equal(colnames(testSummary), sampleNames(GDSCsmall)) + expect_equal(rownames(testSummary), treatmentNames(GDSCsmall)) + expect_equivalent(is(testSummary, ""matrix""), TRUE) +}) + +test_that(""summarizeSensitivityProfiles produces correct values."",{ + + GDSCsmall2 <- subsetTo(GDSCsmall, drugs=""AZD6482"") + testCells <- sensitivityProfiles(GDSCsmall2)[order(sensitivityInfo(GDSCsmall2)$sampleid),""auc_recomputed"", drop=FALSE] + + testSummary <- summarizeSensitivityProfiles(GDSCsmall2, summary.stat = ""median"", fill.missing=FALSE) + testSummary <- testSummary[order(names(testSummary))] + names(testSummary)<- NULL + expect_equivalent(testSummary, mapply(function(x,y) {median(c(x,y))}, testCells[seq(1,18,2),], testCells[seq(1,18,2)+1,])) + + testSummary <- summarizeSensitivityProfiles(GDSCsmall2, summary.stat = ""mean"", fill.missing=FALSE) + testSummary <- testSummary[order(names(testSummary))] + names(testSummary)<- NULL + expect_equivalent(testSummary, mapply(function(x,y) {mean(c(x,y))}, testCells[seq(1,18,2),], testCells[seq(1,18,2)+1,])) + + testSummary <- summarizeSensitivityProfiles(GDSCsmall2, summary.stat = ""first"", fill.missing=FALSE) + testSummary <- testSummary[order(names(testSummary))] + names(testSummary)<- NULL + expect_equivalent(testSummary, mapply(function(x,y) {x}, testCells[seq(1,18,2),], testCells[seq(1,18,2)+1,])) + + testSummary <- summarizeSensitivityProfiles(GDSCsmall2, summary.stat = ""last"", fill.missing=FALSE) + testSummary <- testSummary[order(names(testSummary))] + names(testSummary)<- NULL + expect_equivalent(testSummary, mapply(function(x,y) {y}, testCells[seq(1,18,2),], testCells[seq(1,18,2)+1,])) + +}) + + +test_that(""Summarize Sensitivity Profiles parameters work as expected"", { + expect_silent(summarizeSensitivityProfiles(GDSCsmall, verbose = FALSE)) + expect_equal(ncol(summarizeSensitivityProfiles(GDSCsmall, fill.missing = FALSE)), length(unique(sensitivityInfo(GDSCsmall)$sampleid))) + expect_equal(ncol(summarizeSensitivityProfiles(GDSCsmall, fill.missing = TRUE)), length(sampleNames(GDSCsmall))) +}) + +test_that(""summarizeSensitivityProfiles handles max.conc via updateMaxConc"", { + res <- summarizeSensitivityProfiles(GDSCsmall, sensitivity.measure = ""max.conc"", verbose = FALSE) + expect_true(is.matrix(res)) + expect_equal(ncol(res), length(sampleNames(GDSCsmall))) + expect_equal(nrow(res), length(treatmentNames(GDSCsmall))) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_PharmacoSet_utils.R",".R","695","31","library(PharmacoGx) +library(testthat) +data(CCLEsmall) + +# -- +context(""Testing PharmacoSet subset methods..."") + +test_that('subsetByTreatment works...', { + expect_true({ + treatments <- treatmentNames(CCLEsmall)[1:5] + suppressMessages({ + CCLE_sub <- subsetByTreatment(CCLEsmall, treatments) + }) + all(treatmentNames(CCLE_sub) %in% treatments) + }) +}) + +test_that('subsetBySample works...', { + expect_true({ + samples <- sampleNames(CCLEsmall)[1:5] + suppressMessages({ + CCLE_sub <- subsetBySample(CCLEsmall, samples) + }) + all(sampleNames(CCLE_sub) %in% samples) + }) +}) + +test_that('subsetByFeature works...', { + +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_Hill.R",".R","322","13","library(PharmacoGx) + +context(""Testing .Hill function"") + +test_that(""Returns right maths"",{ + + expect_equal(.Hill(0, c(1, 0, -Inf)), 0) + expect_equal(.Hill(0, c(0, 0, 0)), 1/2) + expect_equal(.Hill(0, c(1, 0, Inf)), 1) + expect_equal(.Hill(-Inf, c(1, 0.2, 1)), 1) + expect_equal(.Hill(Inf, c(1, 0.2, 1)), 0.2) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_drugPerturbationSig.R",".R","333","10","library(PharmacoGx) +require(parallel) +context(""Checking drugPerturbationSig."") + +test_that(""Perturbation result did not change since last time"", { + data(CMAPsmall) + drug.perturbation <- drugPerturbationSig(CMAPsmall, mDataType=""rna"", nthread=1) + expect_equal_to_reference(drug.perturbation@.Data, ""drug.perturbationSmall.rds"") +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_summarizeMolecularProfiles.R",".R","3058","56","library(PharmacoGx) +library(SummarizedExperiment) +library(S4Vectors) + +context(""Checking summarizeMolecularProfiles function."") + +data(""GDSCsmall"") + +test_that(""Summarize Molecular Profiles fails gracefully."",{ + ## FIXME:: No method defition for summarizeMolecularProfiles with class 'missing' + #expect_error(summarizeMolecularProfiles(), ""argument \""pSet\"" is missing"") + expect_error(summarizeMolecularProfiles(GDSCsmall), ""argument \""mDataType\"" is missing"") + expect_error(summarizeMolecularProfiles(GDSCsmall, ""rnaseq""), ""Invalid mDataType"") +}) + +test_that(""Summarize Molecular Profiles function outputs data with right dimensions and dimnames, class"", { + testSummary <- summarizeMolecularProfiles(GDSCsmall, ""rna"") + expect_equal(colnames(testSummary), sampleNames(GDSCsmall)) + expect_equivalent(is(testSummary, ""SummarizedExperiment""), TRUE) + expect_length(rownames(testSummary), 300) +}) + +test_that(""Summarize Molecular Profiles correctly summarizes replicates"", { + myx <- ""647-V"" == colData(molecularProfilesSlot(GDSCsmall)$rna)$sampleid + testCells <- SummarizedExperiment::assay(molecularProfilesSlot(GDSCsmall)$rna, 1)[,myx] + testSummary <- summarizeMolecularProfiles(GDSCsmall, ""rna"", summary.stat = ""median"") + expect_equal(SummarizedExperiment::assay(testSummary, 1)[,""647-V""], apply(testCells, 1, median)) + testSummary <- summarizeMolecularProfiles(GDSCsmall, ""rna"", summary.stat = ""mean"") + expect_equal(SummarizedExperiment::assay(testSummary, 1)[,""647-V""], apply(testCells, 1, mean)) + testSummary <- summarizeMolecularProfiles(GDSCsmall, ""rna"", summary.stat = ""first"") + expect_equal(SummarizedExperiment::assay(testSummary, 1)[,""647-V""], testCells[,1]) + testSummary <- summarizeMolecularProfiles(GDSCsmall, ""rna"", summary.stat = ""last"") + expect_equal(SummarizedExperiment::assay(testSummary, 1)[,""647-V""], testCells[,-1]) + + GDSCsmall2 <- subsetTo(GDSCsmall, cells = c(""22RV1"", ""23132-87"")) + colData(molecularProfilesSlot(GDSCsmall2)$mutation)$sampleid <- ""22RV1"" + testCells <- SummarizedExperiment::assay(molecularProfilesSlot(GDSCsmall2)$mutation, 1) + + testSummary <- summarizeMolecularProfiles(GDSCsmall2, ""mutation"", summary.stat = ""or"") + expect_equal(sum(as.numeric(SummarizedExperiment::assay(testSummary, 1)), na.rm=TRUE), 2) + + testSummary <- summarizeMolecularProfiles(GDSCsmall2, ""mutation"", summary.stat = ""and"") + expect_equal(sum(as.numeric(SummarizedExperiment::assay(testSummary, 1)), na.rm=TRUE), 0) + +}) + + +test_that(""Summarize Molecular Profiles parameters work as expected"", { + expect_equal(summarizeMolecularProfiles(GDSCsmall, ""rna"", summarize=FALSE), molecularProfilesSlot(GDSCsmall)$rna) + expect_silent(summarizeMolecularProfiles(GDSCsmall, ""rna"", verbose = FALSE)) + GDSCsmall2 <- GDSCsmall + molecularProfilesSlot(GDSCsmall2)$rna <- molecularProfilesSlot(GDSCsmall2)$rna[,1] + expect_equivalent(ncol(summarizeMolecularProfiles(GDSCsmall2, ""rna"", fill.missing = FALSE)), 1) + expect_equivalent(ncol(summarizeMolecularProfiles(GDSCsmall2, ""rna"", fill.missing = TRUE)), length(sampleNames(GDSCsmall2))) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_sanitizeInput.R",".R","3476","48","library(PharmacoGx) + +context(""Checking the sanitization of input to curve fitting and sensitivity summary funcitons"") + +test_that(""Function sanitizeInput handles no input correctly."", { + expect_error(sanitizeInput(), ""Both 'Hill_fit' and 'viability'"") +}) + +test_that(""Function sanitizeInput yells at user sufficiently."", { + expect_error(PharmacoGx:::sanitizeInput(conc=c(-3,-2,-1,0,1,2,3),viability=c(100,90,80,70,60,50,40),conc_as_log = FALSE,viability_as_pct = TRUE, verbose=TRUE)) + expect_error(PharmacoGx:::sanitizeInput(conc=c(-3,-2,-1),viability=c(100,90,80,70,60,50,40),conc_as_log = FALSE,viability_as_pct = TRUE, verbose=TRUE)) + expect_error(PharmacoGx:::sanitizeInput(conc=c(-3,-2,-1,0,1,2,3),viability=c(100,90,80,70),conc_as_log = FALSE,viability_as_pct = TRUE, verbose=TRUE)) + expect_warning(PharmacoGx:::sanitizeInput(conc=c(-3,-2,-1,0,1,2,3),viability=c(100,90,80,70,60,50,40),conc_as_log = TRUE,viability_as_pct = FALSE, verbose=TRUE), ""'viability_as_pct' flag may be set incorrectly"") +}) + +test_that(""Function sanitizeInput returns correct values."", { + expect_equal(PharmacoGx:::sanitizeInput(conc=c(-3,-2,-1,0,1,2,3), + viability=c(100,90,80,70,60,50,40), + conc_as_log = TRUE, + viability_as_pct = TRUE, + verbose=TRUE), list(log_conc=c(-3,-2,-1,0,1,2,3),viability=c(100,90,80,70,60,50,40)/100)) + expect_equal(PharmacoGx:::sanitizeInput(conc=c(0,1,2,3), + viability=c(100,90,80,70), + conc_as_log = FALSE, + viability_as_pct = TRUE, + verbose=TRUE), list(log_conc=log10(c(1,2,3)),viability=c(90,80,70)/100)) + expect_equal(PharmacoGx:::sanitizeInput(conc=c(0,1,2,3), + viability=c(100,90,80,70)/100, + conc_as_log = FALSE, + viability_as_pct = FALSE, + verbose=TRUE), list(log_conc=log10(c(1,2,3)),viability=c(90,80,70)/100)) + expect_equal(PharmacoGx:::sanitizeInput(conc=c(-3,-2,-1,0,1,2,3), + viability=c(110,90,80,70,60,50,40), + conc_as_log = TRUE, + viability_as_pct = TRUE, + verbose=FALSE), list(log_conc=c(-3,-2,-1,0,1,2,3),viability=c(100,90,80,70,60,50,40)/100)) + expect_equal(PharmacoGx:::sanitizeInput(conc=c(-3,-2,-1,0,1,2,3), + viability=c(110,90,80,70,60,50,40)/100, + conc_as_log = TRUE, + viability_as_pct = FALSE, + verbose=FALSE), list(log_conc=c(-3,-2,-1,0,1,2,3),viability=c(100,90,80,70,60,50,40)/100)) + expect_equal(PharmacoGx:::sanitizeInput(conc=c(-3,-2,-1,0,1,2,3), + viability=c(110,90,80,70,60,50,40), + conc_as_log = TRUE, + viability_as_pct = TRUE, trunc = FALSE, + verbose=FALSE), list(log_conc=c(-3,-2,-1,0,1,2,3),viability=c(110,90,80,70,60,50,40)/100)) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_drugSensitivitySig.R",".R","1187","20","library(PharmacoGx) +require(parallel) +context(""Checking drugSensitivitySig."") + +test_that(""Sensitivity result did not change since last time"", { + data(GDSCsmall) + + drug.sensitivity <- drugSensitivitySig(GDSCsmall, mDataType=""rna"", nthread=1, features = fNames(GDSCsmall, ""rna"")[seq_len(50)]) + expect_equal_to_reference(drug.sensitivity@.Data, ""drug.sensitivityGDSCSmall.rds"") + + ### TODO:: Determine why this causes 'Fatal error: length > 1 in coercion to logical' when run on Appveyor + # Added verbose = FALSE argument to correct printing issues + #drug.sensitivity <- drugSensitivitySig(GDSCsmall, mDataType=""rna"", nthread=1, features = fNames(GDSCsmall, ""rna"")[seq_len(50)], sensitivity.cutoff = 0.2, sensitivity.measure=""auc_recomputed"", verbose = FALSE) + #expect_equal_to_reference(drug.sensitivity@.Data, ""drug.sensitivity.discreteGDSCSmall.rds"", tolerance = 0.2) + + drug.sensitivity <- drugSensitivitySig(GDSCsmall, mDataType=""rna"", nthread=1, drugs=treatmentNames(GDSCsmall)[1:2], features = fNames(GDSCsmall, ""rna"")[seq_len(10)], sensitivity.measure=c(""auc_recomputed"",""auc_published"")) + expect_equal_to_reference(drug.sensitivity@.Data, ""drug.sensitivity.MANOVAGDSCSmall.rds"") + +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_computeIC50.R",".R","1992","32","library(PharmacoGx) + +context(""Checking computeIC50/ICn."") + +test_that(""Function complains when given insensible input"",{ + expect_error(computeIC50(concentration = c(1, 2, 3), + viability = c(50, 60, 70), + Hill_fit = c(1, 0, 0.1)), ""Please pass in only one"") + # expect_silent(computeIC50(concentration = c(1, 2, 3), + # # viability1 = c(50, 60, 70), + # Hill_fit2 = c(0.5, 0.2, 1))) + + expect_error(computeIC50(concentration = c(1, 2, 3, 5), viability = c(50, 60, 70)), ""is not of same length"") #should complain + expect_error(computeIC50(concentration = c(-1, 2, 3),viability = c(50, 60, 70),conc_as_log = FALSE),""'x_as_log' flag may be set incorrectly"") #should complain + ##TO-DO:: Add wanring strings to expect_warning call + expect_error(computeIC50(concentration = c(NA, ""cat"", 3), viability = c(50, 60, 70), conc_as_log = FALSE), ""real numbers"") #should complain + expect_error(computeIC50(concentration = c(1, 2, Inf), viability = c(50, 60, 70)), ""real numbers, NA-values, and/or -Inf"") #should complain + expect_warning(computeIC50(concentration = c(1, 2, 3), + viability = c(.50, .60, .70), + viability_as_pct = TRUE), ""as_pct"") #should complain + expect_error(computeIC50()) #should complain +}) + +test_that(""Functions return right values"",{ + expect_equal(computeIC50(concentration = seq(-3,3), Hill_fit=c(1,0,0), conc_as_log=TRUE, viability_as_pct=FALSE), 0) + expect_equal(computeIC50(concentration = seq(1,3), Hill_fit=c(1,0,0), conc_as_log=TRUE, viability_as_pct=FALSE), 0) + expect_equal(computeIC50(concentration = seq(1,3), Hill_fit=c(1,.9,0), conc_as_log=TRUE, viability_as_pct=FALSE), NA_real_) + expect_equal(computeIC50(concentration = seq(1,3), Hill_fit=c(1,.5,0), conc_as_log=TRUE, viability_as_pct=FALSE), Inf) + expect_equal(.Hill(computeICn(concentration = seq(1,3), Hill_fit=c(1,0,0), n=.7, conc_as_log=TRUE, viability_as_pct=FALSE), c(1,0,0)), .3) + expect_equal(computeICn(concentration = seq(1,3), Hill_fit=c(1,0,0), n=0, conc_as_log=TRUE, viability_as_pct=FALSE), -Inf) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_unionList.R",".R","755","20","library(PharmacoGx) + +##TODO:: Migrate tests to CoreGx +context(""Checking CoreGx::.unionList function."") + +test_that(""union List works as union with arbitrary number of arguments"",{ + expect_equal(CoreGx::.unionList(1,2,3,4,2,2,1), c(1,2,3,4)) + expect_equal(CoreGx::.unionList(1,2), c(1,2)) + expect_equal(CoreGx::.unionList(list(c(1,2,3), c(2,3,4), c(1,1,1))), c(1,2,3,4)) + expect_equal(CoreGx::.unionList(1), c(1)) + expect_equal(CoreGx::.unionList(), NULL) +}) + +test_that(""CoreGx::.unionList unlists things and unions properly"", { + + expect_equal(CoreGx::.unionList(list(1,2,3,4,3)), c(1,2,3,4)) + expect_equal(CoreGx::.unionList(list(1,2,3), list(4,3)), c(1,2,3,4)) + expect_equal(CoreGx::.unionList(list(1,2,3), list(4,3), list(2,2,2,2,2,2,2)), c(1,2,3,4)) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_downloadPSet.R",".R","757","24","library(PharmacoGx) +library(checkmate) +context(""Testing Download Functionality"") + +test_that(""AvailablePset Works as Expected"", { + canonical_df <- availablePSets(canonical=TRUE) + print(canonical_df) + checkmate::expect_data_frame( + canonical_df, + types= c(""character"", ""character"", ""character"", ""character"", ""list"", ""character"", ""character""), + ncols = 8, + min.rows = 1, + ) + + required_cols = c(""Dataset Name"", ""Date Created"", ""PSet Name"", ""DOI"", ""Download"") + + # the names of the df should include the required columns + expect_true(all(required_cols %in% colnames(canonical_df))) + + non_cano_df <- availablePSets(canonical=FALSE) + + # non canonical should have more rows than canonical + expect_true(nrow(non_cano_df) > nrow(canonical_df)) +})","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_intersectPSet.R",".R","1520","26","library(PharmacoGx) +require(parallel) +context(""Checking intersectPSet."") + +# ###TO-DO:: This test takes forever to run; consider making the intersections smaller +# test_that(""Intersection result did not change since last time"", { +# data(GDSCsmall) +# data(CCLEsmall) +# common <- intersectPSet(list('GDSC'=GDSCsmall, 'CCLE'=CCLEsmall), intersectOn = c(""drugs"", ""cell.lines"",""concentrations"")) +# expect_equal_to_reference(common, ""intersectedSmallData.rds"", tolerance=1e-3) +# expect_equal(sum(!is.na(common$sensitivityProfiles(CCLE)$auc_recomputed_star)),sum(!is.na(common$sensitivityProfiles(CCLE)$auc_recomputed_star))) +# expect_equal(treatmentNames(common$CCLE), treatmentNames(common$GDSC)) +# expect_equal(sampleNames(common$CCLE), sampleNames(common$GDSC)) +# }) +# +# test_that(""Strict Intersection result did not change since last time"", { +# data(GDSCsmall) +# data(CCLEsmall) +# common <- intersectPSet(list('GDSC'=GDSCsmall, 'CCLE'=CCLEsmall), intersectOn = c(""drugs"", ""cell.lines"",""concentrations""), strictIntersect=TRUE) +# expect_equal_to_reference(common, ""intersectedSmallDataStrict.rds"", tolerance=1e-3) +# expect_equal(sum(!is.na(common$sensitivityProfiles(CCLE)$auc_recomputed_star)),sum(!is.na(common$sensitivityProfiles(CCLE)$auc_recomputed_star))) +# expect_equal(treatmentNames(common$CCLE), treatmentNames(common$GDSC)) +# expect_equal(sampleNames(common$CCLE), sampleNames(common$GDSC)) +# expect_equal(rownames(sensitivityProfiles(common$GDSC)), rownames(common$sensitivityProfiles(CCLE))) +# }) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_PharmacoSetClass.R",".R","4174","124","library(PharmacoGx) +require(parallel) +context(""Checking PharmacoSet Class Methods."") + + +test_that(""cellInfo result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(sampleInfo(GDSCsmall), ""cellInfo.GDSCsmall.rds"") +}) + +test_that(""drugInfo result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(treatmentInfo(GDSCsmall), ""drugInfo.GDSCsmall.rds"") +}) + +test_that(""phenoInfo result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(phenoInfo(GDSCsmall, ""rna""), ""phenoInfo.GDSCsmall.rds"") +}) + +test_that(""molecularProfiles result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(molecularProfiles(GDSCsmall, ""rna""), ""molecularProfiles.GDSCsmall.rds"") +}) + +test_that(""featureInfo result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(featureInfo(GDSCsmall, ""rna""), ""featureInfo.GDSCsmall.rds"") +}) + +test_that(""sensitivityInfo result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(sensitivityInfo(GDSCsmall), ""sensitivityInfo.GDSCsmall.rds"") +}) + +test_that(""sensitivityProfiles result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(sensitivityProfiles(GDSCsmall), ""sensitivityProfiles.GDSCsmall.rds"") +}) + + +test_that(""sensitivityMeasures result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(sensitivityMeasures(GDSCsmall), ""sensitivityMeasures.GDSCsmall.rds"") +}) + + +test_that(""drugNames result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(treatmentNames(GDSCsmall), ""drugNames.GDSCsmall.rds"") +}) + +test_that(""cellNames result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(sampleNames(GDSCsmall), ""cellNames.GDSCsmall.rds"") +}) + + +test_that(""fNames result did not change since last time"", { + data(GDSCsmall) + expect_equal_to_reference(fNames(GDSCsmall, ""rna""), ""fNames.GDSCsmall.rds"") +}) + + +test_that(""name result did not change since last time"", { + data(GDSCsmall) + expect_equal(name(GDSCsmall), ""GDSC"") +}) + +test_that(""updateSampleId works without duplicates"", { + data(GDSCsmall) + newNames <- c(""Test"",""Test2"",sampleNames(GDSCsmall)[3:length(sampleNames(GDSCsmall))]) + + + sampleNames(GDSCsmall) <- newNames + + expect_true(all(unique(sensitivityInfo(GDSCsmall)$sampleid) %in% newNames)) + expect_true(all(unique(sensitivityInfo(GDSCsmall)$sampleid) %in% newNames)) + expect_equal(sort(unique(rownames(sampleInfo(GDSCsmall)))), sort(newNames)) + expect_equal(sort(rownames(sensNumber(GDSCsmall))), sort(newNames)) + +}) + + +test_that(""updateSampleId works with duplicates"", { + data(GDSCsmall) + newNames <- c(""Test"",""Test"",sampleNames(GDSCsmall)[3:length(sampleNames(GDSCsmall))]) + + + expect_warning(sampleNames(GDSCsmall) <- newNames, ""Duplicated ids passed to updateSampleId. Merging old ids into the same identifier"") + + expect_true(all(unique(sensitivityInfo(GDSCsmall)$sampleid) %in% newNames)) + expect_equal(sort(unique(rownames(sampleInfo(GDSCsmall)))), sort(unique(newNames))) + expect_equal(sort(rownames(sensNumber(GDSCsmall))), sort(unique(newNames))) + +}) + + + +test_that(""updateTreatmentId works without duplicates"", { + data(GDSCsmall) + newNames <- c(""Test"",""Test2"",treatmentNames(GDSCsmall)[3:length(treatmentNames(GDSCsmall))]) + + treatmentNames(GDSCsmall) <- newNames + + expect_true(all(unique(sensitivityInfo(GDSCsmall)$treatmentid) %in% newNames)) + expect_equal(sort(unique(rownames(treatmentInfo(GDSCsmall)))), sort(newNames)) + expect_equal(sort(colnames(sensNumber(GDSCsmall))), sort(newNames)) + +}) + + +test_that(""updateTreatmentId works with duplicates"", { + data(GDSCsmall) + newNames <- c(""Test"",""Test"",treatmentNames(GDSCsmall)[3:length(treatmentNames(GDSCsmall))]) + + expect_warning(treatmentNames(GDSCsmall) <- newNames, + ""Duplicated ids passed to updateTreatmentId. Merging old ids into the same identifier"") + + expect_true(all(unique(sensitivityInfo(GDSCsmall)$treatmentid) %in% newNames)) + expect_equal(sort(unique(rownames(treatmentInfo(GDSCsmall)))), sort(unique(newNames))) + expect_equal(sort(colnames(sensNumber(GDSCsmall))), sort(unique(newNames))) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_subsetTo.R",".R","397","11","library(PharmacoGx) + +context(""Checking subset."") + +test_that(""Intersection result did not change since last time"", { +data(CCLEsmall) +CCLEsmaller <- subsetTo(CCLEsmall, drugs=treatmentNames(CCLEsmall), cells=sampleNames(CCLEsmall)) +expect_equal(CCLEsmaller@annotation, CCLEsmall@annotation) +expect_equal(attributes(CCLEsmaller@molecularProfiles$rna), attributes(CCLEsmall@molecularProfiles$rna)) +}) +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_computeABC.R",".R","2275","64","library(PharmacoGx) + +context(""Checking computeABC."") + +test_that(""Function complains when given insensible input"",{ + + expect_error(computeABC(conc1 = c(1, 2, 3), + conc2 = c(1, 2, 3), + viability1 = c(50, 60, 70), + viability2 = c(40, 90, 10), + Hill_fit1 = c(1, 0, 0.1), + Hill_fit2 = c(0.5, 0.2, 1)), ""Please pass in only one"") + # expect_silent(computeABC(conc1 = c(1, 2, 3), + # conc2 = c(1, 2, 3), + # viability1 = c(50, 60, 70), + # Hill_fit2 = c(0.5, 0.2, 1))) + + expect_error(computeABC(conc1 = c(1, 2,3), + conc2 = c(1, 2, 3, 4), + viability1 = c(50, 60, 70), + viability2 = c(40, 90, 10)), ""is not of same length"") #should complain + expect_error(computeABC(conc1 = c(-1, 2, 3), + conc2 = c(1, -2, 3), + viability1 = c(50, 60, 70), + viability2 = c(40, 90, 10), + conc_as_log = FALSE)) #should complain + ##TO-DO::Add warning string to expect_warning call + expect_error(computeABC(conc1 = c(NA, ""cat"", 3), + conc2 = c(1, -2, 3), + viability1 = c(50, 60, 70), + viability2 = c(40, 90, 10), + conc_as_log = FALSE)) #should complain + expect_error(computeABC(conc1 = c(1, 2, 3), + conc2 = c(1, -2, 3), + viability1 = c(50, 60, 70), + viability2 = c(40, 90, 10), + verbose = NA)) #should complain + expect_error(computeABC(conc1 = c(1, 2, 3), + conc2 = c(1, -2, 3), + viability1 = c(50, 60, 70))) #should complain + expect_error(computeABC(conc1 = c(1, 2, Inf), + conc2 = c(1, -2, 3), + viability1 = c(50, 60, 70), + viability2 = c(40, 90, 10))) #should complain + ##TO-DO::Add warning string to expect_warning call + expect_warning(expect_error(computeABC(conc1 = c(1, 2, 3), + conc2 = c(1, -2, 3), + viability1 = c(.50, .60, .70), + viability2 = c(.40, .90, .10), + viability_as_pct = TRUE))) #should complain + expect_warning(computeABC(conc1 = c(1, 2, 3), + conc2 = c(1, 2, 3), + viability1 = c(.50, .60, .70), + viability2 = c(.40, .90, .10), + viability_as_pct = TRUE)) #should complain + expect_error(computeABC()) #should complain +}) + +test_that(""Function values make sense"",{ + expect_equal(computeABC(conc1=c(-1,0,1), conc2=c(-1,0,1), Hill_fit1=c(0,1,0), Hill_fit2=c(1,0,0), conc_as_log=TRUE, viability_as_pct=FALSE), 0.5) + expect_equal(computeABC(conc1=c(-1,0,1), conc2=c(-1,0,1), Hill_fit1=c(0,1,0), Hill_fit2=c(0,1,0), conc_as_log=TRUE, viability_as_pct=FALSE), 0) +}) + +","R" +"Pharmacogenomics","bhklab/PharmacoGx","tests/testthat/test_logLogisticRegression.R",".R","3724","63","library(PharmacoGx) + +context(""Testing LogLogisticRegression."") + +##TO-DO::Supress print to console from this test file + +test_that(""Errors are checked."",{ + + expect_error(logLogisticRegression(c(1, 2, 3), c(50, 60))) #should complain + expect_warning(logLogisticRegression(c(1, 2, 3), c(70, 60, 50), viability_as_pct = FALSE)) #should complain + expect_error(logLogisticRegression(c(-1, 2, 3), c(70, 60, 50), conc_as_log = FALSE)) #should complain + + expect_error(logLogisticRegression(c(1, 2, 3), c(70, 60, 50), median_n = 0)) #should complain + expect_error(logLogisticRegression(c(1, 2, 3), c(50, 60, 70), median_n = 3/2)) #should complain + expect_error(logLogisticRegression(c(1, 2, 3), c(50, 60, 70), density = c(1, 1))) #should complain + expect_error(logLogisticRegression(c(1, 2, 3), c(50, 60, 70), density = c(1, 1, -1))) #should complain + expect_error(logLogisticRegression(c(1, 2, 3), c(50, 60, 70), precision = 0)) #should complain + expect_error(logLogisticRegression(c(1, 2, 3), c(50, 60, 70), scale = 0)) #should complain + expect_error(logLogisticRegression(c(1, 2, 3), c(50, 60, 70), lower_bounds = c(0, 0, 0), upper_bounds = c(1, 1, -1))) #should complain + expect_error(logLogisticRegression(c(1, 2, 3), c(50, 60, 70), family = ""The Addams Family"")) #should complain +}) + +test_that(""Values returned as expected (previous runs of function)."",{ + + expect_equivalent( + logLogisticRegression(seq(-10,10,0.1), .Hill(seq(-10,10,0.1), c(1,0,0)) + , conc_as_log=TRUE, viability_as_pct = FALSE), list(1,0,0)) + + expect_equivalent( + logLogisticRegression(seq(-10,10,0.1), .Hill(seq(-10,10,0.1), c(1,0,0)) + , conc_as_log=TRUE, viability_as_pct = FALSE, family=""Cauchy""), list(1,0,0)) + + expect_equal(logLogisticRegression(c(0.1,1, 2, 3,10), c(99,70, 60, 50,40)), + structure(list(HS = 1.28651256396627, E_inf = 36.2653101620223, EC50 = 1.1810533048852), Rsquare = 0.994776857838702), + tolerance=1e-3) #should run with no objections + + expect_equal(logLogisticRegression(c(0.1,1, 2, 3,10), c(99,70, 60, 50,40), family=""Cauchy""), + structure(list(HS = 1.29137210106265, E_inf = 36.32166034246, EC50 = 1.17645746710051), Rsquare = 0.994810069836551), + tolerance=1e-3) #should run with no objections + + expect_equal(logLogisticRegression(c(0.1,1, 2, 3,10), c(100,70, 60, 50,40), trunc=FALSE), + structure(structure(list(HS = 1.33880390747459, E_inf = 36.8315342784204, + EC50 = 1.17467467087487), Rsquare = 0.993325611444731), Rsquare = 0.992907719144335), + tolerance=1e-3) #should run with no objections + + expect_equal(logLogisticRegression(c(0.1,1, 2, 3,10), c(100,70, 60, 50,40), trunc=FALSE, family=""Cauchy""), + structure(list(HS = 1.33972330068866, E_inf = 36.8279821440339, EC50 = 1.17127888613006), Rsquare = 0.993391659104375), + tolerance=1e-3) #should run with no objections + + ## These next few tests make sure trunc is doing something sensible + expect_equal(logLogisticRegression(c(0.1, 1, 2, 3), c(110, 70, 60, 50), family=""Cauchy"", trunc=FALSE), + structure(list(HS = 1.83941027802297, E_inf = 46.2252841409534, EC50 = 0.929240163785174), Rsquare = 0.950154102951421), + tolerance=1e-3) #should run with no objections + + expect_equal(logLogisticRegression(c(0.1, 1, 2, 3), c(110, 70, 60, 50), family=""Cauchy"", trunc=TRUE), + structure(list(HS = 2.06741101065827, E_inf = 48.0764684303728, EC50 = 0.900808050726654), Rsquare = 0.986745954925997), + tolerance=1e-3) #should run with no objections + + expect_equivalent(logLogisticRegression(c(0.1, 1, 2, 3), c(100, 70, 60, 50), trunc=TRUE), + logLogisticRegression(c(0.1, 1, 2, 3), c(500, 70, 60, 50), trunc=TRUE)) + +}) +","R"