Esempio n. 1
0
    def calculateTarget(self, objId1):
        self.profilesInVivo, self.sampleNames = self.getInVivoProfiles()

        self.createOutputExperiment()

        # Compute all pairs
        for profileInVivo, sampleName in izip(self.profilesInVivo,
                                              self.sampleNames):
            tvivo = profileInVivo[0]
            Fabs = profileInVivo[1]
            FabsUnique, tvivoUnique = uniqueFloatValues(Fabs, tvivo)
            BFabs = InterpolatedUnivariateSpline(tvivoUnique, FabsUnique, k=1)

            tmax = np.max(tvivoUnique)
            deltaT = np.min([(tmax + 1) / 1000, 1.0])
            tvivop = np.arange(0, tmax + 1, deltaT)
            Fabsp = BFabs(tvivop)

            tvitro = self.k.get() * np.power(tvivop - self.t0.get(),
                                             self.alpha.get())
            Adissol = np.clip((Fabsp - self.B.get()) / self.A.get(), 0, None)
            if self.saturate:
                Adissol = np.clip(Adissol, None, 100.0)

            self.AdissolUnique, self.tvitroUnique = uniqueFloatValues(
                Adissol, tvitro)

            self.addSample("target_%s" % sampleName)

        self.outputExperiment.write(self._getPath("experiment.pkpd"))
Esempio n. 2
0
    def predict(self, tvivoUnique, tvitroUnique, tvivoXUnique, tvitroXUnique,
                adissolXUnique0, fabsXUnique0, FabsUnique, AdissolUnique,
                tvivoMin, tvivoMax):
        self.tvivoUnique = tvivoUnique
        self.tvitroUnique = tvitroUnique

        # Recover variables
        for prm in self.coeffTimeList + self.coeffResponseList:
            if not prm.startswith("tvivo") and not prm.startswith(
                    "tvitro") and not prm.startswith(
                        'adissol') and not prm.startswith('fabs'):
                exec("%s=self.prm_%s" %
                     (prm, prm))  # These are not spline parameters

        # Forward error
        if self.parsedTimeOperation is None:
            # Splines for time
            Bt = InterpolatedUnivariateSpline(tvivoXUnique, tvitroXUnique, k=1)
            self.tvitroUnique1 = Bt(tvivoUnique)
        else:
            t = tvivoUnique
            self.tvitroUnique1 = eval(self.parsedTimeOperation)

        self.tvitroReinterpolated = np.clip(self.tvitroUnique1, self.tvitroMin,
                                            self.tvitroMax)
        self.AdissolReinterpolated = self.BAdissol(self.tvitroReinterpolated)

        if self.parsedResponseOperation is None:
            adissolXUnique = self.AdissolMaxx * adissolXUnique0
            fabsXUnique = self.FabsMaxx * fabsXUnique0
            BA = InterpolatedUnivariateSpline(adissolXUnique, fabsXUnique, k=1)
            FabsPredicted = BA(self.AdissolReinterpolated)
        else:
            Adissol = self.AdissolReinterpolated
            FabsPredicted = eval(self.parsedResponseOperation)
        self.FabsUnique = FabsUnique
        self.AdissolUnique = AdissolUnique
        self.FabsPredicted = np.clip(FabsPredicted, 0.0, 100)

        # Backward error
        tvitroAux, tvivoAux = uniqueFloatValues(self.tvitroUnique1,
                                                tvivoUnique)
        Btinv = InterpolatedUnivariateSpline(tvitroAux, tvivoAux, k=1)
        self.tvivoReinterpolated = np.clip(Btinv(tvitroUnique), tvivoMin,
                                           tvivoMax)
        self.FabsReinterpolated = self.BFabs(self.tvivoReinterpolated)
        FabsPredictedAux, AdissolAux = uniqueFloatValues(
            self.FabsPredicted, self.AdissolReinterpolated)
        Bfinv = InterpolatedUnivariateSpline(FabsPredictedAux, AdissolAux, k=1)
        self.AdissolPredicted = np.clip(Bfinv(self.FabsReinterpolated), 0.0,
                                        100)
Esempio n. 3
0
 def getParameters(self, x, i0, parameterList, vitroPrefix):
     # print("Unsorted x",x)
     # Get parameters from x
     vitroX = []
     vivoX = []
     i = i0
     for prm in parameterList:
         if prm.startswith(vitroPrefix):
             vitroX.append(x[i])
         else:
             vivoX.append(x[i])
         i += 1
     vitroX = np.sort(vitroX)
     vivoX = np.sort(vivoX)
     i = i0
     it = 0
     iv = 0  # Copy the sorted vector back to x
     for prm in parameterList:
         if prm.startswith(vitroPrefix):
             x[i] = vitroX[it]
             it += 1
         else:
             x[i] = vivoX[iv]
             iv += 1
         i += 1
     vitroX = np.concatenate([[0.0], vitroX, [1.0]])
     vivoX = np.concatenate([[0.0], vivoX, [1.0]])
     tvivoXUnique, tvitroXUnique = uniqueFloatValues(vivoX, vitroX)
     # print("Sorted x",x)
     return tvivoXUnique, tvitroXUnique, i
Esempio n. 4
0
    def getSummary(self,fnPKPD):
        experiment = PKPDExperiment()
        experiment.load(fnPKPD)
        self.timeVarName = experiment.getTimeVariable()
        self.CVarName = experiment.getMeasurementVariables()[0] # The first one

        xmin = 1e38
        xmax = -1e38
        for sampleName, sample in experiment.samples.items():
            xValues, _ = self.getPlotValues(sample)
            xmin = min(xmin, min(xValues))
            xmax = max(xmax, max(xValues))

        dataDict = {}  # key will be time values
        xrange = np.arange(xmin, xmax, (xmax - xmin) / 300.0)
        for sampleName, sample in experiment.samples.items():
            xValues, yValues = self.getPlotValues(sample)
            xValuesUnique, yValuesUnique = uniqueFloatValues(xValues, yValues)
            B = InterpolatedUnivariateSpline(xValuesUnique, yValuesUnique, k=1)
            yrange = B(xrange)
            for x, y in izip(xrange, yrange):
                if x in dataDict:
                    dataDict[x].append(y)
                else:
                    dataDict[x] = [y]

        sortedTime = sorted(dataDict.keys())
        # We will store five values (min, 25%, 50%, 75%, max)
        # for each of the time entries computed
        percentileList = [0, 25, 50, 75, 100]
        Y = np.zeros((len(sortedTime), 5))
        for i, t in enumerate(sortedTime):
            Y[i, :] = np.percentile(dataDict[t], percentileList)
        return sortedTime, Y
