Computes the message from {@code logFactorWeights} to {@code curVarNum}
using the current values of {@code variableMarginals}.

@param curVarNum
@param logFactorWeights
@param variableMarginals
@param variableNums
@return
513650
private static final Tensor getFactorMessage(int curVarNum, Tensor logFactorWeights,
      List<Tensor> variableMarginals, IndexedList<Integer> variableNums) {
    Tensor factorMessage = logFactorWeights;
    // Each message is the outer product of all variable marginals, except
    // variable i, elementwise multiplied by the log factor weights.
    int[] weightVariableNums = factorMessage.getDimensionNumbers();
    List<Integer> variablesToMarginalize = Lists.newArrayList();
    for (int j = 0; j < weightVariableNums.length; j++) {
      if (weightVariableNums[j] == curVarNum) {
        continue;
      }

      Tensor variableMarginal = variableMarginals.get(variableNums.getIndex(weightVariableNums[j]));
      factorMessage = factorMessage.elementwiseProduct(variableMarginal);
      variablesToMarginalize.add(weightVariableNums[j]);
    }
    return factorMessage.sumOutDimensions(variablesToMarginalize);
  }
170008
public PrimitiveMatrix calculateAssetReturns(final PrimitiveMatrix assetWeights) {
        final PrimitiveMatrix tmpAssetWeights = myRiskAversion.compareTo(DEFAULT_RISK_AVERSION) == 0 ? assetWeights : assetWeights.multiply(myRiskAversion);
        return myCovariances.multiply(tmpAssetWeights);
    }
1077923
public static Map<String, Object> findFreeMarkerContextVariables(Variables variables, String... varNames)
    {
        Map<String, Object> results = new HashMap<>();

        for (String varName : varNames)
        {
            WindupVertexFrame payload = null;
            try
            {
                payload = Iteration.getCurrentPayload(variables, null, varName);
            }
            catch (IllegalStateException | IllegalArgumentException e)
            {
                // oh well
            }

            if (payload != null)
            {
                results.put(varName, payload);
            }
            else
            {
                Iterable<? extends WindupVertexFrame> var = variables.findVariable(varName);
                if (var != null)
                {
                    results.put(varName, var);
                }
            }
        }
        return results;
    }
1209211
public Scalar<?> calculatePortfolioVariance(final PrimitiveMatrix assetWeights) {

        PrimitiveMatrix tmpLeft;
        PrimitiveMatrix tmpRight;

        if (assetWeights.countColumns() == 1L) {
            tmpLeft = assetWeights.transpose();
            tmpRight = assetWeights;
        } else {
            tmpLeft = assetWeights;
            tmpRight = assetWeights.transpose();
        }

        return tmpLeft.multiply(myCovariances.multiply(tmpRight)).toScalar(0, 0);
    }
204277
@Override
    public void makeBuildVariables(@SuppressWarnings("rawtypes") AbstractBuild build, Map<String, String> variables) {
        variables.put("ghprbShowMatrixStatus", Boolean.toString(getShowMatrixStatus()));
        variables.put("ghprbUpstreamStatus", "true");
        variables.put("ghprbCommitStatusContext", getCommitStatusContext());
        variables.put("ghprbTriggeredStatus", getTriggeredStatus());
        variables.put("ghprbStartedStatus", getStartedStatus());
        variables.put("ghprbStatusUrl", getStatusUrl());
        variables.put("ghprbAddTestResults", Boolean.toString(getAddTestResults()));

        Map<GHCommitState, StringBuilder> statusMessages = new HashMap<GHCommitState, StringBuilder>(INITIAL_CAPACITY);

        for (GhprbBuildResultMessage message : getCompletedStatus()) {
            GHCommitState state = message.getResult();
            StringBuilder sb;
            if (!statusMessages.containsKey(state)) {
                sb = new StringBuilder();
                statusMessages.put(state, sb);
            } else {
                sb = statusMessages.get(state);
                sb.append("\n");
            }
            sb.append(message.getMessage());
        }

        for (Entry<GHCommitState, StringBuilder> next : statusMessages.entrySet()) {
            String key = String.format("ghprb%sMessage", next.getKey().name());
            variables.put(key, next.getValue().toString());
        }
    }
1078037
def obfn_gvar(self):
        

        # Get inner cbpdn object gvar
        gv = self.inner_obfn_gvar().copy()
        # Set slice corresponding to the coefficient map of the final
        # filter (the impulse inserted for the AMS method) to zero so
        # that it does not affect the results (e.g. l1 norm) computed
        # from this variable by the inner cbpdn object
        gv[..., -self.cri.Cd:] = 0

        return gv
