experimental method to calculate parameter increments for use
        in the finite difference pertubation calculations

        Note
        ----
        user beware!
339782
def build_increments(self):
        
        self.enforce_bounds()
        self.add_transform_columns()
        par_groups = self.parameter_data.groupby("pargp").groups
        inctype = self.parameter_groups.groupby("inctyp").groups
        for itype,inc_groups in inctype.items():
            pnames = []
            for group in inc_groups:
                pnames.extend(par_groups[group])
                derinc = self.parameter_groups.loc[group,"derinc"]
                self.parameter_data.loc[par_groups[group],"derinc"] = derinc
            if itype == "absolute":
                self.parameter_data.loc[pnames,"increment"] = \
                    self.parameter_data.loc[pnames,"derinc"]
            elif itype == "relative":
                self.parameter_data.loc[pnames,"increment"] = \
                    self.parameter_data.loc[pnames,"derinc"] * \
                    self.parameter_data.loc[pnames,"parval1"]
            elif itype == "rel_to_max":
                mx = self.parameter_data.loc[pnames,"parval1"].max()
                self.parameter_data.loc[pnames,"increment"] = \
                    self.parameter_data.loc[pnames,"derinc"] * mx
            else:
                raise Exception('Pst.get_derivative_increments(): '+\
                                'unrecognized increment type:{0}'.format(itype))

        #account for fixed pars
        isfixed = self.parameter_data.partrans=="fixed"
        self.parameter_data.loc[isfixed,"increment"] = \
            self.parameter_data.loc[isfixed,"parval1"]
1344126
def nonparabolicity(self, **kwargs):
        '''
        
        '''
        Eg = self.Eg_Gamma(**kwargs)
        meff = self.meff_e_Gamma(**kwargs)
        T = kwargs.get('T', 300.)
        return k*T/Eg * (1 - meff)**2
823374
private void initParams() {
		nbActives = graph.getNodes().size();
		for (int i = 0; i < nbNodes; i++) {
			successors[i] = graph.getSuccOf(i);
			dfsNumberOfNode[i] = -1;
			father[i] = -1;
			A[i] = -1;
		}
	}
1273057
function () {
			// generate random solution to t-SNE
			this.Y = randn2d(this.N, this.dim); // the solution
			this.gains = randn2d(this.N, this.dim, 1.0); // step gains to accelerate progress in unchanging directions
			this.ystep = randn2d(this.N, this.dim, 0.0); // momentum accumulator
			this.iter = 0;
		}
3155
public void iterate() {
    // build covmat out of fitting matrix by multiplying diagonal elements with
    // 1+lambda
    for(int i = 0; i < numfit; i++) {
      System.arraycopy(alpha[i], 0, covmat[i], 0, numfit);
      covmat[i][i] *= (1.0 + lambda);
    }
    // Solve the equation system (Gauss-Jordan)
    LinearEquationSystem ls = new LinearEquationSystem(covmat, beta);
    ls.solveByTotalPivotSearch();
    // update covmat with the inverse
    covmat = ls.getCoefficents();
    // and deltaparams with the solution vector
    deltaparams = ls.getRHS();
    // deltaparams = beta;
    for(int i = 0, i2 = 0; i < numparams; i++) {
      if(dofit[i]) {
        paramstry[i] = params[i] + deltaparams[i2++];
      }
    }
    double newchisq = simulateParameters(paramstry);
    // have the results improved?
    if(newchisq < chisq) {
      // TODO: Do we need a larger limit than MIN_NORMAL?
      if(lambda * 0.1 > Double.MIN_NORMAL) {
        lambda *= 0.1;
      }
      chisq = newchisq;
      // keep modified covmat as new alpha matrix
      // and da as new beta
      for(int i = 0; i < numfit; i++) {
        System.arraycopy(covmat[i], 0, alpha[i], 0, numfit);
        beta[i] = deltaparams[i];
      }
      System.arraycopy(paramstry, 0, params, 0, numparams);
    }
    else {
      // TODO: Do we need a larger limit than MAX_VALUE?
      // Does it ever make sense to go as far up?
      // Anyway, this should prevent overflows.
      if(lambda * 10 < Double.MAX_VALUE) {
        lambda *= 10;
      }
    }
  }
333466
def _call(self, x):
        """"""
        # The algorithm takes finite differences in one dimension at a time
        # reusing the dx vector to improve efficiency.
        dfdx = self.domain.zero()
        dx = self.domain.zero()

        if self.method == 'backward':
            fx = self.functional(x)
            for i in range(self.domain.size):
                dx[i - 1] = 0  # reset step from last iteration
                dx[i] = self.step
                dfdx[i] = fx - self.functional(x - dx)
        elif self.method == 'forward':
            fx = self.functional(x)
            for i in range(self.domain.size):
                dx[i - 1] = 0  # reset step from last iteration
                dx[i] = self.step
                dfdx[i] = self.functional(x + dx) - fx
        elif self.method == 'central':
            for i in range(self.domain.size):
                dx[i - 1] = 0  # reset step from last iteration
                dx[i] = self.step / 2
                dfdx[i] = self.functional(x + dx) - self.functional(x - dx)
        else:
            raise RuntimeError('unknown method')

        dfdx /= self.step
        return dfdx
791755
def _paramf(ins):
    
    output = _float_oper(ins.quad[1])
    output.extend(_fpush())
    return output