Esempio n. 5
0
    def _onPlotSummaryClick(self, e=None):
        sampleKeys = self.samplesTree.selection()
        n = len(sampleKeys)

        if n == 1:
            self.showInfo("Please select several samples to plot.")
        else:
            if n > 1:
                samples = [self.experiment.samples[k] for k in sampleKeys]
            else:
                samples = list(self.experiment.samples.values())

            xmin = 1e38
            xmax = -1e38
            for s in samples:
                xValues, _ = self.getPlotValues(s)
                xmin = min(xmin, min(xValues))
                xmax = max(xmax, max(xValues))

            dataDict = {}  # key will be time values
            xrange = np.arange(xmin, xmax, (xmax - xmin) / 300.0)
            for s in samples:
                xValues, yValues = self.getPlotValues(s)
                xValuesUnique, yValuesUnique = uniqueFloatValues(
                    xValues, yValues)
                B = InterpolatedUnivariateSpline(xValuesUnique,
                                                 yValuesUnique,
                                                 k=1)
                yrange = B(xrange)
                for x, y in izip(xrange, yrange):
                    if x in dataDict:
                        dataDict[x].append(y)
                    else:
                        dataDict[x] = [y]

            sortedTime = sorted(dataDict.keys())
            # We will store five values (min, 25%, 50%, 75%, max)
            # for each of the time entries computed
            percentileList = [0, 25, 50, 75, 100]
            Y = np.zeros((len(sortedTime), 5))
            for i, t in enumerate(sortedTime):
                Y[i, :] = np.percentile(dataDict[t], percentileList)

            plotter = EmPlotter(style='seaborn-whitegrid',
                                figure=self.reuseFigure())
            # *** Pending
            ax = plotter.createSubPlot("Summary Plot", self.getTimeLabel(),
                                       self.getMeasureLabel())
            ax.plot(sortedTime, Y[:, 0], 'r--', label="Minimum")
            ax.plot(sortedTime, Y[:, 1], 'b--', label="25%")
            ax.plot(sortedTime, Y[:, 2], 'g', label="50% (Median)")
            ax.plot(sortedTime, Y[:, 3], 'b--', label="75%")
            ax.plot(sortedTime, Y[:, 4], 'r--', label="Maximum")
            ax.grid(True)

            ax.legend()
            plotter.show()
Esempio n. 6
0
    def solve(self, objId1):
        self.experiment = self.readExperiment(self.inputExperiment.get().fnPKPD)

        # Create output object
        self.outputExperiment = None

        timeRange = self.experiment.getRange(self.timeVar.get())
        for sampleName, sample in self.experiment.samples.items():
            # Get t, A
            t=np.asarray(sample.getValues(self.timeVar.get()),dtype=np.float64)
            A=np.asarray(sample.getValues(self.amountVar.get()),dtype=np.float64)
            if t[0]>0:
                t=np.insert(t,0,0) # Add (0,0) to the profile
                A=np.insert(A,0,0)
            t, A = uniqueFloatValues(t, A)
            if self.resampleT.get()>0:
                B = InterpolatedUnivariateSpline(t, A, k=1)
                t = np.arange(np.min(t),np.max(t)+self.resampleT.get(),self.resampleT.get())
                A = B(t)

            # Find C and Cp
            C, Cp = self.calculateConcentrations2(t,A)

            if self.outputExperiment is None:
                self.outputExperiment = PKPDExperiment()
                tvar = PKPDVariable()
                tvar.varName = "t"
                tvar.varType = PKPDVariable.TYPE_NUMERIC
                tvar.role = PKPDVariable.ROLE_TIME
                tvar.units = createUnit(self.experiment.getTimeUnits().unit)

                Cvar = PKPDVariable()
                Cvar.varName = "C"
                Cvar.varType = PKPDVariable.TYPE_NUMERIC
                Cvar.role = PKPDVariable.ROLE_MEASUREMENT
                Lunits = createUnit("L")
                Cvar.units = createUnit(divideUnits(self.experiment.getVarUnits(self.amountVar.get()),Lunits.unit))
                Cvar.comment = "Concentration central compartment"

                Cpvar = PKPDVariable()
                Cpvar.varName = "Cp"
                Cpvar.varType = PKPDVariable.TYPE_NUMERIC
                Cpvar.role = PKPDVariable.ROLE_MEASUREMENT
                Cpvar.units = createUnit(divideUnits(self.experiment.getVarUnits(self.amountVar.get()),Lunits.unit))
                Cpvar.comment = "Concentration peripheral compartment"

                self.outputExperiment.variables[tvar.varName] = tvar
                self.outputExperiment.variables[Cvar.varName] = Cvar
                self.outputExperiment.variables[Cpvar.varName] = Cpvar
                self.outputExperiment.general["title"]="Inverse Loo-Riegelman"
                self.outputExperiment.general["comment"]=""

            self.addSample(sampleName,t,C,Cp)

        self.outputExperiment.write(self._getPath("experiment.pkpd"))