1129782
public VariableNumMap getFirstVariables(int numVariables) {
    int numToCopy = Math.min(numVariables, nums.length);
    int[] newNums = Arrays.copyOf(nums, numToCopy);
    String[] newNames = Arrays.copyOf(names, numToCopy);
    Variable[] newVars = Arrays.copyOf(vars, numToCopy);
    return VariableNumMap.fromSortedArrays(newNums, newNames, newVars);
  }
124052
@Override
  public DiscreteFactor getModelFromParameters(SufficientStatistics parameters) {
    Tensor featureWeights = getFeatureWeights(parameters);
    Tensor logProbs = featureValues.getWeights().elementwiseProduct(featureWeights)
        .sumOutDimensions(featureVariables.getVariableNumsArray());

    return exponentiateLogProbs(logProbs); 
  }
287447
static double weightedAverage(double x1, double w1, double x2, double w2) {
        if (x1 <= x2) {
            return weightedAverageSorted(x1, w1, x2, w2);
        } else {
            return weightedAverageSorted(x2, w2, x1, w1);
        }
    }
485545
public static DiscreteFactor createIndicatorFeatureTensor(VariableNumMap vars, int featureVarNum,
      TableFactorBuilder initialWeights) {
    // The "name" of an indicator feature is the assignment that it indicates.
    List<List<Object>> features = Lists.newArrayList();
    Iterator<Assignment> assignmentIterator = initialWeights != null ?
        initialWeights.assignmentIterator() : new AllAssignmentIterator(vars);
    while (assignmentIterator.hasNext()) {
      features.add(assignmentIterator.next().getValues());
    }
    DiscreteVariable featureVariable = new DiscreteVariable("indicator features", features);
    VariableNumMap featureVarMap = VariableNumMap.singleton(featureVarNum, "features-" + featureVarNum,
        featureVariable);

    TableFactorBuilder featureValueBuilder = new TableFactorBuilder(vars.union(featureVarMap),
        SparseTensorBuilder.getFactory());
    for (List<Object> featureValues : features) {
      Assignment newAssignment = vars.outcomeToAssignment(featureValues)
          .union(featureVarMap.outcomeArrayToAssignment(featureValues));
      featureValueBuilder.setWeight(newAssignment, 1.0);
    }
    return featureValueBuilder.build().cacheWeightPermutations();
  }
567487
private void makeCardinalityVariables() {
        vmsCountOnNodes = new ArrayList<>(nodes.size());
        int nbVMs = vms.size();
        for (Node n : nodes) {
            vmsCountOnNodes.add(csp.intVar(makeVarLabel("nbVMsOn('", n, "')"), 0, nbVMs, true));
        }
        vmsCountOnNodes = Collections.unmodifiableList(vmsCountOnNodes);
    }