1149227
function nelderMead(f, x0, parameters) {
        parameters = parameters || {};

        var maxIterations = parameters.maxIterations || x0.length * 200,
            nonZeroDelta = parameters.nonZeroDelta || 1.05,
            zeroDelta = parameters.zeroDelta || 0.001,
            minErrorDelta = parameters.minErrorDelta || 1e-6,
            minTolerance = parameters.minErrorDelta || 1e-5,
            rho = parameters.rho !== undefined ? parameters.rho : 1,
            chi = parameters.chi !== undefined ? parameters.chi : 2,
            psi = parameters.psi !== undefined ? parameters.psi : -0.5,
            sigma = parameters.sigma !== undefined ? parameters.sigma : 0.5,
            maxDiff;

        // initialize simplex.
        var N = x0.length,
            simplex = new Array(N + 1);
        simplex[0] = x0;
        simplex[0].fx = f(x0);
        simplex[0].id = 0;
        for (var i = 0; i < N; ++i) {
            var point = x0.slice();
            point[i] = point[i] ? point[i] * nonZeroDelta : zeroDelta;
            simplex[i + 1] = point;
            simplex[i + 1].fx = f(point);
            simplex[i + 1].id = i + 1;
        }

        function updateSimplex(value) {
            for (var i = 0; i < value.length; i++) {
                simplex[N][i] = value[i];
            }
            simplex[N].fx = value.fx;
        }

        var sortOrder = function sortOrder(a, b) {
            return a.fx - b.fx;
        };

        var centroid = x0.slice(),
            reflected = x0.slice(),
            contracted = x0.slice(),
            expanded = x0.slice();

        for (var iteration = 0; iteration < maxIterations; ++iteration) {
            simplex.sort(sortOrder);

            if (parameters.history) {
                // copy the simplex (since later iterations will mutate) and
                // sort it to have a consistent order between iterations
                var sortedSimplex = simplex.map(function (x) {
                    var state = x.slice();
                    state.fx = x.fx;
                    state.id = x.id;
                    return state;
                });
                sortedSimplex.sort(function (a, b) {
                    return a.id - b.id;
                });

                parameters.history.push({ x: simplex[0].slice(),
                    fx: simplex[0].fx,
                    simplex: sortedSimplex });
            }

            maxDiff = 0;
            for (i = 0; i < N; ++i) {
                maxDiff = Math.max(maxDiff, Math.abs(simplex[0][i] - simplex[1][i]));
            }

            if (Math.abs(simplex[0].fx - simplex[N].fx) < minErrorDelta && maxDiff < minTolerance) {
                break;
            }

            // compute the centroid of all but the worst point in the simplex
            for (i = 0; i < N; ++i) {
                centroid[i] = 0;
                for (var j = 0; j < N; ++j) {
                    centroid[i] += simplex[j][i];
                }
                centroid[i] /= N;
            }

            // reflect the worst point past the centroid  and compute loss at reflected
            // point
            var worst = simplex[N];
            weightedSum(reflected, 1 + rho, centroid, -rho, worst);
            reflected.fx = f(reflected);

            // if the reflected point is the best seen, then possibly expand
            if (reflected.fx < simplex[0].fx) {
                weightedSum(expanded, 1 + chi, centroid, -chi, worst);
                expanded.fx = f(expanded);
                if (expanded.fx < reflected.fx) {
                    updateSimplex(expanded);
                } else {
                    updateSimplex(reflected);
                }
            }

            // if the reflected point is worse than the second worst, we need to
            // contract
            else if (reflected.fx >= simplex[N - 1].fx) {
                    var shouldReduce = false;

                    if (reflected.fx > worst.fx) {
                        // do an inside contraction
                        weightedSum(contracted, 1 + psi, centroid, -psi, worst);
                        contracted.fx = f(contracted);
                        if (contracted.fx < worst.fx) {
                            updateSimplex(contracted);
                        } else {
                            shouldReduce = true;
                        }
                    } else {
                        // do an outside contraction
                        weightedSum(contracted, 1 - psi * rho, centroid, psi * rho, worst);
                        contracted.fx = f(contracted);
                        if (contracted.fx < reflected.fx) {
                            updateSimplex(contracted);
                        } else {
                            shouldReduce = true;
                        }
                    }

                    if (shouldReduce) {
                        // if we don't contract here, we're done
                        if (sigma >= 1) break;

                        // do a reduction
                        for (i = 1; i < simplex.length; ++i) {
                            weightedSum(simplex[i], 1 - sigma, simplex[0], sigma, simplex[i]);
                            simplex[i].fx = f(simplex[i]);
                        }
                    }
                } else {
                    updateSimplex(reflected);
                }
        }

        simplex.sort(sortOrder);
        return { fx: simplex[0].fx,
            x: simplex[0] };
    }
270525
def advance(self, dt_msec):
        
        # TODO: Make the time step adjustable, and choose an appropriate
        # numerical integration method to maintain stability.
        # TODO: The need to catch overflows indicates that the current method is
        # not stable for all possible network configurations and states.
        try:
            self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)
            self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)
            self.u += dt_msec * self.a * (self.b * self.v - self.u)
        except OverflowError:
            # Reset without producing a spike.
            self.v = self.c
            self.u = self.b * self.v

        self.fired = 0.0
        if self.v > 30.0:
            # Output spike and reset.
            self.fired = 1.0
            self.v = self.c
            self.u += self.d
1368221
private void increment( TldFernFeature f , boolean positive ) {
		if( positive ) {
			f.incrementP();
			if( f.numP > maxP )
				maxP = f.numP;
		} else {
			f.incrementN();
			if( f.numN > maxN )
				maxN = f.numN;
		}
	}