Esempio n. 7
0
    def goalFunction(self, x):
        try:
            tvivoXUnique, tvitroXUnique, i0 = self.getParameters(
                x, 0, self.coeffTimeList, 'tvitro')
            tvivoXUnique = self.tvivoMax * tvivoXUnique
            tvitroXUnique = self.tvitroMax * tvitroXUnique

            fabsXUnique, adissolXUnique, _ = self.getParameters(
                x, i0, self.coeffResponseList, 'adissol')
            adissolXUnique = self.AdissolMax * adissolXUnique
            fabsXUnique = self.FabsMax * fabsXUnique

            Bt = InterpolatedUnivariateSpline(tvivoXUnique, tvitroXUnique, k=1)
            tvitroUnique = Bt(self.tvivoUnique)
            self.tvitroReinterpolated = np.clip(tvitroUnique, self.tvitroMin,
                                                self.tvitroMax)
            self.AdissolReinterpolated = self.BAdissol(
                self.tvitroReinterpolated)
            BA = InterpolatedUnivariateSpline(adissolXUnique, fabsXUnique, k=1)
            FabsPredicted = BA(self.AdissolReinterpolated)
            self.FabsPredicted = np.clip(FabsPredicted, 0.0, 100)

            tvitroAux, tvivoAux = uniqueFloatValues(tvitroUnique,
                                                    self.tvivoUnique)
            Btinv = InterpolatedUnivariateSpline(tvitroAux, tvivoAux, k=1)
            self.tvivoReinterpolated = np.clip(Btinv(self.tvitroUnique),
                                               self.tvivoMin, self.tvivoMax)
            self.FabsReinterpolated = self.BFabs(self.tvivoReinterpolated)
            FabsPredictedAux, AdissolAux = uniqueFloatValues(
                self.FabsPredicted, self.AdissolReinterpolated)
            Bfinv = InterpolatedUnivariateSpline(FabsPredictedAux,
                                                 AdissolAux,
                                                 k=1)
            self.AdissolPredicted = np.clip(Bfinv(self.FabsReinterpolated),
                                            0.0, 100)

            error = self.calculateError(x, self.tvitroReinterpolated,
                                        self.tvivoReinterpolated)
        except:
            return 1e38
        return error
Esempio n. 8
0
 def produceLevyPlot(self, tvivo, parameterInVitro, Avivo, tvitroMax):
     Avivounique, tvivoUnique = uniqueFloatValues(Avivo, tvivo)
     B = InterpolatedUnivariateSpline(Avivounique, tvivoUnique, k=1)
     tmax = 10 * np.max(tvivo)
     if self.limitTvitro.get():
         tmax = np.min([tmax, tvitroMax])
     tvitro = np.arange(0, tmax, 1)
     self.protFit.model.x = tvitro
     Avitro = self.protFit.model.forwardModel(parameterInVitro)[0]
     tvivo = []
     for i in range(tvitro.shape[0]):
         tvivo.append(B(Avitro[i]))
     return (tvitro, np.asarray(tvivo, dtype=np.float64), Avitro)
Esempio n. 9
0
 def getProfiles(self, prmExp, varNameT, varNameC):
     experiment = self.readExperiment(prmExp.fnPKPD)
     allY = []
     for sampleName, sample in experiment.samples.items():
         x = np.asarray(sample.getValues(varNameT), dtype=np.float64)
         y = np.asarray(sample.getValues(varNameC), dtype=np.float64)
         if self.resampleT.get() > 0:
             x, y = uniqueFloatValues(x, y)
             B = InterpolatedUnivariateSpline(x, y, k=1)
             xp = np.arange(np.min(x),
                            np.max(x) + self.resampleT.get(),
                            self.resampleT.get())
             y = B(xp)
             if self.keepResample.get():
                 sample.setValues(varNameT, [str(xi) for xi in xp.tolist()])
                 sample.setValues(varNameC, [str(yi) for yi in y.tolist()])
         allY.append(y)
     if self.resampleT.get() > 0 and self.keepResample.get():
         self.experiment = experiment
         self.experiment.write(self._getPath("experiment.pkpd"))
     return allY
Esempio n. 10
0
    def forwardModel(self, parameters, x=None):
        if x is None:
            x = self.x
        xToUse = x[0] if type(
            x) == list else x  # From [array(...)] to array(...)
        xToUse = np.copy(xToUse)  # Just in case it is modified
        self.yPredicted = np.zeros(xToUse.shape[0])

        if self.allowTlag:
            tlag = parameters[0]
            Vmax = parameters[1]
            tmax = parameters[2]
            coefs = parameters[3:]
            xToUse -= tlag
        else:
            Vmax = parameters[0]
            tmax = parameters[1]
            coefs = parameters[2:]

        xToUse = np.clip(xToUse, 0.0, tmax)

        if self.parametersPrepared is None or not np.array_equal(
                self.parametersPrepared, parameters):
            self.knots = np.linspace(0, tmax, self.nknots + 2)
            self.knotsY = np.append(np.insert(coefs, 0, 0), 1)
            self.knotsY = np.sort(self.knotsY)
            knotsUnique, knotsYUnique = uniqueFloatValues(
                self.knots, self.knotsY)
            # self.B=InterpolatedUnivariateSpline(knotsUnique, knotsYUnique, k=1)
            self.B = PchipInterpolator(knotsUnique, knotsYUnique)
            self.parametersPrepared = copy.copy(parameters)

        fraction = self.B(xToUse)
        fraction = np.clip(fraction, 0.0, 1.0)
        self.yPredicted = Vmax * fraction
        self.yPredicted = [self.yPredicted]  # From array(...) to [array(...)]
        return self.yPredicted
Esempio n. 11
0
    def getValues(self, experiment, expression):
        allX = []
        if self.analysisType(experiment) == 0:  # All labels
            for label in self.getLabels():
                x1 = [
                    float(x)
                    for x in experiment.getSubGroupLabels(expression, label)
                ]
                allX.append(x1)
            X = np.asarray(allX, dtype=np.double)
            return np.transpose(X)
        else:  # A measurement
            Ylabel = self.getLabels()[0]
            Xlabel = experiment.getTimeVariable()
            temp = []
            minX = 1e38
            maxX = -1e38
            for sampleName, sample in experiment.samples.items():
                x, y = sample.getXYValues(Xlabel, Ylabel)
                minX = min(minX, np.min(x))
                maxX = max(maxX, np.max(x))
                temp.append((x[0], y[0]))

            for x, y in temp:
                if self.resampleT.get() > 0:
                    x, y = uniqueFloatValues(x, y)
                    B = InterpolatedUnivariateSpline(x, y, k=1)
                    xp = np.arange(minX, maxX + self.resampleT.get(),
                                   self.resampleT.get())
                    y = B(xp)
                allX.append(y)
            X = np.asarray(allX, dtype=np.double)

            v = np.var(X, 0)
            X = X[:, v > 0]  # Remove columns with no variance
            return X
