Get a copy of the factor graph where the predicted variables are clamped.

@param fgLatPred The original factor graph.
@param goldConfig The assignment to the predicted variables.
@return The clamped factor graph.
517997
public static FactorGraph getFgLat(FactorGraph fgLatPred, VarConfig goldConfig) {
        // TODO: instead, have this just look at whether or not the var is in the gold config
        List<Var> predictedVars = VarSet.getVarsOfType(fgLatPred.getVars(), VarType.PREDICTED);
        VarConfig predConfig = goldConfig.getIntersection(predictedVars);
        FactorGraph fgLat = fgLatPred.getClamped(predConfig);
        assert (fgLatPred.getNumFactors() <= fgLat.getNumFactors());
        return fgLat;
    }
1204554
function getPropWalkFn(descriptor) {
  var parts = descriptor.split(/ ?\[\]/);
  if (parts.length === 2) {
    return mapProp.bind(null, parts[0]);
  }
  return getProp.bind(null, descriptor);
}
914117
def get_gl_configuration():
    
    # XXX eventually maybe we can ask `gl` whether or not we can access these
    gl.check_error('pre-config check')
    config = dict()
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
    fb_param = gl.glGetFramebufferAttachmentParameter
    # copied since they aren't in ES:
    GL_FRONT_LEFT = 1024
    GL_DEPTH = 6145
    GL_STENCIL = 6146
    GL_SRGB = 35904
    GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 33296
    GL_STEREO = 3123
    GL_DOUBLEBUFFER = 3122
    sizes = dict(red=(GL_FRONT_LEFT, 33298),
                 green=(GL_FRONT_LEFT, 33299),
                 blue=(GL_FRONT_LEFT, 33300),
                 alpha=(GL_FRONT_LEFT, 33301),
                 depth=(GL_DEPTH, 33302),
                 stencil=(GL_STENCIL, 33303))
    for key, val in sizes.items():
        config[key + '_size'] = fb_param(gl.GL_FRAMEBUFFER, val[0], val[1])
    val = fb_param(gl.GL_FRAMEBUFFER, GL_FRONT_LEFT,
                   GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING)
    if val not in (gl.GL_LINEAR, GL_SRGB):
        raise RuntimeError('unknown value for SRGB: %s' % val)
    config['srgb'] = True if val == GL_SRGB else False  # GL_LINEAR
    config['stereo'] = True if gl.glGetParameter(GL_STEREO) else False
    config['double_buffer'] = (True if gl.glGetParameter(GL_DOUBLEBUFFER)
                               else False)
    config['samples'] = gl.glGetParameter(gl.GL_SAMPLES)
    gl.check_error('post-config check')
    return config
896492
public function getConfig($pPath, $pForceGlobalArray = false)
    {
        if ($this->_config === NULL) {
            $this->_config = new Config();
        }

        return $this->_config->getConfig($pPath, $pForceGlobalArray);
    }
1305416
function loadPreset(descriptor, loader) {
  const config = Array.isArray(descriptor) ? descriptor : [descriptor];
  const [name, options = {}] = config;
  const { error: loaderError, module: getPreset } = loader(name);

  if (loaderError) {
    return {
      error: loaderError,
      name,
    };
  }

  if (typeof getPreset !== 'function') {
    return {
      error: new Error(
        `Expected the preset \`${name}\` to export a function, instead ` +
          `recieved: ${typeof getPreset}`
      ),
      name,
    };
  }

  let preset;
  try {
    preset = getPreset(options);
  } catch (error) {
    return {
      error,
      name,
      options,
    };
  }

  const { presets = [], plugins = [] } = preset;

  return {
    name,
    options,
    presets: presets.map(descriptor => loadPreset(descriptor, loader)),
    plugins: plugins.map(descriptor => loadPlugin(descriptor, loader)),
  };
}
352371
public FSArray getDepRel() {
    if (Token_Type.featOkTst && ((Token_Type)jcasType).casFeat_depRel == null)
      jcasType.jcas.throwFeatMissing("depRel", "de.julielab.jules.types.Token");
    return (FSArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((Token_Type)jcasType).casFeatCode_depRel)));}