1319965
private void addBuiltIn( ) {
        input1.put("inv", Operation::inv);
        input1.put("pinv", Operation::pinv);
        input1.put("rref", Operation::rref);
        input1.put("eye", Operation::eye);
        input1.put("det", Operation::det);
        input1.put("normF", Operation::normF);
        input1.put("sum", Operation::sum_one);
        input1.put("trace", Operation::trace);
        input1.put("diag", Operation::diag);
        input1.put("min", Operation::min);
        input1.put("max", Operation::max);
        input1.put("abs", Operation::abs);
        input1.put("sin", Operation::sin);
        input1.put("cos", Operation::cos);
        input1.put("atan", Operation::atan);
        input1.put("exp", Operation::exp);
        input1.put("log", Operation::log);
        input1.put("sqrt", Operation::sqrt);
        input1.put("rng", Operation::rng);

        inputN.put("normP", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("Two inputs expected");
            return Operation.normP(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("max", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("One or two inputs expected");
            return Operation.max_two(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("min", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("One or two inputs expected");
            return Operation.min_two(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("sum", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("One or two inputs expected");
            return Operation.sum_two(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("zeros", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("Two inputs expected");
            return Operation.zeros(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("ones", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("Two inputs expected");
            return Operation.ones(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("rand", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("Two inputs expected");
            return Operation.rand(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("randn", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("Two inputs expected");
            return Operation.randn(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("kron", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("Two inputs expected");
            return Operation.kron(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("dot", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("Two inputs expected");
            return Operation.dot(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("pow", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("Two inputs expected");
            return Operation.pow(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("atan2", (inputs, manager) -> {
            if (inputs.size() != 2) throw new RuntimeException("Two inputs expected");
            return Operation.atan2(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("solve", (inputs, manager) -> {
            if( inputs.size() != 2 ) throw new RuntimeException("Two inputs expected");
            return Operation.solve(inputs.get(0), inputs.get(1), manager);
        });

        inputN.put("extract", Operation::extract);
        inputN.put("extractScalar", (inputs, manager) -> {
            if( inputs.size() != 2 && inputs.size() != 3 ) throw new RuntimeException("Two or three inputs expected");
            return Operation.extractScalar(inputs, manager);
        });
    }
848685
function ( inPtA, inPtB ) {
		var deltaY = inPtA.y - inPtB.y;
		if ( deltaY < PNLTRI.Math.EPSILON_N ) {
			return -1;
		} else if ( deltaY > PNLTRI.Math.EPSILON_P ) {
			return 1;
		} else {
			var deltaX = inPtA.x - inPtB.x;
			if ( deltaX < PNLTRI.Math.EPSILON_N ) {
				return -1;
			} else if ( deltaX > PNLTRI.Math.EPSILON_P ) {
				return  1;
			} else {
				return  0;
			}
		}
	}
863248
function computeSlotSegPressures(seg) {
	var forwardSegs = seg.forwardSegs;
	var forwardPressure = 0;
	var i, forwardSeg;

	if (seg.forwardPressure === undefined) { // not already computed

		for (i=0; i<forwardSegs.length; i++) {
			forwardSeg = forwardSegs[i];

			// figure out the child's maximum forward path
			computeSlotSegPressures(forwardSeg);

			// either use the existing maximum, or use the child's forward pressure
			// plus one (for the forwardSeg itself)
			forwardPressure = Math.max(
				forwardPressure,
				1 + forwardSeg.forwardPressure
			);
		}

		seg.forwardPressure = forwardPressure;
	}
}
35767
static double computeDynamicTimeWarpingDistance(
    	DoubleTuple u, DoubleTuple v)
    {
        int m = u.getSize();
        int n = v.getSize();
        double matrix[][] = threadLocalMatrix.get();
        if (matrix.length < m || matrix[0].length < n)
        {
        	matrix = new double[m][n];
        	threadLocalMatrix.set(matrix);
        }
        double u0 = u.get(0);
        double v0 = v.get(0);
        matrix[0][0] = Math.abs(u0-v0);
        for (int j=1; j<n; j++)
        {
            matrix[0][j] = Math.abs(u0-v.get(j)) + matrix[0][j-1];
        }
        for (int i=1; i<m; i++)
        {
           matrix[i][0] = Math.abs(u.get(i)-v0) + matrix[i-1][0];
        }
        for (int i = 1; i < m; i++)
        {
            double ui = u.get(i);
            for (int j = 1; j < n; j++)
            {
                double vj = v.get(j);
                double min = matrix[i - 1][j - 1];
                min = min(min, matrix[i][j - 1]);
                min = min(min, matrix[i - 1][j]);
                double d = ui - vj;
                matrix[i][j] = min + (d < 0 ? -d : d);
            }
        }
        return matrix[m-1][n-1];
    }
1187092
def calculo(self):
        """"""
        T = self.kwargs["T"]
        rho = self.kwargs["rho"]
        P = self.kwargs["P"]
        s = self.kwargs["s"]
        h = self.kwargs["h"]
        u = self.kwargs["u"]
        x = self.kwargs["x"]

        # Initial values
        T0 = self.kwargs["T0"]
        rho0 = self.kwargs["rho0"]

        if T0 or rho0:
            To = T0
            rhoo = rho0
        elif self.name == "air":
            To = 300
            rhoo = 1e-3
        else:
            try:
                st0 = IAPWS97(**self.kwargs)
            except NotImplementedError:
                To = 300
                rhoo = 900
            else:
                if st0.status:
                    To = st0.T
                    rhoo = st0.rho
                else:
                    To = 300
                    rhoo = 900

        self.R = self._constants["R"]/self._constants.get("M", self.M)
        rhoc = self._constants.get("rhoref", self.rhoc)
        Tc = self._constants.get("Tref", self.Tc)

        propiedades = None

        if self._mode not in ("Tx", "Px"):
            # Method with iteration necessary to get x
            if self._mode == "TP":
                try:
                    if self.name == "air":
                        raise ValueError
                    st0 = IAPWS97(**self.kwargs)
                    rhoo = st0.rho
                except NotImplementedError:
                    if rho0:
                        rhoo = rho0
                    elif T < self.Tc and P < self.Pc and \
                            self._Vapor_Pressure(T) < P:
                        rhoo = self._Liquid_Density(T)
                    elif T < self.Tc and P < self.Pc:
                        rhoo = self._Vapor_Density(T)
                    else:
                        rhoo = self.rhoc*3
                except ValueError:
                    rhoo = 1e-3

                def f(rho):
                    delta = rho/rhoc
                    tau = Tc/T

                    fird = _phird(tau, delta, self._constants)
                    Po = (1+delta*fird)*self.R*T*rho
                    return Po-P*1000

                rho = fsolve(f, rhoo)[0]

                # Calculate quality
                if T > self.Tc:
                    x = 1
                else:
                    Ps = self._Vapor_Pressure(T)
                    if Ps*0.95 < P < Ps*1.05:
                        rhol, rhov, Ps = self._saturation(T)
                        Ps *= 1e-3

                    if Ps > P:
                        x = 1
                    else:
                        x = 0

            elif self._mode == "Th":
                tau = Tc/T
                ideal = self._phi0(tau, 1)
                fiot = ideal["fiot"]

                def f(rho):
                    delta = rho/rhoc
                    fird = _phird(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    ho = self.R*T*(1+tau*(fiot+firt)+delta*fird)
                    return ho-h

                if T >= self.Tc:
                    rhoo = self.rhoc
                    rho = fsolve(f, rhoo)[0]
                else:
                    x0 = self.kwargs["x0"]
                    rhov = self._Vapor_Density(T)
                    rhol = self._Liquid_Density(T)
                    deltaL = rhol/rhoc
                    deltaG = rhov/rhoc

                    firdL = _phird(tau, deltaL, self._constants)
                    firtL = _phirt(tau, deltaL, self._constants)
                    firdG = _phird(tau, deltaG, self._constants)
                    firtG = _phirt(tau, deltaG, self._constants)
                    hl = self.R*T*(1+tau*(fiot+firtL)+deltaL*firdL)
                    hv = self.R*T*(1+tau*(fiot+firtG)+deltaG*firdG)
                    if x0 not in (0, 1) and hl <= h <= hv:
                        rhol, rhov, Ps = self._saturation(T)
                        vapor = self._Helmholtz(rhov, T)
                        liquido = self._Helmholtz(rhol, T)
                        hv = vapor["h"]
                        hl = liquido["h"]
                        x = (h-hl)/(hv-hl)
                        rho = 1/(x/rhov+(1-x)/rhol)
                        P = Ps/1000
                    else:
                        if h > hv:
                            rhoo = rhov
                        else:
                            rhoo = rhol
                        rho = fsolve(f, rhoo)[0]

            elif self._mode == "Ts":
                tau = Tc/T

                def f(rho):
                    if rho < 0:
                        rho = 1e-20
                    delta = rho/rhoc

                    ideal = self._phi0(tau, delta)
                    fio = ideal["fio"]
                    fiot = ideal["fiot"]
                    fir = _phir(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    so = self.R*(tau*(fiot+firt)-fio-fir)
                    return so-s

                if T >= self.Tc:
                    rhoo = self.rhoc
                    rho = fsolve(f, rhoo)[0]
                else:
                    rhov = self._Vapor_Density(T)
                    rhol = self._Liquid_Density(T)
                    deltaL = rhol/rhoc
                    deltaG = rhov/rhoc

                    idealL = self._phi0(tau, deltaL)
                    idealG = self._phi0(tau, deltaG)
                    fioL = idealL["fio"]
                    fioG = idealG["fio"]
                    fiot = idealL["fiot"]
                    firL = _phir(tau, deltaL, self._constants)
                    firtL = _phirt(tau, deltaL, self._constants)
                    sl = self.R*(tau*(fiot+firtL)-fioL-firL)
                    firG = _phir(tau, deltaG, self._constants)
                    firtG = _phirt(tau, deltaG, self._constants)
                    sv = self.R*(tau*(fiot+firtG)-fioG-firG)

                    if sl <= s <= sv:
                        rhol, rhov, Ps = self._saturation(T)
                        vapor = self._Helmholtz(rhov, T)
                        liquido = self._Helmholtz(rhol, T)
                        sv = vapor["s"]
                        sl = liquido["s"]
                        x = (s-sl)/(sv-sl)
                        rho = 1/(x/rhov+(1-x)/rhol)
                        P = Ps/1000
                    else:
                        if s > sv:
                            rhoo = rhov
                        else:
                            rhoo = rhol
                        rho = fsolve(f, rhoo)[0]

            elif self._mode == "Tu":
                tau = Tc/T
                ideal = self._phi0(tau, 1)
                fiot = ideal["fiot"]

                def f(rho):
                    delta = rho/rhoc

                    fird = _phird(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    Po = (1+delta*fird)*self.R*T*rho
                    ho = self.R*T*(1+tau*(fiot+firt)+delta*fird)

                    return ho-Po/rho-u

                if T >= self.Tc:
                    rhoo = self.rhoc
                    rho = fsolve(f, rhoo)[0]
                else:
                    rhov = self._Vapor_Density(T)
                    rhol = self._Liquid_Density(T)
                    deltaL = rhol/rhoc
                    deltaG = rhov/rhoc

                    firdL = _phird(tau, deltaL, self._constants)
                    firtL = _phirt(tau, deltaL, self._constants)
                    firdG = _phird(tau, deltaG, self._constants)
                    firtG = _phirt(tau, deltaG, self._constants)
                    PoL = (1+deltaL*firdL)*self.R*T*rhol
                    PoG = (1+deltaG*firdG)*self.R*T*rhov
                    hoL = self.R*T*(1+tau*(fiot+firtL)+deltaL*firdL)
                    hoG = self.R*T*(1+tau*(fiot+firtG)+deltaG*firdG)

                    uv = hoG-PoG/rhov
                    ul = hoL-PoL/rhol
                    if ul <= u <= uv:
                        rhol, rhov, Ps = self._saturation(T)
                        vapor = self._Helmholtz(rhov, T)
                        liquido = self._Helmholtz(rhol, T)
                        uv = vapor["h"]-vapor["P"]/rhov
                        ul = liquido["h"]-liquido["P"]/rhol
                        x = (u-ul)/(uv-ul)
                        rho = 1/(x/rhov-(1-x)/rhol)
                        P = Ps/1000
                    else:
                        if u > uv:
                            rhoo = rhov
                        else:
                            rhoo = rhol
                        rho = fsolve(f, rhoo)[0]

            elif self._mode == "Prho":
                delta = rho/rhoc

                def f(T):
                    tau = Tc/T

                    fird = _phird(tau, delta, self._constants)
                    Po = (1+delta*fird)*self.R*T*rho
                    return Po-P*1000

                T = fsolve(f, To)[0]
                rhol = self._Liquid_Density(T)
                rhov = self._Vapor_Density(T)
                if T == To or rhov <= rho <= rhol:

                    def f(parr):
                        T, rhol, rhog = parr
                        tau = Tc/T
                        deltaL = rhol/self.rhoc
                        deltaG = rhog/self.rhoc

                        firL = _phir(tau, deltaL, self._constants)
                        firdL = _phird(tau, deltaL, self._constants)
                        firG = _phir(tau, deltaG, self._constants)
                        firdG = _phird(tau, deltaG, self._constants)

                        Jl = rhol*(1+deltaL*firdL)
                        Jv = rhog*(1+deltaG*firdG)
                        K = firL-firG
                        Ps = self.R*T*rhol*rhog/(rhol-rhog)*(K+log(rhol/rhog))
                        return (Jl-Jv,
                                Jl*(1/rhog-1/rhol)-log(rhol/rhog)-K,
                                Ps - P*1000)

                    for to in [To, 300, 400, 500, 600]:
                        rhoLo = self._Liquid_Density(to)
                        rhoGo = self._Vapor_Density(to)
                        sol = fsolve(f, [to, rhoLo, rhoGo], full_output=True)
                        T, rhoL, rhoG = sol[0]
                        x = (1./rho-1/rhoL)/(1/rhoG-1/rhoL)
                        if sol[2] == 1 and 0 <= x <= 1 and \
                                sum(abs(sol[1]["fvec"])) < 1e-5:
                            break

                    if sum(abs(sol[1]["fvec"])) > 1e-5:
                        raise(RuntimeError(sol[3]))

                    liquido = self._Helmholtz(rhoL, T)
                    vapor = self._Helmholtz(rhoG, T)
                    P = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(
                        liquido["fir"]-vapor["fir"]+log(rhoL/rhoG))/1000

            elif self._mode == "Ph":
                def funcion(parr):
                    rho, T = parr
                    delta = rho/rhoc
                    tau = Tc/T

                    ideal = self._phi0(tau, delta)
                    fiot = ideal["fiot"]
                    fird = _phird(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    Po = (1+delta*fird)*self.R*T*rho
                    ho = self.R*T*(1+tau*(fiot+firt)+delta*fird)
                    return Po-P*1000, ho-h

                rho, T = fsolve(funcion, [rhoo, To])
                rhol = self._Liquid_Density(T)
                rhov = self._Vapor_Density(T)
                if rho == rhoo or rhov <= rho <= rhol:

                    def f(parr):
                        T, rhol, rhog, x = parr
                        tau = Tc/T
                        deltaL = rhol/self.rhoc
                        deltaG = rhog/self.rhoc

                        ideal = self._phi0(tau, deltaL)
                        fiot = ideal["fiot"]

                        firL = _phir(tau, deltaL, self._constants)
                        firdL = _phird(tau, deltaL, self._constants)
                        firtL = _phirt(tau, deltaL, self._constants)
                        hoL = self.R*T*(1+tau*(fiot+firtL)+deltaL*firdL)
                        firG = _phir(tau, deltaG, self._constants)
                        firdG = _phird(tau, deltaG, self._constants)
                        firtG = _phirt(tau, deltaG, self._constants)
                        hoG = self.R*T*(1+tau*(fiot+firtG)+deltaG*firdG)

                        Jl = rhol*(1+deltaL*firdL)
                        Jv = rhog*(1+deltaG*firdG)
                        K = firL-firG
                        Ps = self.R*T*rhol*rhog/(rhol-rhog)*(K+log(rhol/rhog))

                        return (Jl-Jv,
                                Jl*(1/rhog-1/rhol)-log(rhol/rhog)-K,
                                hoL*(1-x)+hoG*x - h,
                                Ps - P*1000)

                    for to in [To, 300, 400, 500, 600]:
                        rLo = self._Liquid_Density(to)
                        rGo = self._Vapor_Density(to)
                        sol = fsolve(f, [to, rLo, rGo, 0.5], full_output=True)
                        T, rhoL, rhoG, x = sol[0]
                        if sol[2] == 1 and 0 <= x <= 1 and \
                                sum(abs(sol[1]["fvec"])) < 1e-5:
                            break

                    if sum(abs(sol[1]["fvec"])) > 1e-5:
                        raise(RuntimeError(sol[3]))

                    liquido = self._Helmholtz(rhoL, T)
                    vapor = self._Helmholtz(rhoG, T)
                    P = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(
                        liquido["fir"]-vapor["fir"]+log(rhoL/rhoG))/1000

            elif self._mode == "Ps":
                try:
                    x0 = st0.x
                except NameError:
                    x0 = None

                if x0 is None or x0 == 0 or x0 == 1:
                    def f(parr):
                        rho, T = parr
                        delta = rho/rhoc
                        tau = Tc/T

                        ideal = self._phi0(tau, delta)
                        fio = ideal["fio"]
                        fiot = ideal["fiot"]
                        fird = _phird(tau, delta, self._constants)
                        fir = _phir(tau, delta, self._constants)
                        firt = _phirt(tau, delta, self._constants)
                        Po = (1+delta*fird)*self.R*T*rho
                        so = self.R*(tau*(fiot+firt)-fio-fir)
                        return Po-P*1000, so-s

                    rho, T = fsolve(f, [rhoo, To])

                else:
                    def funcion(parr):
                        rho, T = parr
                        rhol, rhov, Ps = self._saturation(T)
                        vapor = self._Helmholtz(rhov, T)
                        liquido = self._Helmholtz(rhol, T)
                        x = (1./rho-1/rhol)/(1/rhov-1/rhol)
                        return Ps-P*1000, vapor["s"]*x+liquido["s"]*(1-x)-s
                    rho, T = fsolve(funcion, [2., 500.])
                    rhol, rhov, Ps = self._saturation(T)
                    vapor = self._Helmholtz(rhov, T)
                    liquido = self._Helmholtz(rhol, T)
                    sv = vapor["s"]
                    sl = liquido["s"]
                    x = (s-sl)/(sv-sl)

            elif self._mode == "Pu":
                def f(parr):
                    rho, T = parr
                    delta = rho/rhoc
                    tau = Tc/T

                    ideal = self._phi0(tau, delta)
                    fiot = ideal["fiot"]
                    fird = _phird(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    Po = (1+delta*fird)*self.R*T*rho
                    ho = self.R*T*(1+tau*(fiot+firt)+delta*fird)
                    return ho-Po/rho-u, Po-P*1000

                sol = fsolve(f, [rhoo, To], full_output=True)
                rho, T = sol[0]
                rhol = self._Liquid_Density(T)
                rhov = self._Vapor_Density(T)
                if rho == rhoo or sol[2] != 1:

                    def f(parr):
                        T, rhol, rhog, x = parr
                        tau = Tc/T
                        deltaL = rhol/self.rhoc
                        deltaG = rhog/self.rhoc

                        ideal = self._phi0(tau, deltaL)
                        fiot = ideal["fiot"]

                        firL = _phir(tau, deltaL, self._constants)
                        firdL = _phird(tau, deltaL, self._constants)
                        firtL = _phirt(tau, deltaL, self._constants)
                        hoL = self.R*T*(1+tau*(fiot+firtL)+deltaL*firdL)
                        firG = _phir(tau, deltaG, self._constants)
                        firdG = _phird(tau, deltaG, self._constants)
                        firtG = _phirt(tau, deltaG, self._constants)
                        hoG = self.R*T*(1+tau*(fiot+firtG)+deltaG*firdG)

                        Jl = rhol*(1+deltaL*firdL)
                        Jv = rhog*(1+deltaG*firdG)
                        K = firL-firG
                        Ps = self.R*T*rhol*rhog/(rhol-rhog)*(K+log(rhol/rhog))
                        vu = hoG-Ps/rhog
                        lu = hoL-Ps/rhol
                        return (Jl-Jv,
                                Jl*(1/rhog-1/rhol)-log(rhol/rhog)-K,
                                lu*(1-x)+vu*x - u,
                                Ps - P*1000)

                    for to in [To, 300, 400, 500, 600]:
                        rLo = self._Liquid_Density(to)
                        rGo = self._Vapor_Density(to)
                        sol = fsolve(f, [to, rLo, rGo, 0.5], full_output=True)
                        T, rhoL, rhoG, x = sol[0]
                        if sol[2] == 1 and 0 <= x <= 1 and \
                                sum(abs(sol[1]["fvec"])) < 1e-5:
                            break

                    if sum(abs(sol[1]["fvec"])) > 1e-5:
                        raise(RuntimeError(sol[3]))

                    liquido = self._Helmholtz(rhoL, T)
                    vapor = self._Helmholtz(rhoG, T)
                    P = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(
                        liquido["fir"]-vapor["fir"]+log(rhoL/rhoG))/1000

            elif self._mode == "rhoh":
                delta = rho/rhoc

                def f(T):
                    tau = Tc/T

                    ideal = self._phi0(tau, delta)
                    fiot = ideal["fiot"]
                    fird = _phird(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    ho = self.R*T*(1+tau*(fiot+firt)+delta*fird)
                    return ho-h

                T = fsolve(f, To)[0]
                rhol = self._Liquid_Density(T)
                rhov = self._Vapor_Density(T)
                if T == To or rhov <= rho <= rhol:
                    def f(parr):
                        T, rhol, rhog = parr
                        tau = Tc/T
                        deltaL = rhol/self.rhoc
                        deltaG = rhog/self.rhoc

                        ideal = self._phi0(tau, deltaL)
                        fiot = ideal["fiot"]
                        firL = _phir(tau, deltaL, self._constants)
                        firdL = _phird(tau, deltaL, self._constants)
                        firtL = _phirt(tau, deltaL, self._constants)
                        hoL = self.R*T*(1+tau*(fiot+firtL)+deltaL*firdL)
                        firG = _phir(tau, deltaG, self._constants)
                        firdG = _phird(tau, deltaG, self._constants)
                        firtG = _phirt(tau, deltaG, self._constants)
                        hoG = self.R*T*(1+tau*(fiot+firtG)+deltaG*firdG)

                        Jl = rhol*(1+deltaL*firdL)
                        Jv = rhog*(1+deltaG*firdG)
                        K = firL-firG
                        x = (1./rho-1/rhol)/(1/rhog-1/rhol)
                        return (Jl-Jv,
                                Jl*(1/rhog-1/rhol)-log(rhol/rhog)-K,
                                hoL*(1-x)+hoG*x - h)

                    for to in [To, 300, 400, 500, 600]:
                        rhoLo = self._Liquid_Density(to)
                        rhoGo = self._Vapor_Density(to)
                        sol = fsolve(f, [to, rhoLo, rhoGo], full_output=True)
                        T, rhoL, rhoG = sol[0]
                        x = (1./rho-1/rhoL)/(1/rhoG-1/rhoL)
                        if sol[2] == 1 and 0 <= x <= 1 and \
                                sum(abs(sol[1]["fvec"])) < 1e-5:
                            break

                    if sum(abs(sol[1]["fvec"])) > 1e-5:
                        raise(RuntimeError(sol[3]))

                    liquido = self._Helmholtz(rhoL, T)
                    vapor = self._Helmholtz(rhoG, T)
                    P = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(
                        liquido["fir"]-vapor["fir"]+log(rhoL/rhoG))/1000

            elif self._mode == "rhos":
                delta = rho/rhoc

                def f(T):
                    tau = Tc/T
                    ideal = self._phi0(tau, delta)
                    fio = ideal["fio"]
                    fiot = ideal["fiot"]
                    fir = _phir(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    so = self.R*(tau*(fiot+firt)-fio-fir)
                    return so-s

                T = fsolve(f, To)[0]
                rhol = self._Liquid_Density(T)
                rhov = self._Vapor_Density(T)
                if T == To or rhov <= rho <= rhol:

                    def f(parr):
                        T, rhol, rhog = parr
                        tau = Tc/T
                        deltaL = rhol/self.rhoc
                        deltaG = rhog/self.rhoc

                        idealL = self._phi0(tau, deltaL)
                        fioL = idealL["fio"]
                        fiot = idealL["fiot"]
                        idealG = self._phi0(tau, deltaG)
                        fioG = idealG["fio"]

                        firL = _phir(tau, deltaL, self._constants)
                        firdL = _phird(tau, deltaL, self._constants)
                        firtL = _phirt(tau, deltaL, self._constants)
                        soL = self.R*(tau*(fiot+firtL)-fioL-firL)
                        firG = _phir(tau, deltaG, self._constants)
                        firdG = _phird(tau, deltaG, self._constants)
                        firtG = _phirt(tau, deltaG, self._constants)
                        soG = self.R*(tau*(fiot+firtG)-fioG-firG)

                        Jl = rhol*(1+deltaL*firdL)
                        Jv = rhog*(1+deltaG*firdG)
                        K = firL-firG
                        x = (1./rho-1/rhol)/(1/rhog-1/rhol)
                        return (Jl-Jv,
                                Jl*(1/rhog-1/rhol)-log(rhol/rhog)-K,
                                soL*(1-x)+soG*x - s)

                    for to in [To, 300, 400, 500, 600]:
                        rhoLo = self._Liquid_Density(to)
                        rhoGo = self._Vapor_Density(to)
                        sol = fsolve(f, [to, rhoLo, rhoGo], full_output=True)
                        T, rhoL, rhoG = sol[0]
                        x = (1./rho-1/rhoL)/(1/rhoG-1/rhoL)
                        if sol[2] == 1 and 0 <= x <= 1 and \
                                sum(abs(sol[1]["fvec"])) < 1e-5:
                            break

                    if sum(abs(sol[1]["fvec"])) > 1e-5:
                        raise(RuntimeError(sol[3]))

                    liquido = self._Helmholtz(rhoL, T)
                    vapor = self._Helmholtz(rhoG, T)
                    P = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(
                        liquido["fir"]-vapor["fir"]+log(rhoL/rhoG))/1000

            elif self._mode == "rhou":
                delta = rho/rhoc

                def f(T):
                    tau = Tc/T

                    ideal = self._phi0(tau, delta)
                    fiot = ideal["fiot"]
                    fird = _phird(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    Po = (1+delta*fird)*self.R*T*rho
                    ho = self.R*T*(1+tau*(fiot+firt)+delta*fird)
                    return ho-Po/rho-u

                T = fsolve(f, To)[0]
                rhol = self._Liquid_Density(T)
                rhov = self._Vapor_Density(T)
                if T == To or rhov <= rho <= rhol:
                    def f(parr):
                        T, rhol, rhog = parr
                        tau = Tc/T
                        deltaL = rhol/self.rhoc
                        deltaG = rhog/self.rhoc

                        ideal = self._phi0(tau, deltaL)
                        fiot = ideal["fiot"]
                        firL = _phir(tau, deltaL, self._constants)
                        firdL = _phird(tau, deltaL, self._constants)
                        firtL = _phirt(tau, deltaL, self._constants)
                        hoL = self.R*T*(1+tau*(fiot+firtL)+deltaL*firdL)
                        firG = _phir(tau, deltaG, self._constants)
                        firdG = _phird(tau, deltaG, self._constants)
                        firtG = _phirt(tau, deltaG, self._constants)
                        hoG = self.R*T*(1+tau*(fiot+firtG)+deltaG*firdG)

                        Jl = rhol*(1+deltaL*firdL)
                        Jv = rhog*(1+deltaG*firdG)
                        K = firL-firG
                        x = (1./rho-1/rhol)/(1/rhog-1/rhol)
                        Ps = self.R*T*rhol*rhog/(rhol-rhog)*(K+log(rhol/rhog))
                        vu = hoG-Ps/rhog
                        lu = hoL-Ps/rhol
                        return (Jl-Jv,
                                Jl*(1/rhog-1/rhol)-log(rhol/rhog)-K,
                                lu*(1-x)+vu*x - u)

                    for to in [To, 300, 400, 500, 600]:
                        rhoLo = self._Liquid_Density(to)
                        rhoGo = self._Vapor_Density(to)
                        sol = fsolve(f, [to, rhoLo, rhoGo], full_output=True)
                        T, rhoL, rhoG = sol[0]
                        x = (1./rho-1/rhoL)/(1/rhoG-1/rhoL)
                        if sol[2] == 1 and 0 <= x <= 1 and \
                                sum(abs(sol[1]["fvec"])) < 1e-5:
                            break

                    if sum(abs(sol[1]["fvec"])) > 1e-5:
                        raise(RuntimeError(sol[3]))

                    liquido = self._Helmholtz(rhoL, T)
                    vapor = self._Helmholtz(rhoG, T)
                    P = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(
                        liquido["fir"]-vapor["fir"]+log(rhoL/rhoG))/1000

            elif self._mode == "hs":
                def f(parr):
                    rho, T = parr
                    delta = rho/rhoc
                    tau = Tc/T

                    ideal = self._phi0(tau, delta)
                    fio = ideal["fio"]
                    fiot = ideal["fiot"]
                    fird = _phird(tau, delta, self._constants)
                    fir = _phir(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    ho = self.R*T*(1+tau*(fiot+firt)+delta*fird)
                    so = self.R*(tau*(fiot+firt)-fio-fir)
                    return ho-h, so-s

                rho, T = fsolve(f, [rhoo, To])
                rhol = self._Liquid_Density(T)
                rhov = self._Vapor_Density(T)
                if rhov <= rho <= rhol:

                    def f(parr):
                        T, rhol, rhog, x = parr
                        tau = Tc/T
                        deltaL = rhol/self.rhoc
                        deltaG = rhog/self.rhoc

                        idealL = self._phi0(tau, deltaL)
                        fiot = idealL["fiot"]
                        fioL = idealL["fio"]
                        idealG = self._phi0(tau, deltaG)
                        fioG = idealG["fio"]

                        firL = _phir(tau, deltaL, self._constants)
                        firdL = _phird(tau, deltaL, self._constants)
                        firtL = _phirt(tau, deltaL, self._constants)
                        hoL = self.R*T*(1+tau*(fiot+firtL)+deltaL*firdL)
                        soL = self.R*(tau*(fiot+firtL)-fioL-firL)
                        firG = _phir(tau, deltaG, self._constants)
                        firdG = _phird(tau, deltaG, self._constants)
                        firtG = _phirt(tau, deltaG, self._constants)
                        hoG = self.R*T*(1+tau*(fiot+firtG)+deltaG*firdG)
                        soG = self.R*(tau*(fiot+firtG)-fioG-firG)

                        Jl = rhol*(1+deltaL*firdL)
                        Jv = rhog*(1+deltaG*firdG)
                        K = firL-firG
                        return (Jl-Jv,
                                Jl*(1/rhog-1/rhol)-log(rhol/rhog)-K,
                                hoL*(1-x)+hoG*x - h,
                                soL*(1-x)+soG*x - s)

                    for to in [To, 300, 400, 500, 600]:
                        rLo = self._Liquid_Density(to)
                        rGo = self._Vapor_Density(to)
                        sol = fsolve(f, [to, rLo, rGo, 0.5], full_output=True)
                        T, rhoL, rhoG, x = sol[0]
                        if sol[2] == 1 and 0 <= x <= 1 and \
                                sum(abs(sol[1]["fvec"])) < 1e-5:
                            break

                    if sum(abs(sol[1]["fvec"])) > 1e-5:
                        raise(RuntimeError(sol[3]))

                    liquido = self._Helmholtz(rhoL, T)
                    vapor = self._Helmholtz(rhoG, T)
                    P = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(
                        liquido["fir"]-vapor["fir"]+log(rhoL/rhoG))/1000

            elif self._mode == "hu":
                def f(parr):
                    rho, T = parr
                    delta = rho/rhoc
                    tau = Tc/T

                    ideal = self._phi0(tau, delta)
                    fiot = ideal["fiot"]
                    fird = _phird(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    Po = (1+delta*fird)*self.R*T*rho
                    ho = self.R*T*(1+tau*(fiot+firt)+delta*fird)

                    return ho-Po/rho-u, ho-h

                sol = fsolve(f, [rhoo, To], full_output=True)
                rho, T = sol[0]
                rhol = self._Liquid_Density(T)
                rhov = self._Vapor_Density(T)
                if sol[2] != 1 or rhov <= rho <= rhol:

                    def f(parr):
                        T, rhol, rhog, x = parr
                        tau = Tc/T
                        deltaL = rhol/self.rhoc
                        deltaG = rhog/self.rhoc

                        ideal = self._phi0(tau, deltaL)
                        fiot = ideal["fiot"]

                        firL = _phir(tau, deltaL, self._constants)
                        firdL = _phird(tau, deltaL, self._constants)
                        firtL = _phirt(tau, deltaL, self._constants)
                        hoL = self.R*T*(1+tau*(fiot+firtL)+deltaL*firdL)
                        firG = _phir(tau, deltaG, self._constants)
                        firdG = _phird(tau, deltaG, self._constants)
                        firtG = _phirt(tau, deltaG, self._constants)
                        hoG = self.R*T*(1+tau*(fiot+firtG)+deltaG*firdG)

                        Jl = rhol*(1+deltaL*firdL)
                        Jv = rhog*(1+deltaG*firdG)
                        K = firL-firG

                        Ps = self.R*T*rhol*rhog/(rhol-rhog)*(K+log(rhol/rhog))
                        vu = hoG-Ps/rhog
                        lu = hoL-Ps/rhol

                        return (Jl-Jv,
                                Jl*(1/rhog-1/rhol)-log(rhol/rhog)-K,
                                hoL*(1-x)+hoG*x - h,
                                lu*(1-x)+vu*x - u)

                    for to in [To, 300, 400, 500, 600]:
                        rLo = self._Liquid_Density(to)
                        rGo = self._Vapor_Density(to)
                        sol = fsolve(f, [to, rLo, rGo, 0.5], full_output=True)
                        T, rhoL, rhoG, x = sol[0]
                        if sol[2] == 1 and 0 <= x <= 1 and \
                                sum(abs(sol[1]["fvec"])) < 1e-5:
                            break

                    if sum(abs(sol[1]["fvec"])) > 1e-5:
                        raise(RuntimeError(sol[3]))

                    liquido = self._Helmholtz(rhoL, T)
                    vapor = self._Helmholtz(rhoG, T)
                    P = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(
                        liquido["fir"]-vapor["fir"]+log(rhoL/rhoG))/1000

            elif self._mode == "su":
                def f(parr):
                    rho, T = parr
                    delta = rho/rhoc
                    tau = Tc/T

                    ideal = self._phi0(tau, delta)
                    fio = ideal["fio"]
                    fiot = ideal["fiot"]
                    fird = _phird(tau, delta, self._constants)
                    fir = _phir(tau, delta, self._constants)
                    firt = _phirt(tau, delta, self._constants)
                    ho = self.R*T*(1+tau*(fiot+firt)+delta*fird)
                    so = self.R*(tau*(fiot+firt)-fio-fir)
                    Po = (1+delta*fird)*self.R*T*rho
                    return ho-Po/rho-u, so-s

                sol = fsolve(f, [rhoo, To], full_output=True)
                rho, T = sol[0]
                rhol = self._Liquid_Density(T)
                rhov = self._Vapor_Density(T)
                if sol[2] != 1 or rhov <= rho <= rhol:

                    def f(parr):
                        T, rhol, rhog, x = parr
                        tau = Tc/T
                        deltaL = rhol/self.rhoc
                        deltaG = rhog/self.rhoc

                        idealL = self._phi0(tau, deltaL)
                        fiot = idealL["fiot"]
                        fioL = idealL["fio"]
                        idealG = self._phi0(tau, deltaG)
                        fioG = idealG["fio"]

                        firL = _phir(tau, deltaL, self._constants)
                        firdL = _phird(tau, deltaL, self._constants)
                        firtL = _phirt(tau, deltaL, self._constants)
                        hoL = self.R*T*(1+tau*(fiot+firtL)+deltaL*firdL)
                        soL = self.R*(tau*(fiot+firtL)-fioL-firL)
                        firG = _phir(tau, deltaG, self._constants)
                        firdG = _phird(tau, deltaG, self._constants)
                        firtG = _phirt(tau, deltaG, self._constants)
                        hoG = self.R*T*(1+tau*(fiot+firtG)+deltaG*firdG)
                        soG = self.R*(tau*(fiot+firtG)-fioG-firG)

                        Jl = rhol*(1+deltaL*firdL)
                        Jv = rhog*(1+deltaG*firdG)
                        K = firL-firG

                        Ps = self.R*T*rhol*rhog/(rhol-rhog)*(K+log(rhol/rhog))
                        vu = hoG-Ps/rhog
                        lu = hoL-Ps/rhol

                        return (Jl-Jv,
                                Jl*(1/rhog-1/rhol)-log(rhol/rhog)-K,
                                soL*(1-x)+soG*x - s,
                                lu*(1-x)+vu*x - u)

                    for to in [To, 300, 400, 500, 600]:
                        rLo = self._Liquid_Density(to)
                        rGo = self._Vapor_Density(to)
                        sol = fsolve(f, [to, rLo, rGo, 0.5], full_output=True)
                        T, rhoL, rhoG, x = sol[0]
                        if sol[2] == 1 and 0 <= x <= 1 and \
                                sum(abs(sol[1]["fvec"])) < 1e-5:
                            break

                    if sum(abs(sol[1]["fvec"])) > 1e-5:
                        raise(RuntimeError(sol[3]))

                    liquido = self._Helmholtz(rhoL, T)
                    vapor = self._Helmholtz(rhoG, T)
                    P = self.R*T*rhoL*rhoG/(rhoL-rhoG)*(
                        liquido["fir"]-vapor["fir"]+log(rhoL/rhoG))/1000

            elif self._mode == "Trho":
                if T < self.Tc:
                    rhov = self._Vapor_Density(T)
                    rhol = self._Liquid_Density(T)
                    if rhol > rho > rhov:
                        rhol, rhov, Ps = self._saturation(T)
                        if rhol > rho > rhov:
                            vapor = self._Helmholtz(rhov, T)
                            liquido = self._Helmholtz(rhol, T)
                            x = (1/rho-1/rhol)/(1/rhov-1/rhol)
                            P = Ps/1000

            rho = float(rho)
            T = float(T)
            propiedades = self._Helmholtz(rho, T)

            if T > self.Tc:
                x = 1
            elif x is None:
                x = 0

            if not P:
                P = propiedades["P"]/1000.

        elif self._mode == "Tx":
            # Check input T in saturation range
            if self.Tt > T or self.Tc < T or x > 1 or x < 0:
                raise NotImplementedError("Incoming out of bound")

            rhol, rhov, Ps = self._saturation(T)
            vapor = self._Helmholtz(rhov, T)
            liquido = self._Helmholtz(rhol, T)
            if x == 0:
                propiedades = liquido
            elif x == 1:
                propiedades = vapor
            P = Ps/1000.

        elif self._mode == "Px":
            # Check input P in saturation range
            if self.Pc < P or x > 1 or x < 0:
                raise NotImplementedError("Incoming out of bound")

            # Iterate over saturation routine to get T
            def f(T):
                rhol = self._Liquid_Density(T)
                rhog = self._Vapor_Density(T)

                deltaL = rhol/self.rhoc
                deltaG = rhog/self.rhoc

                tau = Tc/T

                firL = _phir(tau, deltaL, self._constants)
                firG = _phir(tau, deltaG, self._constants)
                Ps = self.R*T*rhol*rhog/(rhol-rhog)*(
                    firL-firG+log(deltaL/deltaG))
                return Ps/1000-P

            if T0:
                To = T0
            elif self.name == "water":
                To = _TSat_P(P)
            else:
                To = (self.Tc+self.Tt)/2
            T = fsolve(f, To)[0]
            rhol, rhov, Ps = self._saturation(T)
            vapor = self._Helmholtz(rhov, T)
            liquido = self._Helmholtz(rhol, T)
            if x == 0:
                propiedades = liquido
            elif x == 1:
                propiedades = vapor

        self.T = T
        self.Tr = T/self.Tc
        self.P = P
        self.Pr = self.P/self.Pc
        self.x = x
        if self._mode in ["Tx", "Px"] or 0 < x < 1:
            region = 4
        else:
            region = 0
        self.phase = getphase(self.Tc, self.Pc, self.T, self.P, self.x, region)

        self.Liquid = _fase()
        self.Gas = _fase()
        if x == 0:
            # liquid phase
            self.fill(self.Liquid, propiedades)
            self.fill(self, propiedades)
        elif x == 1:
            # vapor phase
            self.fill(self.Gas, propiedades)
            self.fill(self, propiedades)
        else:
            self.fill(self.Liquid, liquido)
            self.fill(self.Gas, vapor)

            self.v = x*self.Gas.v+(1-x)*self.Liquid.v
            self.rho = 1./self.v

            self.h = x*self.Gas.h+(1-x)*self.Liquid.h
            self.s = x*self.Gas.s+(1-x)*self.Liquid.s
            self.u = x*self.Gas.u+(1-x)*self.Liquid.u
            self.a = x*self.Gas.a+(1-x)*self.Liquid.a
            self.g = x*self.Gas.g+(1-x)*self.Liquid.g

            self.Z = x*self.Gas.Z+(1-x)*self.Liquid.Z
            self.f = x*self.Gas.f+(1-x)*self.Liquid.f

            self.Z_rho = x*self.Gas.Z_rho+(1-x)*self.Liquid.Z_rho
            self.IntP = x*self.Gas.IntP+(1-x)*self.Liquid.IntP

        # Calculate special properties useful only for one phase
        if self._mode in ("Px", "Tx") or (x < 1 and self.Tt <= T <= self.Tc):
            self.sigma = self._surface(T)
        else:
            self.sigma = None

        vir = self._virial(T)
        self.virialB = vir["B"]/self.rhoc
        self.virialC = vir["C"]/self.rhoc**2

        if 0 < x < 1:
            self.Hvap = vapor["h"]-liquido["h"]
            self.Svap = vapor["s"]-liquido["s"]
        else:
            self.Hvap = None
            self.Svap = None

        self.invT = -1/self.T

        # Ideal properties
        cp0 = self._prop0(self.rho, self.T)
        self.v0 = self.R*self.T/self.P/1000
        self.rho0 = 1./self.v0
        self.h0 = cp0.h
        self.u0 = self.h0-self.P*self.v0
        self.s0 = cp0.s
        self.a0 = self.u0-self.T*self.s0
        self.g0 = self.h0-self.T*self.s0
        self.cp0 = cp0.cp
        self.cv0 = cp0.cv
        self.cp0_cv = self.cp0/self.cv0
        cp0.v = self.v0
        self.gamma0 = -self.v0/self.P/1000*self.derivative("P", "v", "s", cp0)
509517
private static int interpolate(
        double y_minus, // = f(-1)
        double y_0, // = f(0)
        double y_plus, // = f(+1)
        double[] result // xe, ye, root1, root2
    ) {

        double a = 0.5 * (y_plus + y_minus) - y_0;
        double b = 0.5 * (y_plus - y_minus);

        double xe = -b / (2.0 * a);
        double ye = (a * xe + b) * xe + y_0;
        double dis = b * b - 4 * a * y_0;

        double root1 = Double.NaN;
        double root2 = Double.NaN;
        int count = 0;

        if (dis >= 0) {
            double dx = 0.5 * Math.sqrt(dis) / Math.abs(a);
            if (Math.abs(xe - dx) <= 1.0) {
                root1 = xe - dx;
                count++;
            }
            if (Math.abs(xe + dx) <= 1.0) {
                root2 = xe + dx;
                count++;
            }
        }

        result[0] = xe;
        result[1] = ye;
        result[2] = root1;
        result[3] = root2;

        return count;

    }
707983
@Override
    public void backward() {
        MVecArray<VarTensor> xs = modIn.getOutput();
        MVecArray<VarTensor> xsAdj = modIn.getOutputAdj();
        for (int a=0; a<xsAdj.dim(); a++) {
            VarTensor xAdj = xsAdj.get(a);
            // Compute the product of all the input factors except for a.
            // We compute this cavity by brute force, rather than dividing out from the joint.
            VarTensor prod = new VarTensor(yAdj);
            for (int b=0; b<xsAdj.dim(); b++) {
                if (a == b) { continue; }
                prod.prod(xs.get(b));
            }
            xAdj.add(prod.getMarginal(xAdj.getVars(), false));
        }
    }