Combines pwl, polynomial and user-defined costs.
346787
def _combine_costs(self, Npwl, Hpwl, Cpwl, fparm_pwl, any_pwl,
                       Npol, Hpol, Cpol, fparm_pol, npol, nw):
        
        NN = vstack([n for n in [Npwl, Npol] if n is not None], "csr")

        if (Hpwl is not None) and (Hpol is not None):
            Hpwl = hstack([Hpwl, csr_matrix((any_pwl, npol))])
            Hpol = hstack([csr_matrix((npol, any_pwl)), Hpol])
#        if H is not None:
#            H = hstack([csr_matrix((nw, any_pwl+npol)), H])

        HHw = vstack([h for h in [Hpwl, Hpol] if h is not None], "csr")

        CCw = r_[Cpwl, Cpol]

        ffparm = r_[fparm_pwl, fparm_pol]

        return NN, HHw, CCw, ffparm
542227
public void computeMST(double[][] costs, UndirectedGraph graph) throws ContradictionException {
		g = graph;
		for (int i = 0; i < n; i++) {
			Tree.getNeighOf(i).clear();
		}
		this.costs = costs;
		heap.clear();
		inTree.clear();
		treeCost = 0;
		tSize = 0;
		prim();
	}
380267
public void setCosts(Costs nodeCosts) {
		// add the costs from the step function
		nodeCosts.addCosts(this.solutionSetDeltaPlanNode.getCumulativeCostsShare());
		nodeCosts.addCosts(this.nextWorkSetPlanNode.getCumulativeCostsShare());

		super.setCosts(nodeCosts);
	}
636783
void compute_Rv() {
		double t = Math.sqrt(v1*v1 + v2*v2);
		double s = Math.sqrt(t*t + 1);
		double cosT = 1.0/s;
		double sinT = Math.sqrt(1-1.0/(s*s));

		K_x.data[0] = 0;   K_x.data[1] = 0;   K_x.data[2] = v1;
		K_x.data[3] = 0;   K_x.data[4] = 0;   K_x.data[5] = v2;
		K_x.data[6] = -v1; K_x.data[7] = -v2; K_x.data[8] = 0;
		CommonOps_DDRM.divide(K_x,t);
		CommonOps_DDRM.setIdentity(R_v);
		CommonOps_DDRM.addEquals(R_v,sinT,K_x);
		CommonOps_DDRM.multAdd(1.0-cosT,K_x,K_x,R_v);
	}
92447
def _pwl_costs(self, ny, nxyz, ipwl):
        
        any_pwl = int(ny > 0)
        if any_pwl:
            y = self.om.get_var("y")
            # Sum of y vars.
            Npwl = csr_matrix((ones(ny), (zeros(ny), array(ipwl) + y.i1)))
            Hpwl = csr_matrix((1, 1))
            Cpwl = array([1])
            fparm_pwl = array([[1., 0., 0., 1.]])
        else:
            Npwl = None#zeros((0, nxyz))
            Hpwl = None#array([])
            Cpwl = array([])
            fparm_pwl = zeros((0, 4))

        return Npwl, Hpwl, Cpwl, fparm_pwl, any_pwl