Esempio n. 12
0
    def deconvolve(self, objId1):
        self.experiment = self.readExperiment(
            self.inputExperiment.get().fnPKPD)

        # Create output object
        self.outputExperiment = PKPDExperiment()
        tvar = PKPDVariable()
        tvar.varName = "t"
        tvar.varType = PKPDVariable.TYPE_NUMERIC
        tvar.role = PKPDVariable.ROLE_TIME
        tvar.units = createUnit(self.experiment.getTimeUnits().unit)

        Avar = PKPDVariable()
        Avar.varName = "A"
        Avar.varType = PKPDVariable.TYPE_NUMERIC
        Avar.role = PKPDVariable.ROLE_MEASUREMENT
        Avar.units = createUnit("none")

        self.outputExperiment.variables[tvar.varName] = tvar
        self.outputExperiment.variables[Avar.varName] = Avar
        self.outputExperiment.general[
            "title"] = "Deconvolution of the amount released"
        self.outputExperiment.general[
            "comment"] = "Amount released at any time t"

        # Get the input sample from another experiment if necessary
        sampleFrom = None
        if self.externalIV.get() == self.ANOTHER_INPUT:
            anotherExperiment = self.readExperiment(
                self.externalIVODE.get().outputExperiment.fnPKPD)
            for _, sampleFrom in anotherExperiment.samples.items(
            ):  # Take the first sample from the reference
                break

        timeRange = self.experiment.getRange(self.timeVar.get())
        for sampleName, sample in self.experiment.samples.items():
            # Get t, Cp
            t = np.asarray(sample.getValues(self.timeVar.get()),
                           dtype=np.float64)
            Cp = np.asarray(sample.getValues(self.concVar.get()),
                            dtype=np.float64)
            Cp = np.clip(Cp, 0.0, None)
            t = np.insert(t, 0, 0)  # Add (0,0) to the profile
            Cp = np.insert(Cp, 0, 0)
            t, Cp = uniqueFloatValues(t, Cp)
            if self.resampleT.get() > 0:
                B = InterpolatedUnivariateSpline(t, Cp, k=1)
                t = np.arange(np.min(t),
                              np.max(t) + self.resampleT.get(),
                              self.resampleT.get())
                Cp = B(t)

            # Calculate AUC0t
            AUC0t = calculateAUC0t(t, Cp)
            AUC0inf = float(AUC0t[-1])

            # Calculate peripheral
            if self.externalIV.get() == self.SAME_INPUT:
                sampleFrom = sample
            Cl = float(sampleFrom.descriptors['Cl'])
            V = float(sampleFrom.descriptors['V'])
            Clp = float(sampleFrom.descriptors['Clp'])
            Vp = float(sampleFrom.descriptors['Vp'])
            k12 = Clp / V
            k21 = Clp / Vp
            Cperipheral = self.calculateCperipheral(t, Cp, k12, k21)

            # Deconvolve
            k10 = Cl / V
            A = (Cp + Cperipheral + k10 * AUC0t) / k10
            if self.normalize.get():
                A *= 100 / AUC0inf
                if self.saturate.get():
                    A = np.clip(A, None, 100.0)
            A = np.clip(A, 0, None)
            if self.smooth:
                if t[0] > 0:
                    t = np.insert(t, 0, 0)
                    A = np.insert(A, 0, 0)
                if self.saturate.get() and self.normalize.get():
                    A = np.clip(A, None, 100.0)
                A = np.clip(smoothPchip(t, A), 0, None)

            if self.considerBioaval.get() == self.BIOAVAIL_DIV:
                A /= sample.getBioavailability()
            elif self.considerBioaval.get() == self.BIOAVAIL_MULT:
                A *= sample.getBioavailability()
            self.addSample(sampleName, t, A)

        self.outputExperiment.write(self._getPath("experiment.pkpd"))