1055196
private Tensor getMsgs(VarTensor[] inMsgs, int tf) {
        Algebra s = inMsgs[0].getAlgebra();
        EdgeScores es = new EdgeScores(n, s.zero());
        for (VarTensor inMsg : inMsgs) {
            LinkVar link = (LinkVar) inMsg.getVars().get(0);            
            double val = inMsg.getValue(tf);
            es.setScore(link.getParent(), link.getChild(), val);
        }
        return es.toTensor(s);
    }
740823
private Pair<Gradient, INDArray> getGradientsAndDelta(INDArray preOut, LayerWorkspaceMgr workspaceMgr) {
        ILossFunction lossFunction = layerConf().getLossFn();
        INDArray labels2d = getLabels2d(workspaceMgr, ArrayType.BP_WORKING_MEM);
        if (labels2d.size(1) != preOut.size(1)) {
            throw new DL4JInvalidInputException(
                            "Labels array numColumns (size(1) = " + labels2d.size(1) + ") does not match output layer"
                                            + " number of outputs (nOut = " + preOut.size(1) + ") " + layerId());
        }

        INDArray delta = lossFunction.computeGradient(labels2d, preOut, layerConf().getActivationFn(), maskArray);

        Gradient gradient = new DefaultGradient();

        INDArray weightGradView = gradientViews.get(CenterLossParamInitializer.WEIGHT_KEY);
        INDArray biasGradView = gradientViews.get(CenterLossParamInitializer.BIAS_KEY);
        INDArray centersGradView = gradientViews.get(CenterLossParamInitializer.CENTER_KEY);

        // centers delta
        double alpha = layerConf().getAlpha();

        INDArray centers = params.get(CenterLossParamInitializer.CENTER_KEY);
        INDArray l = labels.castTo(centers.dataType()); //Ensure correct dtype (same as params); no-op if already correct dtype
        INDArray centersForExamples = l.mmul(centers);
        INDArray diff = centersForExamples.sub(input).muli(alpha);
        INDArray numerator = l.transpose().mmul(diff);
        INDArray denominator = l.sum(0).reshape(l.size(1), 1).addi(1.0);

        INDArray deltaC;
        if (layerConf().getGradientCheck()) {
            double lambda = layerConf().getLambda();
            //For gradient checks: need to multiply dLc/dcj by lambda to get dL/dcj
            deltaC = numerator.muli(lambda);
        } else {
            deltaC = numerator.diviColumnVector(denominator);
        }
        centersGradView.assign(deltaC);



        // other standard calculations
        Nd4j.gemm(input, delta, weightGradView, true, false, 1.0, 0.0); //Equivalent to:  weightGradView.assign(input.transpose().mmul(delta));
        delta.sum(biasGradView, 0); //biasGradView is initialized/zeroed first in sum op

        gradient.gradientForVariable().put(CenterLossParamInitializer.WEIGHT_KEY, weightGradView);
        gradient.gradientForVariable().put(CenterLossParamInitializer.BIAS_KEY, biasGradView);
        gradient.gradientForVariable().put(CenterLossParamInitializer.CENTER_KEY, centersGradView);

        return new Pair<>(gradient, delta);
    }
66715
private void extractAllFeats(FgExampleList data, FactorTemplateList templates) {
        // Create a "no-op" counter.
        IFgModel counts = new IFgModel() {                        
            @Override
            public void addAfterScaling(FeatureVector fv, double multiplier) { }
            @Override
            public void add(int feat, double addend) { }
        };  
        
        // Loop over all factors in the dataset. 
        for (int i=0; i<data.size(); i++) {
            if (i % 1000 == 0) {
                log.debug("Processing example: " + i);
            }
            LFgExample ex = data.get(i);
            FactorGraph fgLat = MarginalLogLikelihood.getFgLat(ex.getFactorGraph(), ex.getGoldConfig());
            // Create a "no-op" inferencer, which returns arbitrary marginals.
            NoOpInferencer inferencer = new NoOpInferencer(ex.getFactorGraph());   
            for (int a=0; a<ex.getFactorGraph().getNumFactors(); a++) {
                Factor f = fgLat.getFactor(a);
                if (f instanceof ObsFeatureCarrier && f instanceof TemplateFactor) {
                    // For each observation function extractor.
                    int t = templates.getTemplateId((TemplateFactor) f);
                    if (t != -1) {
                        ((ObsFeatureCarrier) f).getObsFeatures();                                      
                    }
                } else {
                    // For each standard factor.  
                    f = ex.getFactorGraph().getFactor(a);
                    if (f instanceof GlobalFactor) {
                        ((GlobalFactor) f).addExpectedPartials(counts, 0, inferencer, a);
                    } else {
                        VarTensor marg = inferencer.getMarginalsForFactorId(a);
                        f.addExpectedPartials(counts, marg, 0);
                    }
                }
            }
        }
    }