284412
public TableFactor sumOut(int variable) {

    // OPTIMIZATION: This is by far the most common case, for linear chain inference, and is worth making fast
    // We can use closed loops, and not bother with using the basic iterator to loop through indices.
    // If this special case doesn't trip, we fall back to the standard (but slower) algorithm for the general case

    if (getDimensions().length == 2) {
      if (neighborIndices[0] == variable) {
        TableFactor marginalized = new TableFactor(new int[]{neighborIndices[1]}, new int[]{getDimensions()[1]});

        for (int i = 0; i < marginalized.values.length; i++) marginalized.values[i] = 0;

        // We use the stable log-sum-exp trick here, so first we calculate the max

        double[] max = new double[getDimensions()[1]];
        for (int j = 0; j < getDimensions()[1]; j++) {
          max[j] = Double.NEGATIVE_INFINITY;
        }

        for (int i = 0; i < getDimensions()[0]; i++) {
          int k = i * getDimensions()[1];
          for (int j = 0; j < getDimensions()[1]; j++) {
            int index = k + j;
            assert !Double.isNaN(values[index]);
            if (values[index] > max[j]) {
              max[j] = values[index];
            }
          }
        }

        // Then we take the sum, minus the max

        for (int i = 0; i < getDimensions()[0]; i++) {
          int k = i * getDimensions()[1];
          for (int j = 0; j < getDimensions()[1]; j++) {
            int index = k + j;
            if (Double.isFinite(max[j])) {
              if (USE_EXP_APPROX) {
                marginalized.values[j] += exp(values[index] - max[j]);
              } else {
                marginalized.values[j] += Math.exp(values[index] - max[j]);
              }
              assert !Double.isNaN(marginalized.values[j]);
            }
          }
        }

        // And now we exponentiate, and add back in the values

        for (int j = 0; j < getDimensions()[1]; j++) {
          if (Double.isFinite(max[j])) {
            marginalized.values[j] = max[j] + Math.log(marginalized.values[j]);
          } else {
            marginalized.values[j] = max[j];
          }
          assert !Double.isNaN(marginalized.values[j]);
        }

        return marginalized;
      } else {
        assert (neighborIndices[1] == variable);
        TableFactor marginalized = new TableFactor(new int[]{neighborIndices[0]}, new int[]{getDimensions()[0]});

        for (int i = 0; i < marginalized.values.length; i++) marginalized.values[i] = 0;

        // We use the stable log-sum-exp trick here, so first we calculate the max

        double[] max = new double[getDimensions()[0]];
        for (int i = 0; i < getDimensions()[0]; i++) {
          max[i] = Double.NEGATIVE_INFINITY;
        }

        for (int i = 0; i < getDimensions()[0]; i++) {
          int k = i * getDimensions()[1];
          for (int j = 0; j < getDimensions()[1]; j++) {
            int index = k + j;
            assert !Double.isNaN(values[index]);
            if (values[index] > max[i]) {
              max[i] = values[index];
            }
          }
        }

        // Then we take the sum, minus the max

        for (int i = 0; i < getDimensions()[0]; i++) {
          int k = i * getDimensions()[1];
          for (int j = 0; j < getDimensions()[1]; j++) {
            int index = k + j;
            if (Double.isFinite(max[i])) {
              if (USE_EXP_APPROX) {
                marginalized.values[i] += exp(values[index] - max[i]);
              } else {
                marginalized.values[i] += Math.exp(values[index] - max[i]);
              }
              assert !Double.isNaN(marginalized.values[i]);
            }
          }
        }

        // And now we exponentiate, and add back in the values

        for (int i = 0; i < getDimensions()[0]; i++) {
          if (Double.isFinite(max[i])) {
            marginalized.values[i] = max[i] + Math.log(marginalized.values[i]);
          } else {
            marginalized.values[i] = max[i];
          }
          assert !Double.isNaN(marginalized.values[i]);
        }

        return marginalized;
      }
    } else {
      // This is a little tricky because we need to use the stable log-sum-exp trick on top of our marginalize
      // dataflow operation.

      // First we calculate all the max values to use as pivots to prevent overflow
      TableFactor maxValues = maxOut(variable);

      // Then we do the sum against an offset from the pivots
      TableFactor marginalized = marginalize(variable, 0, (marginalizedVariableValue, assignment) -> (a, b) -> {
        double val = a;
        if (USE_EXP_APPROX) {
          assert !Double.isNaN(b);
          val += exp(b - maxValues.getAssignmentLogValue(assignment)) ;
          assert !Double.isNaN(val);
        } else {
          assert !Double.isNaN(b);
          val += Math.exp(b - maxValues.getAssignmentLogValue(assignment));
          assert !Double.isNaN(val);
        }
        assert !Double.isNaN(val);
        return val;
      });

      // Then we factor the max values back in, and
      for (int[] assignment : marginalized) {
        marginalized.setAssignmentLogValue(assignment, maxValues.getAssignmentLogValue(assignment) + Math.log(marginalized.getAssignmentLogValue(assignment)));
      }

      return marginalized;
    }
  }
608177
function SumFactor(sum_variable, terms_variables, coeffs) {
      if (len(terms_variables) !== len(coeffs)) {
        throw new Error("assert error");
      }
      this.sum = sum_variable;
      this.terms = terms_variables;
      this.coeffs = coeffs;
      SumFactor.__super__.constructor.call(this, [sum_variable].concat(terms_variables));
    }
439340
private VarTensor calcFactorBeliefs(Factor factor) {
        if (factor instanceof GlobalFactor) {
            log.warn("Getting marginals of a global factor is not supported."
                    + " This will require exponential space to store the resulting factor."
                    + " This should only be used for testing.");
        }        
        // Compute the product of all messages sent to this factor.
        VarTensor prod = safeNewVarTensor(factor);
        calcProductAtFactor(factor.getId(), prod, -1, -1);
        return prod;
    }
426905
Scalar<?> calculateImpliedRiskAversion(final PrimitiveMatrix assetWeights, final PrimitiveMatrix assetReturns) {

        Scalar<?> retVal = myCovariances.multiply(assetWeights).solve(assetReturns).toScalar(0, 0);

        if (retVal.isSmall(PrimitiveMath.ONE)) {
            retVal = BigScalar.ONE;
        } else if (!retVal.isAbsolute()) {
            retVal = retVal.negate();
        }

        return retVal;
    }
1046433
@Nullable
  private static Double getPathWeight(State inState, State outState, HashMap<Integer,Double>[] closure) {
    if (closure[inState.getId()] != null) {
      return closure[inState.getId()].get(outState.getId());
    }
    return null;
  }
1184408
@Override
    @SuppressWarnings("unchecked")
    public <T> Variable<T> getVariable(final String variableName) {
        final String[] subTokens = getSubVariableTokens(variableName);
        if (subTokens != null) {
            final Variable<T> sub = getSubVariable(subTokens[0], subTokens[1]);
            if (sub != null) {
                return sub;
            }
        }
        final Variable<T> v;
        synchronized (variables) {
            v = variables.get(variableName);
        }
        return v;
    }