Esempio n. 13
0
    def deconvolve(self, objId):
        self.protODE = self.inputODE.get()
        self.experiment = self.readExperiment(self.protODE.outputExperiment.fnPKPD)
        self.fitting = self.readFitting(self.protODE.outputFitting.fnFitting)
        self.varNameX = self.fitting.predictor.varName
        self.varNameY = self.fitting.predicted.varName

        # Create drug source
        self.clearGroupParameters()
        self.createDrugSource()

        # Create output object
        self.outputExperiment = PKPDExperiment()
        tvar = PKPDVariable()
        tvar.varName = "t"
        tvar.varType = PKPDVariable.TYPE_NUMERIC
        tvar.role = PKPDVariable.ROLE_TIME
        tvar.units = createUnit(self.experiment.getTimeUnits().unit)

        Avar = PKPDVariable()
        Avar.varName = "A"
        Avar.varType = PKPDVariable.TYPE_NUMERIC
        Avar.role = PKPDVariable.ROLE_MEASUREMENT
        if self.normalize.get():
            Avar.units = createUnit("none")
        else:
            Avar.units = createUnit(self.experiment.getDoseUnits())

        self.outputExperiment.variables[tvar.varName] = tvar
        self.outputExperiment.variables[Avar.varName] = Avar
        self.outputExperiment.general["title"]="Deconvolution of the amount released"
        self.outputExperiment.general["comment"]="Amount released at any time t"

        # Create PK model
        timeRange = self.experiment.getRange(self.varNameX)
        deltaT = 0.5
        t = np.arange(0.0,timeRange[1]*5+deltaT,deltaT)

        model = self.protODE.createModel()
        model.setExperiment(self.experiment)
        model.deltaT = deltaT
        model.setXVar(self.varNameX)
        model.setYVar(self.varNameY)
        model.x = t
        model.t0=0
        model.tF=np.max(t)
        prmNames = model.getParameterNames()

        if len(self.experiment.samples)==0:
            print("Cannot find any sample in the experiment")
            return

        # Create unit dose
        drugSource = DrugSource()
        dose=None
        for sampleName, sample in self.experiment.samples.items():
            sample.interpretDose()
            if len(sample.parsedDoseList)>0:
                dose = createDeltaDose(1.0, via=createVia("Intravenous; iv", self.experiment),
                                       dunits=sample.parsedDoseList[0].dunits)
        if dose is None:
            print("Cannot find any dose among the samples")
            return
        drugSource.setDoses([dose], 0.0, timeRange[1])
        model.drugSource = drugSource

        # Get the input sample from another experiment if necessary
        sampleFrom = None
        if self.externalIV.get() == self.ANOTHER_INPUT:
            anotherExperiment = self.readExperiment(self.externalIVODE.get().outputExperiment.fnPKPD)
            for _, sampleFrom in anotherExperiment.samples.items(): # Take the first sample from the reference
                break

        # Simulate the different responses
        for sampleName, sample in self.experiment.samples.items():
            self.printSection("Deconvolving "+sampleName)
            drugSourceSample = DrugSource()
            drugSourceSample.setDoses(sample.parsedDoseList, 0.0, timeRange[1])

            p=[]
            tlag=0
            for paramName in drugSourceSample.getParameterNames():
                p.append(float(sample.getDescriptorValue(paramName)))
                if paramName.endswith('_tlag') and self.removeTlag.get():
                    tlag=float(sample.getDescriptorValue(paramName))
            drugSourceSample.setParameters(p)

            if self.externalIV.get()==self.SAME_INPUT:
                sampleFrom = sample
            parameters=[]
            for prmName in prmNames:
                parameters.append(float(sampleFrom.descriptors[prmName]))
            model.setParameters(parameters)
            h = model.forwardModel(parameters, [t]*model.getResponseDimension())[0]

            ts,Cs = sample.getXYValues(self.varNameX,self.varNameY)
            ts=np.insert(ts,0,0.0)
            Cs=np.insert(Cs,0,0.0)
            ts, Cs = uniqueFloatValues(ts,Cs)
            B=InterpolatedUnivariateSpline(ts, Cs, k=1)
            C=np.clip(B(t),0.0,None)

            Fabs=np.clip(np.real(ifft(np.divide(fft(C),fft(h)))),0.0,None)

            cumulatedDose=0.0
            A=t*0.0 # Allocate memory
            totalReleased = drugSourceSample.getAmountReleasedUpTo(10*t[-1]) # Divided by 100 to have a number between 0 and 100
            print("Total amount released: %f"%totalReleased)
            print("t(min) A(%s)"%Avar.units._toString())
            for i in range(t.size):
                cumulatedDose+=Fabs[i]
                A[i]=cumulatedDose
                if self.normalize.get():
                    A[i] *= 100.0/totalReleased
                print("%f %f"%(t[i],A[i]))
                # print("%f %f %f %f"%(t[i], A[i], drugSource.getAmountReleasedAt(t[i], 0.5), drugSource.getAmountReleasedUpTo(t[i] + 0.5)))
            if self.saturate.get() and self.normalize.get():
                A = np.clip(A,None,100.0)
            if self.considerBioaval.get()==self.BIOAVAIL_DIV:
                A /= sample.getBioavailability()
            elif self.considerBioaval.get()==self.BIOAVAIL_MULT:
                A *= sample.getBioavailability()
            As, ts = uniqueFloatValues(np.clip(A,0,None),t-tlag)
            self.addSample(sampleName,ts,As)

        self.outputExperiment.write(self._getPath("experiment.pkpd"))