885855
public static function setLegend( $graph, $config )
	{
		if( !self::getConfigValue( $config, 'show' ) )
		{
			$graph->legend->hide();
			return;
		}
		
		$graph->legend->setLayout( self::getConfigValue( $config, 'layout', LEGEND_VERT ) );

		$shadowShow		= self::getConfigValue( $config, 'shadow.show', FALSE );
		$shadowWidth	= self::getConfigValue( $config, 'shadow.width', 2 );
		$shadowColor	= self::getConfigValue( $config, 'shadow.color', 'gray' );
		$graph->legend->setShadow( FALSE );
		if( $shadowShow )
			$graph->legend->setShadow( $shadowColor, $shadowWidth );

		$color		= self::getConfigValue( $config, 'color', 'black' );
		$frameColor	= self::getConfigValue( $config, 'frame.color', 'black' );
		$graph->legend->setColor( $color, $frameColor );
		$graph->legend->setFrameWeight( self::getConfigValue( $config, 'frame.weight', 1 ) ); 

		$posX		= self::getConfigValue( $config, 'pos.x', 0 );
		$posY		= self::getConfigValue( $config, 'pos.y', 0 );
		$posAlignH	= self::getConfigValue( $config, 'pos.align.h', 'right' );
		$posAlignV	= self::getConfigValue( $config, 'pos.align.v', 'top' );
		$graph->legend->pos( $posX, $posY, $posAlignH, $posAlignV );

		$fillColor	= self::getConfigValue( $config, 'fill.color', NULL );
		$graph->legend->setFillColor( $fillColor );

		self::setFont( $graph->legend, $config );
	}
1072532
public String asFlatPrint() {
        val sb = new StringBuilder();
        val fb = asFlatBuffers();

        val graph = FlatGraph.getRootAsFlatGraph(fb);

        sb.append("\nExternal variables:\n\n");
        for (int e = 0; e < graph.variablesLength(); e++) {
            val var = graph.variables(e);
            INDArray ndarray = null;
            try(MemoryWorkspace ws = Nd4j.getWorkspaceManager().scopeOutOfWorkspaces()) {
                FlatArray fa = var.ndarray();
                if(fa != null) {
                    ndarray = Nd4j.createFromFlatArray(fa);
                }
            }

            sb.append(var.id().first())
                    .append(":<").append(var.name()).append("> ");
            if(ndarray == null){
                sb.append("<no array>").append("; Values: ").append("<no array>").append(";\n");
            } else {
                sb.append(Arrays.toString(ndarray.shapeInfoDataBuffer().asInt())).append("; Values: ");
                if(ndarray.data() == null){
                    //Empty array
                    sb.append("<empty array>");
                } else if(ndarray.dataType() == DataType.UTF8) {
                    sb.append("<string array>");
                } else {
                    if(ndarray.length() < 50){
                        sb.append(Arrays.toString(ndarray.data().asFloat()).replaceAll(" ",""));
                    } else {
                        //Array is too long - only tak. last few values...
                        sb.append("[");
                        for( int i=0; i<50; i++ ){
                            if(i > 0)
                                sb.append(",");
                            sb.append(ndarray.data().getFloat(i));
                        }
                        sb.append("]");
                    }
                }
                sb.append(";\n");
            }

        }

        val map = Nd4j.getExecutioner().getCustomOperations();


        sb.append("\nOps sequence:\n\n");
        for (int e = 0; e < graph.nodesLength(); e++) {
            val node = graph.nodes(e);

            log.info("{}:<{}>", node.id(), node.name());
            sb.append(node.id())
                    .append(":<").append(node.name()).append("> ").append(FlatBuffersMapper.getTypeFromByte(node.opType()));

            if (FlatBuffersMapper.getTypeFromByte(node.opType()) != Op.Type.CUSTOM)
                sb.append(": ").append(node.opNum());
            else {
                val keys = map.keySet();
                String opName = null;
                for (val k : keys) {
                    val d = map.get(k);
                    if (d.getHash() == node.opNum())
                        opName = k;
                }

                if (opName == null)
                    opName = "unknown";

                sb.append(": ").append(opName);
            }

            sb.append("; Inputs: {");

            for (int i = 0; i < node.inputPairedLength(); i++) {
                val pair = node.inputPaired(i);

                sb.append("[").append(pair.first()).append(":").append(pair.second()).append("]");

                if (i < node.inputPairedLength() - 1)
                    sb.append(", ");
            }

            sb.append("};");
            sb.append(" OpNum: {").append(node.opNum()).append("};");

            sb.append("\n");
        }


        return sb.toString();
    }