1281529
function penalty_costs(penalty, bounds, prmname) {
  var costs = [];
  var marg_cost, bound;

  var lastBound;
  for( var i = 2; i < penalty.length; i++ ) {
    bound = penalty[i][0] - penalty[i-1][0];
    lastBound = penalty[i][0];
    marg_cost = (penalty[i][1] - penalty[i-1][1]) / bound;

    costs.push({
      cost: marg_cost, 
      lb : 0, 
      ub: bound
    });
  }

  // TODO: adding logic here for ISSUE #36
  // Now does solutions for ISSUE #36 invalidate above statements?
  var isNegativeSlope = false;
  for( var i = 0; i < costs.length; i++ ) {
    c = costs[i];
    if( c.cost < 0 ) {
      isNegativeSlope = true;
      break;
    }
  }

  if( costs[0] === 0  ) {
    if( costs.length > 1 ) {
      if( LOCAL_DEBUG ) console.log(`${prmname}: Slope 0 but multiple k`);
    }
    return;
  }

  var updated = false;

  if( isNegativeSlope ) {

    if( bounds.LBDefined ) {
      if( costs[0].lb !== bounds.LB ) {
        costs[0].lb = bounds.LB;
        
        // need to adjust the ub as well.
        if( penalty.length >= 3 ) {
          costs[0].ub = penalty[2][0];
        }
        if( LOCAL_DEBUG ) console.log(`${prmname}: s<0 && LB, setting k=0 lb to LB`);
        updated = true;
      }
    } else {
      costs[0].lb = 0;
      if( penalty.length >= 3 ) {
        costs[0].ub = penalty[2][0];
      }

      if( LOCAL_DEBUG ) console.log(`${prmname}: s<0 && !LB, Setting k=0 lb to 0`);
      updated = true;
    }

    if( exists(bounds.UB) ) {
      if( lastBound < bounds.UB ) {
        costs.push({
          lb   : 0,
          ub   : bounds.UB - lastBound,
          cost : 0
        });
       }
    } else {
      costs.push({
        lb   : 0,
        ub   : config.maxUb || 1e9,
        cost : 0
      });
    }

  } else {

    if( bounds.LBDefined ) {
      if( costs[0].lb !== bounds.LB ) {
        costs[0].lb = bounds.LB;
        
        if( LOCAL_DEBUG ) {
          console.log(`${prmname}: s>0 && LB, Setting k=0 lb to LB`);
          if( prmname.indexOf('-') > -1 ) {
            console.log(` WARNING This should never happen!`);
          }
        }
        updated = true;
      }
    } else {

      if( costs[0].lb !== 0 ) {
        if( LOCAL_DEBUG ) {
          console.log(`${prmname}:  s>1 && !LB`);
          if( prmname.indexOf('-') > -1 ) {
            console.log(`  WARNING This should never happen! `);
          }
        }

        costs.unshift({
          cost : 0, 
          lb : 0, 
          ub : costs[0].lb
        });
        updated = true;
      }
    }

    if( exists(bounds.UB) ) {
      if( costs[costs.length-1].ub !== bounds.UB ) {
        costs[costs.length-1].ub = bounds.UB;
        if( LOCAL_DEBUG ) console.log(`${prmname}: s>0 && UB, Setting k=K ub to UB`);
        updated = true;
      }
    } else {
      var c = costs[costs.length-1];

      costs[costs.length-1].ub = config.maxUb || 1e9;

      if( LOCAL_DEBUG ) {
        console.log(`${prmname}: s>0 && !UB, Extending k to ub=${1e9}`);
        if( prmname.indexOf('-') > -1 ) {
          console.log(` WARNING This should never happen!`);
        }
      }
      updated = true;
    }
  }

  if( updated && LOCAL_DEBUG ) {
    console.log(costs);
  }

  return costs;
}
778329
def total_cost(self, p=None, p_cost=None, pcost_model=None):
        
        p = self.p if p is None else p
        p_cost = self.p_cost if p_cost is None else p_cost
        pcost_model = self.pcost_model if pcost_model is None else pcost_model

        p = 0.0 if not self.online else p

        if pcost_model == PW_LINEAR:
            n_segments = len(p_cost) - 1
            # Iterate over the piece-wise linear segments.
            for i in range(n_segments):
                x1, y1 = p_cost[i]
                x2, y2 = p_cost[i + 1]
                m = (y2 - y1) / (x2 - x1)
                c = y1 - m * x1
                if x1 <= p <= x2:
                    result = m*p + c
                    break
            else:
#                print "TOTC:", self.name, p, self.p_max, p_cost

#                raise ValueError, "Value [%f] outwith pwl cost curve." % p

                # Use the last segment for values outwith the cost curve.
                logger.error("Value [%f] outside pwl cost curve [%s]." %
                             (p, p_cost[-1][0]))
                result = m*p + c
        elif pcost_model == POLYNOMIAL:
#            result = p_cost[-1]
#            for i in range(1, len(p_cost)):
#                result += p_cost[-(i + 1)] * p**i
            result = polyval(p_cost, p)
        else:
            raise ValueError

        if self.is_load:
            return -result
        else:
            return result
334791
def _augment(self):
        
        #build a minimum cost tree
        _pred, _ready, istar, j, mu = self._build_tree()

        #update prices
        self._v[_ready] += self._d[_ready] - mu

        #augment the solution with the minimum cost path from the
        #tree. Follows an alternating path along matched, unmatched
        #edges from X to Y
        while True:
            i = _pred[j]
            self._y[j] = i
            k = j
            j = self._x[i]
            self._x[i] = k
            if i == istar:
                break
        self._update_cred()
459961
static void computePPXP( DMatrixRMaj P , DMatrixRMaj P_plus, DMatrixRMaj X , int offsetX,  DMatrixRMaj output ) {
		final int N = P.numRows;
		output.reshape(N,2);

		// diag(X) * P <-- N x 2
		for (int i = 0, index=0; i < N; i++, index += 2) {
			double x = -X.data[index+offsetX];
			output.data[index] = x*P.data[index];
			output.data[index+1] = x*P.data[index+1];
		}

		// A = P_plus*( diag(x)*P ) <-- 2 x 2
		double a00=0,a01=0,a10=0,a11=0;
		for (int i = 0, index=0; i < N; i++, index += 2) {
			a00 += P_plus.data[i]*output.data[index];
			a01 += P_plus.data[i]*output.data[index+1];
			a10 += P_plus.data[i+N]*output.data[index];
			a11 += P_plus.data[i+N]*output.data[index+1];
		}

		// P*A <-- N x 2
		for (int i = 0, index=0; i < N; i++, index += 2) {
			output.data[index]   = P.data[index]*a00 + P.data[index+1]*a10;
			output.data[index+1] = P.data[index]*a01+ P.data[index+1]*a11;
		}
	}