Esempio n. 14
0
    def calculateAllIvIvC(self):
        # Get the PK and dissolution profiles from the input
        self.parametersInVitro = []
        self.vesselNames = []
        self.profilesInVivo = []
        self.sampleNames = []
        self.experimentsInVitro = []
        idx = 1
        for ptrProt in self.inputIVIVCs:
            parametersInVitro, vesselNames, tvitroMax = ptrProt.get(
            ).getInVitroModels()
            profilesInVivo, sampleNames = ptrProt.get().getInVivoProfiles()
            self.parametersInVitro.append(parametersInVitro)
            self.vesselNames.append(vesselNames)
            self.profilesInVivo.append(profilesInVivo)
            self.sampleNames.append(sampleNames)

            self.experimentInVitro = ptrProt.get().experimentInVitro
            self.experimentInVivo = ptrProt.get().experimentInVivo
            if idx == 1:
                self.varNameX = ptrProt.get().fitting.predictor.varName
                self.varNameY = ptrProt.get().fitting.predicted.varName
                self.protFit = ptrProt.get().protFit
            self.experimentsInVitro.append(self.experimentInVitro)
            idx += 1

        # Prepare all data and pairs for processing
        self.allPairs = []
        self.tvitroMaxx = -1e38
        self.tvivoMaxx = -1e38
        self.FabsMaxx = -1e38
        self.AdissolMaxx = -1e38
        for block in range(len(self.sampleNames)):
            for parameterInVitro, vesselName in izip(
                    self.parametersInVitro[block], self.vesselNames[block]):
                if "tvitroMax" in self.experimentsInVitro[block].variables:
                    tvitroMax = float(
                        self.experimentsInVitro[block].samples[vesselName].
                        getDescriptorValue("tvitroMax"))
                else:
                    tvitroMax = 1e38
                j = 0
                for self.tvivo, self.Fabs in self.profilesInVivo[block]:
                    self.FabsUnique, self.tvivoUnique = uniqueFloatValues(
                        self.Fabs, self.tvivo)
                    self.tvitro, self.Adissol = self.produceAdissol(
                        parameterInVitro,
                        min(np.max(self.tvivoUnique * 10), tvitroMax))
                    self.AdissolUnique, self.tvitroUnique = uniqueFloatValues(
                        self.Adissol, self.tvitro)
                    self.tvivoMin = np.min(self.tvivoUnique)
                    self.tvivoMax = np.max(self.tvivoUnique)
                    self.tvitroMin = np.min(self.tvitroUnique)
                    self.tvitroMax = np.max(self.tvitroUnique)
                    self.tvitroMaxx = max(self.tvitroMaxx, self.tvitroMax)
                    self.tvivoMaxx = max(self.tvivoMaxx, self.tvivoMax)
                    self.FabsMaxx = max(self.FabsMaxx, np.max(self.FabsUnique))
                    self.AdissolMaxx = max(self.AdissolMaxx,
                                           np.max(self.AdissolUnique))

                    # Make sure they are sorted in x
                    self.tvivoUnique, self.FabsUnique = uniqueFloatValues(
                        self.tvivoUnique, self.FabsUnique)
                    self.tvitroUnique, self.AdissolUnique = uniqueFloatValues(
                        self.tvitroUnique, self.AdissolUnique)
                    self.FabsMax = np.max(self.FabsUnique)
                    self.AdissolMax = np.max(self.AdissolUnique)

                    self.BAdissol = InterpolatedUnivariateSpline(
                        self.tvitroUnique, self.AdissolUnique, k=1)
                    self.BFabs = InterpolatedUnivariateSpline(self.tvivoUnique,
                                                              self.FabsUnique,
                                                              k=1)
                    self.allPairs.append([
                        self.tvivoUnique, self.tvitroUnique, self.FabsUnique,
                        self.AdissolUnique, self.BAdissol, self.BFabs,
                        self.tvitroMin, self.tvitroMax, self.tvivoMin,
                        self.tvivoMax, self.AdissolMax, self.FabsMax,
                        vesselName, self.sampleNames[j]
                    ])
                    j += 1

        # Prepare the parameter names and bounds
        if self.timeScale.get() <= 6:
            if self.timeScale.get() == 0:
                timeScaleOperation = "$(t)"
            elif self.timeScale.get() == 1:
                timeScaleOperation = "$(t)-$[t0]"
            elif self.timeScale.get() == 2:
                timeScaleOperation = "$[k]*$(t)"
            elif self.timeScale.get() == 3:
                timeScaleOperation = "$[k]*($(t)-$[t0])"
            elif self.timeScale.get() == 4:
                timeScaleOperation = "$[k]*np.power($(t),$[alpha])"
            elif self.timeScale.get() == 5:
                timeScaleOperation = "$[k]*np.power($(t)-$[t0],$[alpha])"
            else:
                timeScaleOperation = self.timeScaleOperation.get()
            self.parsedTimeOperation, self.varTimeList, self.coeffTimeList = parseOperation(
                timeScaleOperation)
            self.timeBoundsList = ProtPKPDDissolutionIVIVCGeneric.constructBounds(
                self, self.coeffTimeList, self.timeBounds.get())
        else:
            self.parsedTimeOperation = None  # It is a spline
            self.timeSplinesN = self.timeScale.get() - 6
            self.coeffTimeList = self.constructTimeCoeffs(self.timeSplinesN)
            self.timeBoundsList = ProtPKPDDissolutionIVIVCSplines.constructBounds(
                self, self.coeffTimeList, "")

        if self.responseScale.get() <= 3:
            if self.responseScale.get() == 0:
                responseScaleOperation = "$(Adissol)"
            elif self.responseScale.get() == 1:
                responseScaleOperation = "$[A]*$(Adissol)"
            elif self.responseScale.get() == 2:
                responseScaleOperation = "$[A]*$(Adissol)+$[B]"
            elif self.responseScale.get() == 3:
                responseScaleOperation = self.responseScaleOperation.get()
            self.parsedResponseOperation, self.varResponseList, self.coeffResponseList = parseOperation(
                responseScaleOperation)
            self.responseBoundsList = ProtPKPDDissolutionIVIVCGeneric.constructBounds(
                self, self.coeffResponseList, self.responseBounds.get())
        else:
            self.parsedResponseOperation = None  # It is a spline
            self.responseSplinesN = self.responseScale.get() - 3
            self.coeffResponseList = self.constructResponseCoeffs(
                self.responseSplinesN)
            self.responseBoundsList = ProtPKPDDissolutionIVIVCSplines.constructBounds(
                self, self.coeffResponseList, "")

        self.parameters = self.coeffTimeList + self.coeffResponseList
        self.bounds = self.timeBoundsList + self.responseBoundsList

        self.createOutputExperiments(set=2)

        self.verbose = False
        self.bestError = 1e38
        optimum = differential_evolution(self.goalFunction,
                                         self.bounds,
                                         popsize=50)

        # Evaluate correlation
        self.goalFunction(optimum.x)
        R = self.calculateR()

        self.addSample(2, "ivivc_all", "allSamples", "allVessels", optimum.x,
                       R)
        self.outputExperimentFabsSingle.write(
            self._getPath("experimentFabsSingle.pkpd"))

        fh = open(self._getPath("summary.txt"), "w")
        self.doublePrint(fh, "Correlation coefficient (R) %f" % R)
        self.printFormulas(fh)
        fh.close()

        # Generate Fabs and FabsPredicted for all pairs
        self.createOutputExperiments(set=1)
        tvivoXUnique, tvitroXUnique, adissolXUnique0, fabsXUnique0 = self.getAxes(
            optimum.x)
        i = 1
        for tvivoUnique, tvitroUnique, FabsUnique, AdissolUnique, BAdissol, BFabs, tvitroMin, tvitroMax, tvivoMin, tvivoMax, AdissolMax, FabsMax, vesselName, sampleName in self.allPairs:
            try:
                self.predict(tvivoUnique, tvitroUnique, tvivoXUnique,
                             tvitroXUnique, adissolXUnique0, fabsXUnique0,
                             FabsUnique, AdissolUnique, tvivoMin, tvivoMax)
                R = ProtPKPDDissolutionIVIVCSplines.calculateR(self)
                self.addSample(1, "ivivc_%d" % i, sampleName, vesselName,
                               optimum.x, R)
                i += 1
            except:
                pass
        self.outputExperimentFabs.write(self._getPath("experimentFabs.pkpd"))
        self.outputExperimentAdissol.write(
            self._getPath("experimentAdissol.pkpd"))