995348
public FlatGraph asFlatGraph(long graphId, ExecutorConfiguration configuration) {
        return FlatGraph.getRootAsFlatGraph(asFlatBuffers(graphId, configuration));
    }
886471
def obfn_gvar(self):
        

        if self.opt['gEvalY']:
            return self.Y
        else:
            return self.cnst_A(None, self.Xf) - self.cnst_c()
1142692
@Override
  public DynamicFactorGraph getModelFromParameters(SufficientStatistics parameters) {
    List<SufficientStatistics> parameterList = parameters.coerceToList().getStatistics();
    Preconditions.checkArgument(parameterList.size() == parametricFactors.size());
    List<PlateFactor> plateFactors = Lists.newArrayList();
    for (int i = 0; i < parameterList.size(); i++) {
      plateFactors.add(new ReplicatedFactor(
          parametricFactors.get(i).getModelFromParameters(parameterList.get(i)),
          factorPatterns.get(i)));
    }
    return baseFactorGraph.addPlateFactors(plateFactors, factorNames.items());
  }
114129
private Assignment doSamplingRound(FactorGraph factorGraph, Assignment curAssignment) {
	  Assignment assignment = curAssignment;
	  int[] variableNums = factorGraph.getVariables().getVariableNumsArray();
		for (int i = 0; i < variableNums.length; i++) {
			assignment = doSample(factorGraph, assignment, variableNums[i]);
		}
		return assignment;
	}
1019920
public static int faceWindingOrderToGL(
    final JCGLFaceWindingOrder f)
  {
    switch (f) {
      case FRONT_FACE_CLOCKWISE:
        return GL11.GL_CW;
      case FRONT_FACE_COUNTER_CLOCKWISE:
        return GL11.GL_CCW;
    }

    throw new UnreachableCodeException();
  }
82642
public void decode(FgInferencer infLatPred, UFgExample ex) {
        FactorGraph fgLatPred = ex.getFactorGraph();
        
        mbrVarConfig = new VarConfig();
        margs = new ArrayList<VarTensor>();
        varMargMap = new HashMap<Var,Double>();

        // Get the MBR configuration of all the latent and predicted
        // variables.        
        if (prm.loss == Loss.L1 || prm.loss == Loss.MSE) {
            for (int varId = 0; varId < fgLatPred.getNumVars(); varId++) {
                Var var = fgLatPred.getVar(varId);
                VarTensor marg = infLatPred.getMarginalsForVarId(varId);
                margs.add(marg);
                int argmaxState = marg.getArgmaxConfigId();
                mbrVarConfig.put(var, argmaxState);

                varMargMap.put(var, marg.getValue(argmaxState));
                if (log.isTraceEnabled()) {
                    log.trace("Variable marginal: " + marg);
                }
            }
        } else {
            throw new RuntimeException("Loss type not implemented: " + prm.loss);
        }
    }