782301
def calculate_fee(self, input_values):
        '''
        
        '''
        total_in = sum(input_values)
        total_out = sum([utils.le2i(tx_out.value) for tx_out in self.tx_outs])
        for js in self.tx_joinsplits:
            total_in += utils.le2i(js.vpub_new)
            total_out += utils.le2i(js.vpub_old)
        return total_in - total_out
1152136
static function processStaticOptimizations( $useComments, $php, $tpl, &$node, &$resourceData, &$newNode )
    {
        $nodeType = $node[0];
        if ( $nodeType == eZTemplate::NODE_ROOT )
        {
            $children = $node[1];
            $newNode[0] = $nodeType;
            $newNode[1] = false;
            if ( $children )
            {
                $newNode[1] = array();
                foreach ( $children as $child )
                {
                    $newChild = array();
                    eZTemplateCompiler::processStaticOptimizations( $useComments, $php, $tpl, $child, $resourceData, $newChild );
                    $newNode[1][] = $newChild;
                }
            }
        }
        else if ( $nodeType == eZTemplate::NODE_TEXT )
        {
            $text = $node[2];
            $placement = $node[3];

            $newNode[0] = $nodeType;
            $newNode[1] = false;
            $newNode[2] = $text;
            $newNode[3] = $placement;
        }
        else if ( $nodeType == eZTemplate::NODE_VARIABLE )
        {
            $variableCustom = $node[1];
            $variableData = $node[2];
            $variablePlacement = $node[3];
            $dataInspection = eZTemplateCompiler::inspectVariableData( $tpl,
                                                                       $variableData, $variablePlacement,
                                                                       $resourceData );
            if ( isset( $dataInspection['new-data'] ) )
            {
                $variableData = $dataInspection['new-data'];
            }
            $newNode = $node;
            $newNode[1] = $variableCustom;
            $newNode[2] = $variableData;
            unset( $dataInspection );
        }
        else if ( $nodeType == eZTemplate::NODE_FUNCTION )
        {
            $functionChildren = $node[1];
            $functionName = $node[2];
            $functionParameters = $node[3];
            $functionPlacement = $node[4];

            $newFunctionChildren = array();
            if ( is_array( $functionChildren ) )
            {
                foreach ( $functionChildren as $functionChild )
                {
                    $newChild = array();
                    eZTemplateCompiler::processStaticOptimizations( $useComments, $php, $tpl,
                                                                        $functionChild, $resourceData, $newChild );
                    $newFunctionChildren[] = $newChild;
                }
                $functionChildren = $newFunctionChildren;
            }

            $newFunctionParameters = array();
            if ( $functionParameters )
            {
                foreach ( $functionParameters as $functionParameterName => $functionParameterData )
                {
                    $dataInspection = eZTemplateCompiler::inspectVariableData( $tpl,
                                                                                   $functionParameterData, false,
                                                                                   $resourceData );
                    if ( isset( $dataInspection['new-data'] ) )
                    {
                        $functionParameterData = $dataInspection['new-data'];
                    }
                    $newFunctionParameters[$functionParameterName] = $functionParameterData;
                }
                $functionParameters = $newFunctionParameters;
            }

            $newNode[0] = $nodeType;
            $newNode[1] = $functionChildren;
            $newNode[2] = $functionName;
            $newNode[3] = $functionParameters;
            $newNode[4] = $functionPlacement;
            if ( isset( $node[5] ) )
                $newNode[5] = $node[5];
        }
        else
            $newNode = $node;
    }
949666
void combine(final MomentStatistics b) {
		requireNonNull(b);

		final double m2 = _m2.value();
		final double m3 = _m3.value();

		final double pn = _n;
		final double n = _n + b._n;
		final double nn = n*n;

		final double d = b._m1.value() - _m1.value();
		final double dd = d*d;

		_n += b._n;

		_m1.add(d*b._n/n);

		_m2.add(b._m2).add(dd*pn*b._n/n);

		_m3.add(b._m3)
			.add(dd*d*(pn*b._n*(pn - b._n)/nn))
			.add(3.0*d*(pn*b._m2.value() - b._n*m2)/n);

		final double bnbn = (double)b._n*(double)b._n;

		_m4.add(b._m4)
			.add(dd*dd*(pn*b._n*(pn*pn - pn*b._n + bnbn)/(nn*n)))
			.add(6.0*dd*(pn*pn*b._m2.value() + bnbn*m2)/nn)
			.add(4.0*d*(pn*b._m3.value() - b._n*m3)/n);
	}