Esempio n. 15
0
    def calculateAllIvIvC(self, objId1, objId2):
        self.parametersInVitro, self.vesselNames, _ = self.getInVitroModels()
        self.profilesInVivo, self.sampleNames = self.getInVivoProfiles()

        self.createOutputExperiments(set=1)

        i = 1
        allt0 = []
        allk = []
        allalpha = []
        allA = []
        allB = []
        allR = []
        self.parameters = []
        self.bounds = []
        if self.timeScale.get() == 1:  # tvitro=tvivo-t0
            self.parameters.append('t0')
            self.bounds.append(self.parseBounds(self.t0Bounds.get()))
        elif self.timeScale.get() == 2:  # tvitro=k*tvivo
            self.parameters.append('k')
            self.bounds.append(self.parseBounds(self.kBounds.get()))
        elif self.timeScale.get() == 3:  # tvitro=k*(tvivo-t0)
            self.parameters.append('k')
            self.parameters.append('t0')
            self.bounds.append(self.parseBounds(self.kBounds.get()))
            self.bounds.append(self.parseBounds(self.t0Bounds.get()))
        elif self.timeScale.get() == 4:  # tvitro=k*tvivo^alpha
            self.parameters.append('k')
            self.parameters.append('alpha')
            self.bounds.append(self.parseBounds(self.kBounds.get()))
            self.bounds.append(self.parseBounds(self.alphaBounds.get()))
        elif self.timeScale.get() == 5:  # tvitro=k*(tvivo-t0)^alpha
            self.parameters.append('k')
            self.parameters.append('alpha')
            self.parameters.append('t0')
            self.bounds.append(self.parseBounds(self.kBounds.get()))
            self.bounds.append(self.parseBounds(self.alphaBounds.get()))
            self.bounds.append(self.parseBounds(self.t0Bounds.get()))
        if self.responseScale.get() >= 1:  # Linear
            self.parameters.append('A')
            self.bounds.append(self.parseBounds(self.ABounds.get()))
        if self.responseScale.get() == 2:  # Affine
            self.parameters.append('B')
            self.bounds.append(self.parseBounds(self.BBounds.get()))

        # Compute all pairs
        invitroIdx = 0
        self.verbose = False
        vitroList = []
        vivoList = []
        for parameterInVitro, vesselName in izip(self.parametersInVitro,
                                                 self.vesselNames):
            invivoIdx = 0
            if "tvitroMax" in self.experimentInVitro.variables:
                tvitroMax = float(self.experimentInVitro.samples[vesselName].
                                  getDescriptorValue("tvitroMax"))
            else:
                tvitroMax = 1e38
            for self.tvivo, self.Fabs in self.profilesInVivo:
                print("New combination %d" % i)
                self.FabsUnique, self.tvivoUnique = uniqueFloatValues(
                    self.Fabs, self.tvivo)
                self.tvitro, self.Adissol = self.produceAdissol(
                    parameterInVitro,
                    min(np.max(self.tvivoUnique * 10), tvitroMax))
                self.AdissolUnique, self.tvitroUnique = uniqueFloatValues(
                    self.Adissol, self.tvitro)
                self.tvivoMin = np.min(self.tvivoUnique)
                self.tvivoMax = np.max(self.tvivoUnique)
                self.tvitroMin = np.min(self.tvitroUnique)
                self.tvitroMax = np.max(self.tvitroUnique)

                # Make sure they are sorted in x
                self.tvivoUnique, self.FabsUnique = uniqueFloatValues(
                    self.tvivoUnique, self.FabsUnique)
                self.tvitroUnique, self.AdissolUnique = uniqueFloatValues(
                    self.tvitroUnique, self.AdissolUnique)
                vivoList.append((self.tvivoUnique, self.FabsUnique))
                vitroList.append((self.tvitroUnique, self.AdissolUnique))

                # for i in range(len(self.tvivoUnique)):
                #   print("i=",i,"tvivo[i]=",self.tvivoUnique[i],"Fabs[i]",self.FabsUnique[i])
                # for i in range(len(self.tvitroUnique)):
                #   print("i=",i,"tvitro[i]=",self.tvitroUnique[i],"Adissol[i]",self.AdissolUnique[i])

                self.BAdissol = InterpolatedUnivariateSpline(
                    self.tvitroUnique, self.AdissolUnique, k=1)
                self.BFabs = InterpolatedUnivariateSpline(self.tvivoUnique,
                                                          self.FabsUnique,
                                                          k=1)

                self.bestError = 1e38
                if len(self.bounds) > 0:
                    optimum = differential_evolution(self.goalFunction,
                                                     self.bounds,
                                                     popsize=50)
                    x = optimum.x
                else:
                    x = None
                # self.verbose=True
                self.goalFunction(x)

                j = 0
                t0 = 0.0
                k = 1.0
                A = 1.0
                B = 0.0
                for prm in self.parameters:
                    exec("%s=%f" % (prm, optimum.x[j]))
                    exec("all%s.append(%f)" % (prm, optimum.x[j]))
                    j += 1

                # Evaluate correlation
                R = self.calculateR()
                allR.append(R)

                self.addSample("ivivc_%04d" % i,
                               self.sampleNames[invivoIdx],
                               self.vesselNames[invitroIdx],
                               x,
                               R,
                               set=1)
                i += 1
                invivoIdx += 1
            invitroIdx += 1

        fh = open(self._getPath("summary.txt"), "w")
        self.summarize(fh, allt0, "t0")
        self.summarize(fh, allk, "k")
        self.summarize(fh, allalpha, "alpha")
        self.summarize(fh, allA, "A")
        self.summarize(fh, allB, "B")
        self.doublePrint(fh, " ")
        self.summarize(fh, allR, "Correlation coefficient (R)")
        self.doublePrint(fh, " ")

        if self.timeScale.get() == 0:
            timeStr = "t"
        elif self.timeScale.get() == 1:
            timeStr = "t-t0"
        elif self.timeScale.get() == 2:
            timeStr = "k*t"
        elif self.timeScale.get() == 3:
            timeStr = "k*(t-t0)"
        elif self.timeScale.get() == 4:
            timeStr = "k*t^alpha"
        elif self.timeScale.get() == 5:
            timeStr = "k*(t-t0)^alpha"
        if self.responseScale.get() == 0:
            eqStr = "Fabs(t)=Adissol(%s)" % timeStr
        elif self.responseScale.get() == 1:
            eqStr = "Fabs(t)=A*Adissol(%s)" % timeStr
        elif self.responseScale.get() == 2:
            eqStr = "Fabs(t)=A*Adissol(%s)+B" % timeStr
        self.doublePrint(fh, "IVIVC equation: %s" % eqStr)
        fh.close()

        self.outputExperimentFabs.write(self._getPath("experimentFabs.pkpd"))
        self.outputExperimentAdissol.write(
            self._getPath("experimentAdissol.pkpd"))

        # Compute single
        print("Single IVIVC")
        self.tvivoUnique, self.FabsUnique = computeXYmean(vivoList)
        self.tvitroUnique, self.AdissolUnique = computeXYmean(vitroList)
        self.tvivoUnique, self.FabsUnique = uniqueFloatValues(
            self.tvivoUnique, self.FabsUnique)
        self.tvitroUnique, self.AdissolUnique = uniqueFloatValues(
            self.tvitroUnique, self.AdissolUnique)

        self.BAdissol = InterpolatedUnivariateSpline(self.tvitroUnique,
                                                     self.AdissolUnique,
                                                     k=1)
        self.BFabs = InterpolatedUnivariateSpline(self.tvivoUnique,
                                                  self.FabsUnique,
                                                  k=1)
        self.bestError = 1e38
        if len(self.bounds) > 0:
            optimum = differential_evolution(self.goalFunction,
                                             self.bounds,
                                             popsize=50)
            x = optimum.x
        else:
            x = None
        self.goalFunction(x)
        R = self.calculateR()
        self.createOutputExperiments(set=2)
        self.addSample("ivivc_single", "AvgVivo", "AvgVitro", x, R, set=2)
        self.outputExperimentFabsSingle.write(
            self._getPath("experimentFabsSingle.pkpd"))