405368
def _fit_stacking_model(self,X, y, cost_mat, max_iter=100):
        """"""
        self.f_staking = CostSensitiveLogisticRegression(verbose=self.verbose, max_iter=max_iter)
        X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_,
                                          self.estimators_weight_, X, self.combination)
        self.f_staking.fit(X_stacking, y, cost_mat)
        return self
584237
def edge_cost(self, node_a, node_b):
        """"""
        cost = float('inf')
        node_object_a = self.get_node(node_a)
        for edge_id in node_object_a['edges']:
            edge = self.get_edge(edge_id)
            tpl = (node_a, node_b)
            if edge['vertices'] == tpl:
                cost = edge['cost']
                break
        return cost
1330207
def partial_fit(self, X):
        
        opt, cost = self.sess.run((self.optimizer, self.cost), 
                                  feed_dict={self.x: X})
        return cost
847419
public static double approxSumPaths(WeightedIntDiGraph g, RealVector startWeights, RealVector endWeights,
            Iterator<DiEdge> seq, DoubleConsumer c) {
        // we keep track of the total weight of discovered paths ending along
        // each edge and the total weight
        // of all paths ending at each node (including the empty path); on each
        // time step, we
        // at each step, we pick an edge (s, t), update the sum at s, and extend
        // each of those (including
        // the empty path starting there) with the edge (s, t)

        DefaultDict<DiEdge, Double> prefixWeightsEndingAt = new DefaultDict<DiEdge, Double>(Void -> 0.0);

        // we'll maintain node sums and overall sum with subtraction rather than
        // re-adding (it's an approximation anyway!)
        RealVector currentSums = startWeights.copy();
        double currentTotal = currentSums.dotProduct(endWeights);
        if (c != null) {
            c.accept(currentTotal);
        }
        for (DiEdge e : ScheduleUtils.iterable(seq)) {
            int s = e.get1();
            int t = e.get2();
            // compute the new sums
            double oldTargetSum = currentSums.getEntry(t);
            double oldEdgeSum = prefixWeightsEndingAt.get(e);
            // new edge sum is the source sum times the edge weight
            double newEdgeSum = currentSums.getEntry(s) * g.getWeight(e);
            // new target sum is the old target sum plus the difference between
            // the new and old edge sums
            double newTargetSum = oldTargetSum + (newEdgeSum - oldEdgeSum);
            // the new total is the old total plus the difference in new and
            // target
            double newTotal = currentTotal + (newTargetSum - oldTargetSum) * endWeights.getEntry(t);
            // store the new sums
            prefixWeightsEndingAt.put(e, newEdgeSum);
            currentSums.setEntry(t, newTargetSum);
            currentTotal = newTotal;
            // and report the new total to the consumer
            if (c != null) {
                c.accept(currentTotal);
            }
        }
        return currentTotal;
    }
483500
function(instance, searchNode, x, y, cost) {
		var adjacentCoordinateX = searchNode.x+x;
		var adjacentCoordinateY = searchNode.y+y;
		
		if (instance.endX === adjacentCoordinateX && instance.endY === adjacentCoordinateY) {
			instance.isDoneCalculating = true;
			var path = [];
			var pathLen = 0;
			path[pathLen] = {x: adjacentCoordinateX, y: adjacentCoordinateY};
			pathLen++;
			path[pathLen] = {x: searchNode.x, y:searchNode.y};
			pathLen++;
			var parent = searchNode.parent;
			while (parent!=null) {
				path[pathLen] = {x: parent.x, y:parent.y};
				pathLen++;
				parent = parent.parent;
			}
			path.reverse();
			instance.callback(path);
		}

		if (pointsToAvoid[adjacentCoordinateX + "_" + adjacentCoordinateY] === undefined) {
			for (var i = 0; i < acceptableTiles.length; i++) {
				if (collisionGrid[adjacentCoordinateY][adjacentCoordinateX] === acceptableTiles[i]) {
					
					var node = coordinateToNode(instance, adjacentCoordinateX, 
						adjacentCoordinateY, searchNode, cost);
					
					if (node.list === undefined) {
						node.list = EasyStar.Node.OPEN_LIST;
						instance.openList.insert(node);
					} else if (node.list === EasyStar.Node.OPEN_LIST) {
						if (searchNode.costSoFar + cost < node.costSoFar) {
							node.costSoFar = searchNode.costSoFar + cost;
							node.parent = searchNode;
						}
					}
					break;
				}
			}

		}
	}