Esempio n. 16
0
    def runJoin(self, objId, resampleT):
        experiment = self.readExperiment(self.inputExperiment.get().fnPKPD)
        tvarName = experiment.getTimeVariable()
        mvarNames = experiment.getMeasurementVariables()
        self.experiment = PKPDExperiment()

        # General
        self.experiment.general[
            "title"] = "Average of " + experiment.general["title"]
        if self.condition.get() != "":
            self.experiment.general[
                "title"] += " Condition: %s" % self.condition.get()
        self.experiment.general["comment"] = copy.copy(
            experiment.general["comment"])
        for key, value in experiment.general.items():
            if not (key in self.experiment.general):
                self.experiment.general[key] = copy.copy(value)

        # Variables
        for key, value in experiment.variables.items():
            if not (key in self.experiment.variables):
                self.experiment.variables[key] = copy.copy(value)

        # Vias
        for key, value in experiment.vias.items():
            if not (key in self.experiment.vias):
                self.experiment.vias[key] = copy.copy(value)

        # Doses
        doseName = None
        for key, value in experiment.doses.items():
            dose = copy.copy(value)
            self.experiment.doses[dose.doseName] = dose
            doseName = dose.doseName

        # Samples
        self.printSection("Averaging")
        self.experiment.samples["avg"] = PKPDSample()
        tokens = ["AverageSample"]
        if doseName is not None:
            tokens.append("dose=%s" % doseName)
        self.experiment.samples["avg"].parseTokens(tokens,
                                                   self.experiment.variables,
                                                   self.experiment.doses,
                                                   self.experiment.groups)

        for mvarName in mvarNames:
            allt = {}
            for sampleName, sample in experiment.getSubGroup(
                    self.condition.get()).items():
                t, _ = sample.getXYValues(tvarName, mvarName)
                t = t[0]  # [[...]] -> [...]
                for i in range(len(t)):
                    ti = float(t[i])
                    if not ti in allt:
                        allt[ti] = True
            allt = sorted(allt.keys())

            observations = {}
            for sampleName, sample in experiment.getSubGroup(
                    self.condition.get()).items():
                for ti in allt:
                    observations[ti] = []

            for sampleName, sample in experiment.getSubGroup(
                    self.condition.get()).items():
                print("%s participates in the average" % sampleName)
                t, y = sample.getXYValues(tvarName, mvarName)
                t = t[0]  # [array]
                y = y[0]  # [array]
                tUnique, yUnique = uniqueFloatValues(t, y)
                B = InterpolatedUnivariateSpline(tUnique, yUnique, k=1)

                mint = np.min(t)
                maxt = np.max(t)

                for ti in allt:
                    if ti >= mint and ti <= maxt:
                        observations[ti].append(B(ti))

            for ti in observations:
                if len(observations[ti]) > 0:
                    if self.mode.get() == self.MODE_MEAN:
                        observations[ti] = np.mean(observations[ti])
                    else:
                        observations[ti] = np.median(observations[ti])
                else:
                    observations[ti] = np.nan

            t = []
            yavg = []
            for ti in sorted(observations):
                t.append(ti)
                yavg.append(observations[ti])

            if self.resampleT.get() > 0:
                t, yavg = uniqueFloatValues(t, yavg)
                B = InterpolatedUnivariateSpline(t, yavg, k=1)
                t = np.arange(np.min(t),
                              np.max(t) + self.resampleT.get(),
                              self.resampleT.get())
                yavg = B(t)
            self.experiment.samples["avg"].addMeasurementColumn(tvarName, t)
            self.experiment.samples["avg"].addMeasurementColumn(mvarName, yavg)
        print(" ")

        # Print and save
        self.writeExperiment(self.experiment, self._getPath("experiment.pkpd"))