nus-yam/ex-repair huggingface dataset:
Program: 131353
Project: 131353
Buggy source:
@Test public void testErmaGradientOneVarAssertions(){
  FactorGraph fg=new FactorGraph();
  Var t0=new Var(VarType.PREDICTED,2,"String_Node_Str",null);
  ExplicitFactor emit0=new ExplicitFactor(new VarSet(t0));
  fg.addFactor(emit0);
  emit0.setValue(0,FastMath.log(1.1));
  emit0.setValue(1,FastMath.log(1.9));
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(t0,1);
  ErmaBpPrm prm=new ErmaBpPrm();
  prm.maxIterations=10;
  prm.logDomain=logDomain;
  ErmaBp bp=new ErmaBp(fg,prm);
  bp.forward();
  bp.getOutputAdj().varBeliefs[0].setValue(0,1.0);
  bp.getOutputAdj().varBeliefs[0].setValue(1,0.0);
  bp.backward();
{
    assertEquals(2,bp.getMessagesAdj().length);
    Messages adj0=bp.getMessagesAdj()[0];
    assertEquals(0,adj0.message.getValue(0),1e-3);
    assertEquals(0,adj0.message.getValue(1),1e-3);
    assertEquals(1.181,adj0.newMessage.getValue(0),1e-3);
    assertEquals(-0.175,adj0.newMessage.getValue(1),1e-3);
    Messages adj1=bp.getMessagesAdj()[1];
    assertEquals(0,adj1.message.getValue(0),1e-3);
    assertEquals(0,adj1.message.getValue(1),1e-3);
    assertEquals(0,adj1.newMessage.getValue(0),1e-3);
    assertEquals(0,adj1.newMessage.getValue(1),1e-3);
  }
{
    assertEquals(1,bp.getPotentialsAdj().length);
    VarTensor adj=bp.getPotentialsAdj()[0];
    assertEquals(1.181,adj.getValue(0),1e-3);
    assertEquals(-0.175,adj.getValue(1),1e-3);
  }
}

Fixed version (ground truth):
@Test public void testErmaGradientOneVarAssertions(){
  FactorGraph fg=new FactorGraph();
  Var t0=new Var(VarType.PREDICTED,2,"String_Node_Str",null);
  ExplicitFactor emit0=new ExplicitFactor(new VarSet(t0));
  fg.addFactor(emit0);
  emit0.setValue(0,FastMath.log(1.1));
  emit0.setValue(1,FastMath.log(1.9));
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(t0,1);
  ErmaBpPrm prm=new ErmaBpPrm();
  prm.maxIterations=1;
  prm.logDomain=logDomain;
  ErmaBp bp=new ErmaBp(fg,prm);
  bp.forward();
  bp.getOutputAdj().varBeliefs[0].setValue(0,1.0);
  bp.getOutputAdj().varBeliefs[0].setValue(1,0.0);
  bp.backward();
{
    assertEquals(2,bp.getMessagesAdj().length);
    Messages adj0=bp.getMessagesAdj()[0];
    assertEquals(0,adj0.message.getValue(0),1e-3);
    assertEquals(0,adj0.message.getValue(1),1e-3);
    assertEquals(1.181,adj0.newMessage.getValue(0),1e-3);
    assertEquals(-0.175,adj0.newMessage.getValue(1),1e-3);
    Messages adj1=bp.getMessagesAdj()[1];
    assertEquals(0,adj1.message.getValue(0),1e-3);
    assertEquals(0,adj1.message.getValue(1),1e-3);
    assertEquals(0,adj1.newMessage.getValue(0),1e-3);
    assertEquals(0,adj1.newMessage.getValue(1),1e-3);
  }
{
    assertEquals(1,bp.getPotentialsAdj().length);
    VarTensor adj=bp.getPotentialsAdj()[0];
    assertEquals(1.181,adj.getValue(0),1e-3);
    assertEquals(-0.175,adj.getValue(1),1e-3);
  }
}
Program: 131355
Project: 131355
Buggy source:
private void checkLogOddsRatios(EdgeScores es,Algebra s){
  double minOddsRatio=s.posInf();
  double maxOddsRatio=s.negInf();
  for (int p=-1; p < n; p++) {
    for (int c=0; c < n; c++) {
      double oddsRatio=es.getScore(p,c);
      if (s.lt(oddsRatio,minOddsRatio) && oddsRatio != s.zero()) {
        minOddsRatio=oddsRatio;
      }
      if (s.gt(oddsRatio,maxOddsRatio)) {
        maxOddsRatio=oddsRatio;
      }
    }
  }
  oddsRatioCount++;
  if (s.minus(s.plus(maxOddsRatio,minOddsRatio),maxOddsRatio) == s.zero()) {
    extremeOddsRatios++;
    log.debug(String.format("String_Node_Str",maxOddsRatio,minOddsRatio));
    log.debug(String.format("String_Node_Str",(double)extremeOddsRatios / oddsRatioCount,extremeOddsRatios,oddsRatioCount));
    log.debug(String.format("String_Node_Str",(double)unsafeLogSubtracts / logSubtractCount,unsafeLogSubtracts,logSubtractCount));
  }
}

Fixed version (ground truth):
private void checkLogOddsRatios(EdgeScores es,Algebra s){
  double minOddsRatio=s.posInf();
  double maxOddsRatio=s.minValue();
  for (int p=-1; p < n; p++) {
    for (int c=0; c < n; c++) {
      double oddsRatio=es.getScore(p,c);
      if (s.lt(oddsRatio,minOddsRatio) && oddsRatio != s.zero()) {
        minOddsRatio=oddsRatio;
      }
      if (s.gt(oddsRatio,maxOddsRatio)) {
        maxOddsRatio=oddsRatio;
      }
    }
  }
  oddsRatioCount++;
  if (s.minus(s.plus(maxOddsRatio,minOddsRatio),maxOddsRatio) == s.zero()) {
    extremeOddsRatios++;
    log.debug(String.format("String_Node_Str",maxOddsRatio,minOddsRatio));
    log.debug(String.format("String_Node_Str",(double)extremeOddsRatios / oddsRatioCount,extremeOddsRatios,oddsRatioCount));
    log.debug(String.format("String_Node_Str",(double)unsafeLogSubtracts / logSubtractCount,unsafeLogSubtracts,logSubtractCount));
  }
}
Program: 131356
Project: 131356
Buggy source:
public ErmaBp(final FactorGraph fg,ErmaBpPrm prm,ExpFamFactorsModule effm){
  this.fg=fg;
  this.s=prm.getAlgebra();
  this.prm=prm;
  this.effm=effm;
  if (!s.equals(effm.getAlgebra())) {
    throw new IllegalArgumentException("String_Node_Str" + s + "String_Node_Str"+ effm.getAlgebra());
  }
  if (prm.updateOrder == BpUpdateOrder.SEQUENTIAL) {
    if (prm.schedule == BpScheduleType.TREE_LIKE) {
      sched=new BfsBpSchedule(fg);
    }
 else     if (prm.schedule == BpScheduleType.RANDOM) {
      sched=new RandomBpSchedule(fg);
    }
 else {
      throw new RuntimeException("String_Node_Str" + prm.schedule);
    }
  }
 else {
    sched=new BpSchedule(){
      @Override public List<FgEdge> getOrder(){
        return fg.getEdges();
      }
    }
;
  }
}

Fixed version (ground truth):
public ErmaBp(final FactorGraph fg,ErmaBpPrm prm,ExpFamFactorsModule effm){
  this.fg=fg;
  this.s=prm.getAlgebra();
  this.prm=prm;
  this.effm=effm;
  if (effm != null && !s.equals(effm.getAlgebra())) {
    throw new IllegalArgumentException("String_Node_Str" + s + "String_Node_Str"+ effm.getAlgebra());
  }
  if (prm.updateOrder == BpUpdateOrder.SEQUENTIAL) {
    if (prm.schedule == BpScheduleType.TREE_LIKE) {
      sched=new BfsBpSchedule(fg);
    }
 else     if (prm.schedule == BpScheduleType.RANDOM) {
      sched=new RandomBpSchedule(fg);
    }
 else {
      throw new RuntimeException("String_Node_Str" + prm.schedule);
    }
  }
 else {
    sched=new BpSchedule(){
      @Override public List<FgEdge> getOrder(){
        return fg.getEdges();
      }
    }
;
  }
}
Program: 131357
Project: 131357
Buggy source:
/** 
 * Gets messages from the Messages[].
 * @param parent The node for this factor.
 * @param msgs The input messages.
 * @param tf Whether to get TRUE or FALSE messages.
 * @param isNew Whether to get messages from .newMessage or .message.
 * @param isIn Whether to get incoming or outgoing messages.
 * @param s The abstract algebra.
 * @return The output messages.
 */
private Tensor getMsgs(FgNode parent,Messages[] msgs,int tf,boolean isNew,boolean isIn,Algebra s){
  EdgeScores es=new EdgeScores(n,s.zero());
  DoubleArrays.fill(es.root,s.zero());
  DoubleArrays.fill(es.child,s.zero());
  List<FgEdge> edges=(isIn) ? parent.getInEdges() : parent.getOutEdges();
  for (  FgEdge edge : edges) {
    LinkVar link=(LinkVar)edge.getVar();
    VarTensor msg=(isNew) ? msgs[edge.getId()].newMessage : msgs[edge.getId()].message;
    double val=msg.getValue(tf);
    es.setScore(link.getParent(),link.getChild(),val);
  }
  return es.toTensor(s);
}

Fixed version (ground truth):
/** 
 * Gets messages from the Messages[].
 * @param parent The node for this factor.
 * @param msgs The input messages.
 * @param tf Whether to get TRUE or FALSE messages.
 * @param isNew Whether to get messages in .newMessage or .message.
 * @param isIn Whether to get incoming or outgoing messages.
 * @param s The abstract algebra.
 * @return The output messages.
 */
private Tensor getMsgs(FgNode parent,Messages[] msgs,int tf,boolean isNew,boolean isIn,Algebra s){
  EdgeScores es=new EdgeScores(n,s.zero());
  DoubleArrays.fill(es.root,s.zero());
  DoubleArrays.fill(es.child,s.zero());
  List<FgEdge> edges=(isIn) ? parent.getInEdges() : parent.getOutEdges();
  for (  FgEdge edge : edges) {
    LinkVar link=(LinkVar)edge.getVar();
    VarTensor msg=(isNew) ? msgs[edge.getId()].newMessage : msgs[edge.getId()].message;
    double val=msg.getValue(tf);
    es.setScore(link.getParent(),link.getChild(),val);
  }
  return es.toTensor(s);
}
Program: 131358
Project: 131358
Buggy source:
/** 
 * Sets messages on a Messages[].
 * @param parent The node for this factor.
 * @param msgs The output messages.
 * @param t The input messages.
 * @param tf Whether to set TRUE or FALSE messages.
 * @param isNew Whether to set messages from .newMessage or .message.
 * @param isIn Whether to set incoming or outgoing messages.
 * @param s The abstract algebra.
 */
private void setMsgs(FgNode parent,Messages[] msgs,Tensor t,int tf,boolean isNew,boolean isIn,Algebra s){
  EdgeScores es=EdgeScores.tensorToEdgeScores(t);
  List<FgEdge> edges=(isIn) ? parent.getInEdges() : parent.getOutEdges();
  for (  FgEdge edge : edges) {
    LinkVar link=(LinkVar)edge.getVar();
    VarTensor msg=(isNew) ? msgs[edge.getId()].newMessage : msgs[edge.getId()].message;
    double val=es.getScore(link.getParent(),link.getChild());
    msg.setValue(tf,val);
  }
}

Fixed version (ground truth):
/** 
 * Sets messages on a Messages[].
 * @param parent The node for this factor.
 * @param msgs The output messages.
 * @param t The input messages.
 * @param tf Whether to set TRUE or FALSE messages.
 * @param isNew Whether to set messages in .newMessage or .message.
 * @param isIn Whether to set incoming or outgoing messages.
 * @param s The abstract algebra.
 */
private void setMsgs(FgNode parent,Messages[] msgs,Tensor t,int tf,boolean isNew,boolean isIn,Algebra s){
  EdgeScores es=EdgeScores.tensorToEdgeScores(t);
  List<FgEdge> edges=(isIn) ? parent.getInEdges() : parent.getOutEdges();
  for (  FgEdge edge : edges) {
    LinkVar link=(LinkVar)edge.getVar();
    VarTensor msg=(isNew) ? msgs[edge.getId()].newMessage : msgs[edge.getId()].message;
    double val=es.getScore(link.getParent(),link.getChild());
    msg.setValue(tf,val);
  }
}
Program: 131359
Project: 131359
Buggy source:
public void forwardAndBackward(FgNode parent,Messages[] msgs,Messages[] msgsAdj,Algebra s,boolean isForward){
  Tensor tmTrueIn=getMsgs(parent,msgs,LinkVar.TRUE,CUR_MSG,IN_MSG,s);
  Tensor tmFalseIn=getMsgs(parent,msgs,LinkVar.FALSE,CUR_MSG,IN_MSG,s);
  TensorIdentity mTrueIn=new TensorIdentity(tmTrueIn);
  TensorIdentity mFalseIn=new TensorIdentity(tmFalseIn);
  Algebra tmpS=(isForward) ? new LogSemiring() : new LogPosNegAlgebra();
  ProjDepTreeModule dep=new ProjDepTreeModule(mTrueIn,mFalseIn,tmpS);
  dep.forward();
  if (isForward) {
    Pair<Tensor,Tensor> pair=dep.getOutput();
    Tensor tmTrueOut=pair.get1();
    Tensor tmFalseOut=pair.get2();
    setMsgs(parent,msgs,tmTrueOut,LinkVar.TRUE,NEW_MSG,OUT_MSG,s);
    setMsgs(parent,msgs,tmFalseOut,LinkVar.FALSE,NEW_MSG,OUT_MSG,s);
  }
 else {
    Tensor tTrue=getMsgs(parent,msgsAdj,LinkVar.TRUE,NEW_MSG,OUT_MSG,s);
    Tensor tFalse=getMsgs(parent,msgsAdj,LinkVar.FALSE,NEW_MSG,OUT_MSG,s);
    Pair<Tensor,Tensor> pairAdj=dep.getOutputAdj();
    Tensor tmTrueOutAdj=pairAdj.get1();
    Tensor tmFalseOutAdj=pairAdj.get2();
    tmTrueOutAdj.elemAdd(tTrue);
    tmFalseOutAdj.elemAdd(tFalse);
    dep.backward();
    setMsgs(parent,msgsAdj,mTrueIn.getOutputAdj(),LinkVar.TRUE,CUR_MSG,IN_MSG,s);
    setMsgs(parent,msgsAdj,mFalseIn.getOutputAdj(),LinkVar.TRUE,CUR_MSG,IN_MSG,s);
  }
}

Fixed version (ground truth):
public void forwardAndBackward(FgNode parent,Messages[] msgs,Messages[] msgsAdj,Algebra s,boolean isForward){
  Tensor tmTrueIn=getMsgs(parent,msgs,LinkVar.TRUE,CUR_MSG,IN_MSG,s);
  Tensor tmFalseIn=getMsgs(parent,msgs,LinkVar.FALSE,CUR_MSG,IN_MSG,s);
  TensorIdentity mTrueIn=new TensorIdentity(tmTrueIn);
  TensorIdentity mFalseIn=new TensorIdentity(tmFalseIn);
  Algebra tmpS=(isForward) ? new LogSemiring() : new LogPosNegAlgebra();
  ProjDepTreeModule dep=new ProjDepTreeModule(mTrueIn,mFalseIn,tmpS);
  dep.forward();
  if (isForward) {
    Pair<Tensor,Tensor> pair=dep.getOutput();
    Tensor tmTrueOut=pair.get1();
    Tensor tmFalseOut=pair.get2();
    setMsgs(parent,msgs,tmTrueOut,LinkVar.TRUE,NEW_MSG,OUT_MSG,s);
    setMsgs(parent,msgs,tmFalseOut,LinkVar.FALSE,NEW_MSG,OUT_MSG,s);
  }
 else {
    Tensor tTrue=getMsgs(parent,msgsAdj,LinkVar.TRUE,NEW_MSG,OUT_MSG,s);
    Tensor tFalse=getMsgs(parent,msgsAdj,LinkVar.FALSE,NEW_MSG,OUT_MSG,s);
    Pair<Tensor,Tensor> pairAdj=dep.getOutputAdj();
    Tensor tmTrueOutAdj=pairAdj.get1();
    Tensor tmFalseOutAdj=pairAdj.get2();
    tmTrueOutAdj.elemAdd(tTrue);
    tmFalseOutAdj.elemAdd(tFalse);
    dep.backward();
    addMsgs(parent,msgsAdj,mTrueIn.getOutputAdj(),LinkVar.TRUE,CUR_MSG,IN_MSG,s);
    addMsgs(parent,msgsAdj,mFalseIn.getOutputAdj(),LinkVar.FALSE,CUR_MSG,IN_MSG,s);
  }
}
Program: 131360
Project: 131360
Buggy source:
@Test public void testErmaGradient2WordGlobalFactor(){
  double[] root=new double[]{1.0,1.0};
  double[][] child=new double[][]{{0.0,1.0},{0.0,1.0}};
  FgAndLinks fgl=ProjDepTreeFactorTest.getFgl(root,child,logDomain);
  FactorGraph fg=fgl.fg;
  LinkVar[] rootVars=fgl.rootVars;
  LinkVar[][] childVars=fgl.childVars;
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(rootVars[0],0);
  goldConfig.put(rootVars[1],1);
  goldConfig.put(childVars[0][1],0);
  goldConfig.put(childVars[1][0],1);
  ErmaErFn fn=new ErmaErFn(fg,goldConfig);
  testGradientByFiniteDifferences(fn);
}

Fixed version (ground truth):
@Test public void testErmaGradient2WordGlobalFactor(){
  double[] root=new double[]{1.0,1.0};
  double[][] child=new double[][]{{0.0,1.0},{1.0,0.0}};
  FgAndLinks fgl=ProjDepTreeFactorTest.getFgl(root,child,logDomain);
  FactorGraph fg=fgl.fg;
  LinkVar[] rootVars=fgl.rootVars;
  LinkVar[][] childVars=fgl.childVars;
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(rootVars[0],0);
  goldConfig.put(rootVars[1],1);
  goldConfig.put(childVars[0][1],0);
  goldConfig.put(childVars[1][0],1);
  ErmaErFn fn=new ErmaErFn(fg,goldConfig);
  testGradientByFiniteDifferences(fn);
}
Program: 131361
Project: 131361
Buggy source:
@Override public void backward(){
  final int n=graph.getNumTokens();
  scores.alphaAdj=new double[graph.getNodes().size()];
  scores.betaAdj=new double[graph.getNodes().size()];
  for (  Hypernode node : graph.getNodes()) {
    if (node instanceof PCBasicHypernode) {
      PCBasicHypernode pc=(PCBasicHypernode)node;
      int p=pc.getP();
      int c=pc.getC();
      int pp=EdgeScores.getTensorParent(p,c);
      int id=node.getId();
      scores.alphaAdj[id]=yAdj.get(ALPHA_IDX,pp,c);
      scores.betaAdj[id]=yAdj.get(BETA_IDX,pp,c);
    }
  }
  scores.betaAdj[graph.getRoot().getId()]=yAdj.get(ROOT_IDX,0,0);
  Hyperpotential w=graph.getPotentials();
  Hyperalgo.outsideAdjoint(graph,w,s,scores);
  Hyperalgo.insideAdjoint(graph,w,s,scores);
  Hyperalgo.weightAdjoint(graph,w,s,scores);
  final Tensor wAdj=weightsIn.getOutputAdj();
  HyperedgeDoubleFn lambda=new HyperedgeDoubleFn(){
    public void apply(    Hyperedge e,    double adj_w_e){
      Hypernode head=e.getHeadNode();
      if (head instanceof PCBasicHypernode) {
        PCBasicHypernode pc=(PCBasicHypernode)head;
        int p=pc.getP();
        int c=pc.getC();
        int pp=EdgeScores.getTensorParent(p,c);
        wAdj.add(adj_w_e,pp,c);
      }
    }
  }
;
  Hyperalgo.weightAdjoint(graph,w,s,scores,lambda);
}

Fixed version (ground truth):
@Override public void backward(){
  scores.alphaAdj=new double[graph.getNodes().size()];
  scores.betaAdj=new double[graph.getNodes().size()];
  DoubleArrays.fill(scores.alphaAdj,s.zero());
  DoubleArrays.fill(scores.betaAdj,s.zero());
  for (  Hypernode node : graph.getNodes()) {
    if (node instanceof PCBasicHypernode) {
      PCBasicHypernode pc=(PCBasicHypernode)node;
      int p=pc.getP();
      int c=pc.getC();
      int pp=EdgeScores.getTensorParent(p,c);
      int id=node.getId();
      scores.alphaAdj[id]=yAdj.get(ALPHA_IDX,pp,c);
      scores.betaAdj[id]=yAdj.get(BETA_IDX,pp,c);
    }
  }
  scores.betaAdj[graph.getRoot().getId()]=yAdj.get(ROOT_IDX,0,0);
  Hyperpotential w=graph.getPotentials();
  Hyperalgo.outsideAdjoint(graph,w,s,scores);
  Hyperalgo.insideAdjoint(graph,w,s,scores);
  final Tensor wAdj=weightsIn.getOutputAdj();
  HyperedgeDoubleFn lambda=new HyperedgeDoubleFn(){
    public void apply(    Hyperedge e,    double adj_w_e){
      Hypernode head=e.getHeadNode();
      if (head instanceof PCBasicHypernode) {
        PCBasicHypernode pc=(PCBasicHypernode)head;
        int p=pc.getP();
        int c=pc.getC();
        int pp=EdgeScores.getTensorParent(p,c);
        wAdj.add(adj_w_e,pp,c);
      }
    }
  }
;
  Hyperalgo.weightAdjoint(graph,w,s,scores,lambda);
}
Program: 131362
Project: 131362
Buggy source:
public static void assertFdAndAdEqual(ModuleVecFn vecFn,double epsilon,double delta){
  int numParams=vecFn.getNumDimensions();
  IntDoubleDenseVector x=getMultiZeroOneGaussian(numParams);
  int outDim=vecFn.forward(x).size();
  for (int i=0; i < outDim; i++) {
    for (int j=0; j < numParams; j++) {
      ModuleFn fn=new ModuleFn(vecFn,i);
      IntDoubleVector d=new IntDoubleDenseVector(numParams);
      d.set(j,1);
      double dotFd=StochasticGradientApproximation.getGradDotDirApprox(fn,x,d,epsilon);
      IntDoubleVector grad=fn.getGradient(x);
      double dotAd=grad.dot(d);
      double relError=Math.abs(dotFd - dotAd) / Math.max(Math.abs(dotFd),Math.abs(dotAd));
      System.out.println("String_Node_Str" + dotFd + "String_Node_Str"+ dotAd+ "String_Node_Str"+ relError);
      assertEquals(dotFd,dotAd,delta);
    }
  }
}

Fixed version (ground truth):
public static void assertFdAndAdEqual(ModuleVecFn vecFn,IntDoubleDenseVector x,double epsilon,double delta){
  int numParams=vecFn.getNumDimensions();
  int outDim=vecFn.forward(x).size();
  for (int i=0; i < outDim; i++) {
    for (int j=0; j < numParams; j++) {
      ModuleFn fn=new ModuleFn(vecFn,i);
      IntDoubleVector d=new IntDoubleDenseVector(numParams);
      d.set(j,1);
      double dotFd=StochasticGradientApproximation.getGradDotDirApprox(fn,x,d,epsilon);
      IntDoubleVector grad=fn.getGradient(x);
      double dotAd=grad.dot(d);
      double relError=Math.abs(dotFd - dotAd) / Math.max(Math.abs(dotFd),Math.abs(dotAd));
      System.out.printf("String_Node_Str",i,j,dotFd,dotAd,relError);
      assertEquals(dotFd,dotAd,delta);
    }
  }
}
Program: 131363
Project: 131363
Buggy source:
@Override public double getValue(IntDoubleVector point){
  return vecFn.forward(point).getValue(outIdx);
}

Fixed version (ground truth):
@Override public double getValue(IntDoubleVector point){
  Tensor out=vecFn.forward(point);
  return out.getValue(outIdx);
}
Program: 131364
Project: 131364
Buggy source:
@Test public void testErmaGradientOneVar(){
  FactorGraph fg=new FactorGraph();
  Var t0=new Var(VarType.PREDICTED,2,"String_Node_Str",null);
  ExplicitFactor emit0=new ExplicitFactor(new VarSet(t0));
  fg.addFactor(emit0);
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(t0,1);
  ErmaErFn fn=new ErmaErFn(fg,goldConfig);
  Prng.seed(12345);
  fn.getGradient(getTheta(fn.getNumDimensions()));
  IntDoubleVector gradAd=testGradientByFiniteDifferences(fn);
}

Fixed version (ground truth):
@Test public void testErmaGradientOneVar(){
  FactorGraph fg=new FactorGraph();
  Var t0=new Var(VarType.PREDICTED,2,"String_Node_Str",null);
  ExplicitFactor emit0=new ExplicitFactor(new VarSet(t0));
  fg.addFactor(emit0);
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(t0,1);
  ErmaErFn fn=new ErmaErFn(fg,goldConfig);
  Prng.seed(12345);
  fn.getGradient(ModuleTestUtils.getAbsZeroOneGaussian(fn.getNumDimensions()));
  IntDoubleVector gradAd=testGradientByFiniteDifferences(fn);
}
Program: 131365
Project: 131365
Buggy source:
private static IntDoubleVector testGradientByFiniteDifferences(ErmaErFn fn){
  Prng.seed(12345);
  int numParams=fn.getNumDimensions();
  IntDoubleVector theta0=getTheta(numParams);
  System.out.println("String_Node_Str" + theta0);
  Prng.seed(System.currentTimeMillis());
  IntDoubleVector gradFd0=StochasticGradientApproximation.estimateGradientSpsa(fn,theta0,1000);
  IntDoubleVector gradFd1=StochasticGradientApproximation.estimateGradientSpsa(fn,theta0,1000);
  IntDoubleVector gradAd=fn.getGradient(theta0);
  System.out.println("String_Node_Str" + gradFd0);
  System.out.println("String_Node_Str" + gradFd1);
  System.out.println("String_Node_Str" + gradAd);
  double infNormFd=infNorm(gradFd0,gradFd1);
  double infNorm=infNorm(gradFd0,gradAd);
  System.out.println("String_Node_Str" + infNormFd);
  System.out.println("String_Node_Str" + infNorm);
  assertTrue(infNorm < 1e-1);
  return gradAd;
}

Fixed version (ground truth):
private static IntDoubleVector testGradientByFiniteDifferences(ErmaErFn fn){
  Prng.seed(12345);
  int numParams=fn.getNumDimensions();
  IntDoubleVector theta0=ModuleTestUtils.getAbsZeroOneGaussian(numParams);
  System.out.println("String_Node_Str" + theta0);
  Prng.seed(System.currentTimeMillis());
  IntDoubleVector gradFd0=StochasticGradientApproximation.estimateGradientSpsa(fn,theta0,1000);
  IntDoubleVector gradFd1=StochasticGradientApproximation.estimateGradientSpsa(fn,theta0,1000);
  IntDoubleVector gradAd=fn.getGradient(theta0);
  System.out.println("String_Node_Str" + gradFd0);
  System.out.println("String_Node_Str" + gradFd1);
  System.out.println("String_Node_Str" + gradAd);
  double infNormFd=infNorm(gradFd0,gradFd1);
  double infNorm=infNorm(gradFd0,gradAd);
  System.out.println("String_Node_Str" + infNormFd);
  System.out.println("String_Node_Str" + infNorm);
  assertTrue(infNorm < 1e-1);
  return gradAd;
}
Program: 131366
Project: 131366
Buggy source:
@Override public Tensor forward(){
  EdgeScores es=EdgeScores.tensorToEdgeScores(weightsIn.getOutput());
  scores=new Scores();
  graph=new FirstOrderDepParseHypergraph(es.root,es.child,s);
  Hyperpotential w=graph.getPotentials();
  Hyperalgo.insideAlgorithm(graph,w,s,scores);
  Hyperalgo.outsideAlgorithm(graph,w,s,scores);
  int n=graph.getNumTokens();
  y=new Tensor(3,n,n);
  y.fill(s.zero());
  for (  Hypernode node : graph.getNodes()) {
    if (node instanceof PCBasicHypernode) {
      PCBasicHypernode pc=(PCBasicHypernode)node;
      int p=pc.getP();
      int c=pc.getC();
      int pp=EdgeScores.getTensorParent(n,p,c);
      int id=node.getId();
      y.set(scores.beta[id],BETA_IDX,pp,c);
      y.set(scores.alpha[id],ALPHA_IDX,pp,c);
    }
  }
  y.set(scores.beta[graph.getRoot().getId()],ROOT_IDX,0,0);
  return y;
}

Fixed version (ground truth):
@Override public Tensor forward(){
  scores=new Scores();
  EdgeScores es=EdgeScores.tensorToEdgeScores(weightsIn.getOutput());
  graph=new FirstOrderDepParseHypergraph(es.root,es.child,s);
  Hyperpotential w=graph.getPotentials();
  Hyperalgo.insideAlgorithm(graph,w,s,scores);
  Hyperalgo.outsideAlgorithm(graph,w,s,scores);
  int n=graph.getNumTokens();
  y=new Tensor(3,n,n);
  y.fill(s.zero());
  for (  Hypernode node : graph.getNodes()) {
    if (node instanceof PCBasicHypernode) {
      PCBasicHypernode pc=(PCBasicHypernode)node;
      int p=pc.getP();
      int c=pc.getC();
      int pp=EdgeScores.getTensorParent(n,p,c);
      int id=node.getId();
      y.set(scores.beta[id],BETA_IDX,pp,c);
      y.set(scores.alpha[id],ALPHA_IDX,pp,c);
    }
  }
  y.set(scores.beta[graph.getRoot().getId()],ROOT_IDX,0,0);
  return y;
}
Program: 131367
Project: 131367
Buggy source:
@Override public void backward(){
  final int n=graph.getNumTokens();
  for (  Hypernode node : graph.getNodes()) {
    if (node instanceof PCBasicHypernode) {
      PCBasicHypernode pc=(PCBasicHypernode)node;
      int p=pc.getP();
      int c=pc.getC();
      int pp=EdgeScores.getTensorParent(n,p,c);
      int id=node.getId();
      scores.alphaAdj[id]=yAdj.get(ALPHA_IDX,pp,c);
      scores.betaAdj[id]=yAdj.get(BETA_IDX,pp,c);
    }
  }
  scores.betaAdj[graph.getRoot().getId()]=yAdj.get(ROOT_IDX,0,0);
  Hyperpotential w=graph.getPotentials();
  Hyperalgo.outsideAdjoint(graph,w,s,scores);
  Hyperalgo.insideAdjoint(graph,w,s,scores);
  Hyperalgo.weightAdjoint(graph,w,s,scores);
  final Tensor wAdj=weightsIn.getOutputAdj();
  HyperedgeDoubleFn lambda=new HyperedgeDoubleFn(){
    public void apply(    Hyperedge e,    double adj_w_e){
      Hypernode head=e.getHeadNode();
      if (head instanceof PCBasicHypernode) {
        PCBasicHypernode pc=(PCBasicHypernode)head;
        int p=pc.getP();
        int c=pc.getC();
        int pp=EdgeScores.getTensorParent(n,p,c);
        wAdj.add(adj_w_e,pp,c);
      }
    }
  }
;
  Hyperalgo.weightAdjoint(graph,w,s,scores,lambda);
}

Fixed version (ground truth):
@Override public void backward(){
  final int n=graph.getNumTokens();
  scores.alphaAdj=new double[graph.getNodes().size()];
  scores.betaAdj=new double[graph.getNodes().size()];
  for (  Hypernode node : graph.getNodes()) {
    if (node instanceof PCBasicHypernode) {
      PCBasicHypernode pc=(PCBasicHypernode)node;
      int p=pc.getP();
      int c=pc.getC();
      int pp=EdgeScores.getTensorParent(n,p,c);
      int id=node.getId();
      scores.alphaAdj[id]=yAdj.get(ALPHA_IDX,pp,c);
      scores.betaAdj[id]=yAdj.get(BETA_IDX,pp,c);
    }
  }
  scores.betaAdj[graph.getRoot().getId()]=yAdj.get(ROOT_IDX,0,0);
  Hyperpotential w=graph.getPotentials();
  Hyperalgo.outsideAdjoint(graph,w,s,scores);
  Hyperalgo.insideAdjoint(graph,w,s,scores);
  Hyperalgo.weightAdjoint(graph,w,s,scores);
  final Tensor wAdj=weightsIn.getOutputAdj();
  HyperedgeDoubleFn lambda=new HyperedgeDoubleFn(){
    public void apply(    Hyperedge e,    double adj_w_e){
      Hypernode head=e.getHeadNode();
      if (head instanceof PCBasicHypernode) {
        PCBasicHypernode pc=(PCBasicHypernode)head;
        int p=pc.getP();
        int c=pc.getC();
        int pp=EdgeScores.getTensorParent(n,p,c);
        wAdj.add(adj_w_e,pp,c);
      }
    }
  }
;
  Hyperalgo.weightAdjoint(graph,w,s,scores,lambda);
}
Program: 131368
Project: 131368
Buggy source:
public static void assertFdAndAdEqual(VecFn vecFn,IntDoubleDenseVector x,double epsilon,double delta){
  int numParams=vecFn.getNumDimensions();
  int outDim=vecFn.forward(x).size();
  for (int i=0; i < outDim; i++) {
    for (int j=0; j < numParams; j++) {
      ModuleFn fn=new ModuleFn(vecFn,i);
      IntDoubleVector d=new IntDoubleDenseVector(numParams);
      d.set(j,1);
      double dotFd=StochasticGradientApproximation.getGradDotDirApprox(fn,x,d,epsilon);
      IntDoubleVector grad=fn.getGradient(x);
      double dotAd=grad.dot(d);
      double relError=Math.abs(dotFd - dotAd) / Math.max(Math.abs(dotFd),Math.abs(dotAd));
      System.out.printf("String_Node_Str",i,j,dotFd,dotAd,relError);
      assertEquals(dotFd,dotAd,delta);
    }
  }
}

Fixed version (ground truth):
public static void assertFdAndAdEqual(DifferentiableFunction fn,IntDoubleVector x,double epsilon,double delta){
  int numParams=fn.getNumDimensions();
  for (int j=0; j < numParams; j++) {
    IntDoubleVector d=new IntDoubleDenseVector(numParams);
    d.set(j,1);
    double dotFd=StochasticGradientApproximation.getGradDotDirApprox(fn,x,d,epsilon);
    IntDoubleVector grad=fn.getGradient(x);
    double dotAd=grad.dot(d);
    double relError=Math.abs(dotFd - dotAd) / Math.max(Math.abs(dotFd),Math.abs(dotAd));
    System.out.printf("String_Node_Str",j,dotFd,dotAd,relError);
    assertEquals(dotFd,dotAd,delta);
  }
}
Program: 131369
Project: 131369
Buggy source:
private static IntDoubleVector testGradientByFiniteDifferences(ErmaErFn fn){
  Prng.seed(12345);
  int numParams=fn.getNumDimensions();
  IntDoubleVector theta0=ModuleTestUtils.getAbsZeroOneGaussian(numParams);
  System.out.println("String_Node_Str" + theta0);
  Prng.seed(System.currentTimeMillis());
  IntDoubleVector gradFd0=StochasticGradientApproximation.estimateGradientSpsa(fn,theta0,1000);
  IntDoubleVector gradFd1=StochasticGradientApproximation.estimateGradientSpsa(fn,theta0,1000);
  IntDoubleVector gradAd=fn.getGradient(theta0);
  System.out.println("String_Node_Str" + gradFd0);
  System.out.println("String_Node_Str" + gradFd1);
  System.out.println("String_Node_Str" + gradAd);
  double infNormFd=infNorm(gradFd0,gradFd1);
  double infNorm=infNorm(gradFd0,gradAd);
  System.out.println("String_Node_Str" + infNormFd);
  System.out.println("String_Node_Str" + infNorm);
  assertTrue(infNorm < 1e-1);
  return gradAd;
}

Fixed version (ground truth):
private static IntDoubleVector testGradientByFiniteDifferences(ErmaErFn fn){
  Prng.seed(12345);
  int numParams=fn.getNumDimensions();
  IntDoubleVector theta0=ModuleTestUtils.getAbsZeroOneGaussian(numParams);
  System.out.println("String_Node_Str" + theta0);
  Prng.seed(System.currentTimeMillis());
  ModuleTestUtils.assertFdAndAdEqual(fn,theta0,1e-5,1e-8);
  IntDoubleVector gradFd0=StochasticGradientApproximation.estimateGradientSpsa(fn,theta0,1000);
  IntDoubleVector gradFd1=StochasticGradientApproximation.estimateGradientSpsa(fn,theta0,1000);
  IntDoubleVector gradAd=fn.getGradient(theta0);
  System.out.println("String_Node_Str" + gradFd0);
  System.out.println("String_Node_Str" + gradFd1);
  System.out.println("String_Node_Str" + gradAd);
  double infNormFd=infNorm(gradFd0,gradFd1);
  double infNorm=infNorm(gradFd0,gradAd);
  System.out.println("String_Node_Str" + infNormFd);
  System.out.println("String_Node_Str" + infNorm);
  assertTrue(infNorm < 1e-1);
  return gradAd;
}
Program: 131370
Project: 131370
Buggy source:
public void forwardAndBackward(FgNode parent,Messages[] msgs,Messages[] msgsAdj,Algebra s,boolean isForward){
  Tensor tmTrueIn=getMsgs(parent,msgs,LinkVar.TRUE,CUR_MSG,IN_MSG,s);
  Tensor tmFalseIn=getMsgs(parent,msgs,LinkVar.FALSE,CUR_MSG,IN_MSG,s);
  TensorIdentity mTrueIn=new TensorIdentity(tmTrueIn);
  TensorIdentity mFalseIn=new TensorIdentity(tmFalseIn);
  ProjDepTreeModule dep=new ProjDepTreeModule(mTrueIn,mFalseIn,s);
  dep.forward();
  if (isForward) {
    Pair<Tensor,Tensor> pair=dep.getOutput();
    Tensor tmTrueOut=pair.get1();
    Tensor tmFalseOut=pair.get2();
    setMsgs(parent,msgs,tmTrueOut,LinkVar.TRUE,NEW_MSG,OUT_MSG,s);
    setMsgs(parent,msgs,tmFalseOut,LinkVar.FALSE,NEW_MSG,OUT_MSG,s);
  }
 else {
    Tensor tTrue=getMsgs(parent,msgsAdj,LinkVar.TRUE,NEW_MSG,OUT_MSG,s);
    Tensor tFalse=getMsgs(parent,msgsAdj,LinkVar.FALSE,NEW_MSG,OUT_MSG,s);
    Pair<Tensor,Tensor> pairAdj=dep.getOutput();
    Tensor tmTrueOutAdj=pairAdj.get1();
    Tensor tmFalseOutAdj=pairAdj.get2();
    tmTrueOutAdj.elemAdd(tTrue);
    tmFalseOutAdj.elemAdd(tFalse);
    dep.backward();
    setMsgs(parent,msgsAdj,mTrueIn.getOutputAdj(),LinkVar.TRUE,CUR_MSG,IN_MSG,s);
    setMsgs(parent,msgsAdj,mFalseIn.getOutputAdj(),LinkVar.TRUE,CUR_MSG,IN_MSG,s);
  }
}

Fixed version (ground truth):
public void forwardAndBackward(FgNode parent,Messages[] msgs,Messages[] msgsAdj,Algebra s,boolean isForward){
  Tensor tmTrueIn=getMsgs(parent,msgs,LinkVar.TRUE,CUR_MSG,IN_MSG,s);
  Tensor tmFalseIn=getMsgs(parent,msgs,LinkVar.FALSE,CUR_MSG,IN_MSG,s);
  TensorIdentity mTrueIn=new TensorIdentity(tmTrueIn);
  TensorIdentity mFalseIn=new TensorIdentity(tmFalseIn);
  ProjDepTreeModule dep=new ProjDepTreeModule(mTrueIn,mFalseIn,s);
  dep.forward();
  if (isForward) {
    Pair<Tensor,Tensor> pair=dep.getOutput();
    Tensor tmTrueOut=pair.get1();
    Tensor tmFalseOut=pair.get2();
    setMsgs(parent,msgs,tmTrueOut,LinkVar.TRUE,NEW_MSG,OUT_MSG,s);
    setMsgs(parent,msgs,tmFalseOut,LinkVar.FALSE,NEW_MSG,OUT_MSG,s);
  }
 else {
    Tensor tTrue=getMsgs(parent,msgsAdj,LinkVar.TRUE,NEW_MSG,OUT_MSG,s);
    Tensor tFalse=getMsgs(parent,msgsAdj,LinkVar.FALSE,NEW_MSG,OUT_MSG,s);
    Pair<Tensor,Tensor> pairAdj=dep.getOutputAdj();
    Tensor tmTrueOutAdj=pairAdj.get1();
    Tensor tmFalseOutAdj=pairAdj.get2();
    tmTrueOutAdj.elemAdd(tTrue);
    tmFalseOutAdj.elemAdd(tFalse);
    dep.backward();
    setMsgs(parent,msgsAdj,mTrueIn.getOutputAdj(),LinkVar.TRUE,CUR_MSG,IN_MSG,s);
    setMsgs(parent,msgsAdj,mFalseIn.getOutputAdj(),LinkVar.TRUE,CUR_MSG,IN_MSG,s);
  }
}
Program: 131371
Project: 131371
Buggy source:
/** 
 * Backward pass:  dG/dx_i += dG/dy_i dy_i/dx_i = dG/dy_i / w_i  dG/dw_i += dG/dy_i dy_i/dw_i = dG/dy_i * x_i / (- w_i^2)
 */
@Override public void backward(){
  Tensor x=modInX.getOutput();
  Tensor w=modInW.getOutput();
{
    Tensor tmp=yAdj.copy();
    tmp.elemDivide(w);
    modInX.getOutputAdj().elemAdd(tmp);
  }
{
    Tensor tmp=w.copy();
    tmp.fill(1.0);
    tmp.elemDivide(w);
    tmp.elemDivide(w);
    tmp.multiply(-1);
    tmp.elemMultiply(yAdj);
    tmp.elemMultiply(x);
    modInW.getOutputAdj().elemAdd(tmp);
  }
}

Fixed version (ground truth):
/** 
 * Backward pass:  dG/dx_i += dG/dy_i dy_i/dx_i = dG/dy_i / w_i  dG/dw_i += dG/dy_i dy_i/dw_i = dG/dy_i * x_i / (- w_i^2)
 */
@Override public void backward(){
  Tensor x=modInX.getOutput();
  Tensor w=modInW.getOutput();
{
    Tensor tmp=yAdj.copy();
    tmp.elemDivide(w);
    correctForZeros(tmp);
    modInX.getOutputAdj().elemAdd(tmp);
  }
{
    Tensor tmp=w.copy();
    tmp.fill(1.0);
    tmp.elemDivide(w);
    tmp.elemDivide(w);
    tmp.multiply(-1);
    tmp.elemMultiply(yAdj);
    tmp.elemMultiply(x);
    correctForZeros(tmp);
    modInW.getOutputAdj().elemAdd(tmp);
  }
}
Program: 131372
Project: 131372
Buggy source:
private static void checkEqualSize(Tensor t1,Tensor t2){
  if (t1.size() != t2.size()) {
    throw new IllegalArgumentException("String_Node_Str");
  }
}

Fixed version (ground truth):
public static void checkEqualSize(Tensor t1,Tensor t2){
  if (t1.size() != t2.size()) {
    throw new IllegalArgumentException("String_Node_Str");
  }
}
Program: 131373
Project: 131373
Buggy source:
/** 
 * For debugging. Remove later.
 */
public Messages[] getMessages(){
  return msgs;
}

Fixed version (ground truth):
/** 
 * For testing only. 
 */
public Messages[] getMessages(){
  return msgs;
}
Program: 131375
Project: 131375
Buggy source:
private void backwardNormalize(int t){
  FgEdge edge=tape.edges.get(t);
  double msgSum=tape.msgSums.get(t);
  int i=edge.getId();
  if (prm.normalizeMessages) {
    unnormalizeAdjInPlace(msgs[i].newMessage,msgsAdj[i].newMessage,msgSum);
  }
}

Fixed version (ground truth):
private void backwardNormalize(int t){
  if (prm.normalizeMessages) {
    FgEdge edge=tape.edges.get(t);
    double msgSum=tape.msgSums.get(t);
    int i=edge.getId();
    unnormalizeAdjInPlace(msgs[i].newMessage,msgsAdj[i].newMessage,msgSum);
  }
}
Program: 131376
Project: 131376
Buggy source:
private void backwardSendMessage(int t){
  FgEdge edge=tape.edges.get(t);
  DenseFactor oldMsg=tape.msgs.get(t);
  int i=edge.getId();
  msgs[i].newMessage=msgs[i].message;
  msgs[i].message=oldMsg;
  msgsAdj[i].newMessage=msgsAdj[i].message;
  msgsAdj[i].message.set(s.zero());
}

Fixed version (ground truth):
private void backwardSendMessage(int t){
  FgEdge edge=tape.edges.get(t);
  DenseFactor oldMsg=tape.msgs.get(t);
  int i=edge.getId();
  msgs[i].newMessage=msgs[i].message;
  msgs[i].message=oldMsg;
  DenseFactor tmp=msgsAdj[i].newMessage;
  tmp.scale(0);
  msgsAdj[i].newMessage=msgsAdj[i].message;
  msgsAdj[i].message=tmp;
}
Program: 131378
Project: 131378
Buggy source:
/** 
 * Gets a new factor graph, identical to this one, except that specified variables are clamped to their values. Each clamped variable will be removed from the factor graph. All factors, even those with zero variables will be preserved.
 * @param clampVars The variables to clamp.
 */
public FactorGraph getClamped(VarConfig clampVars){
  FactorGraph clmpFg=new FactorGraph();
  for (  Var v : this.vars) {
    clmpFg.addVar(v);
  }
  for (  Factor origFactor : this.getFactors()) {
    VarConfig factorConfig=clampVars.getIntersection(origFactor.getVars());
    Factor clmpFactor=origFactor.getClamped(factorConfig);
    clmpFg.addFactor(clmpFactor);
  }
  for (  Var v : clampVars.getVars()) {
    int c=clampVars.getState(v);
    clmpFg.addFactor(new ClampFactor(v,c));
  }
  return clmpFg;
}

Fixed version (ground truth):
/** 
 * Gets a new factor graph, identical to this one, except that specified variables are clamped to their values. Each clamped variable will be removed from the factor graph. All factors, even those with zero variables will be preserved.
 * @param clampVars The variables to clamp.
 */
public FactorGraph getClamped(VarConfig clampVars){
  FactorGraph clmpFg=new FactorGraph();
  for (  Var v : this.vars) {
    clmpFg.addVar(v);
  }
  for (  Factor origFactor : this.getFactors()) {
    if (origFactor instanceof ClampFactor) {
      clmpFg.addFactor(origFactor);
    }
 else {
      VarConfig factorConfig=clampVars.getIntersection(origFactor.getVars());
      Factor clmpFactor=origFactor.getClamped(factorConfig);
      clmpFg.addFactor(clmpFactor);
    }
  }
  for (  Var v : clampVars.getVars()) {
    int c=clampVars.getState(v);
    clmpFg.addFactor(new ClampFactor(v,c));
  }
  return clmpFg;
}
Program: 131379
Project: 131379
Buggy source:
private void backwardFactorToVar(FgEdge edgeAI,int i){
  int facId=edgeAI.getFactor().getId();
{
    DenseFactor prod=new DenseFactor(msgsAdj[i].newMessage);
    getProductOfMessages(edgeAI.getParent(),prod,edgeAI.getChild());
    VarSet varsMinusI=new VarSet(prod.getVars());
    varsMinusI.remove(edgeAI.getVar());
    potentialsAdj[facId].add(prod.getMarginal(varsMinusI,false));
  }
  for (  FgEdge edgeJA : fg.getFactorNode(facId).getInEdges()) {
    if (edgeJA != edgeAI.getOpposing()) {
      DenseFactor prod=new DenseFactor(potentialsAdj[facId]);
      getProductOfMessages(edgeAI.getParent(),prod,edgeAI.getChild(),edgeJA.getParent());
      prod.prod(msgsAdj[i].newMessage);
      VarSet varJ=msgsAdj[edgeJA.getId()].message.getVars();
      msgsAdj[edgeJA.getId()].message.add(prod.getMarginal(varJ,false));
    }
  }
}

Fixed version (ground truth):
private void backwardFactorToVar(FgEdge edgeAI,int i){
  Factor factor=edgeAI.getFactor();
  int facId=factor.getId();
{
    DenseFactor prod=new DenseFactor(msgsAdj[i].newMessage);
    getProductOfMessages(edgeAI.getParent(),prod,edgeAI.getChild());
    potentialsAdj[facId].add(prod);
  }
  for (  FgEdge edgeJA : fg.getFactorNode(facId).getInEdges()) {
    if (edgeJA != edgeAI.getOpposing()) {
      DenseFactor prod=new DenseFactor(BruteForceInferencer.safeGetDenseFactor(factor));
      getProductOfMessages(edgeAI.getParent(),prod,edgeAI.getChild(),edgeJA.getParent());
      prod.prod(msgsAdj[i].newMessage);
      VarSet varJ=msgsAdj[edgeJA.getId()].message.getVars();
      msgsAdj[edgeJA.getId()].message.add(prod.getMarginal(varJ,false));
    }
  }
}
Program: 131380
Project: 131380
Buggy source:
public static int[] getParents(List<DenseFactor> margs,List<Var> vars,int n,boolean logDomain){
  Pair<EdgeScores,Integer> pair=getEdgeScores(margs,vars,n,false,logDomain);
  EdgeScores scores=pair.get1();
  int linkVarCount=pair.get2();
  if (linkVarCount > 0) {
    int[] parents=new int[n];
    Arrays.fill(parents,DepTree.EMPTY_POSITION);
    ProjectiveDependencyParser.parse(scores.root,scores.child,parents);
    return parents;
  }
 else {
    return null;
  }
}

Fixed version (ground truth):
public static int[] getParents(List<DenseFactor> margs,List<Var> vars,int n,boolean logDomain){
  Pair<EdgeScores,Integer> pair=getEdgeScores(margs,vars,n,false,logDomain);
  EdgeScores scores=pair.get1();
  int linkVarCount=pair.get2();
  if (linkVarCount > 0) {
    final SemiringExt s=logDomain ? new LogSemiring() : new RealSemiring();
    scores.apply(new LambdaUnaryOpDouble(){
      @Override public double call(      double v){
        return s.toReal(v);
      }
    }
);
    int[] parents=new int[n];
    Arrays.fill(parents,DepTree.EMPTY_POSITION);
    ProjectiveDependencyParser.parse(scores.root,scores.child,parents);
    return parents;
  }
 else {
    return null;
  }
}
Program: 131381
Project: 131381
Buggy source:
private static Pair<EdgeScores,Integer> getEdgeScores(List<DenseFactor> margs,List<Var> vars,int n,boolean logOdds,boolean logDomain){
  SemiringExt s=logDomain ? new LogSemiring() : new RealSemiring();
  int linkVarCount=0;
  EdgeScores scores=new EdgeScores(n,Double.NEGATIVE_INFINITY);
  for (int varId=0; varId < vars.size(); varId++) {
    Var var=vars.get(varId);
    DenseFactor marg=margs.get(varId);
    if (var instanceof LinkVar && (var.getType() == VarType.LATENT || var.getType() == VarType.PREDICTED)) {
      LinkVar link=((LinkVar)var);
      int c=link.getChild();
      int p=link.getParent();
      double belief;
      if (logOdds) {
        belief=s.divide(marg.getValue(LinkVar.TRUE),marg.getValue(LinkVar.FALSE));
      }
 else {
        belief=s.toReal(marg.getValue(LinkVar.TRUE));
      }
      if (p == -1) {
        scores.root[c]=belief;
      }
 else {
        scores.child[p][c]=belief;
      }
      linkVarCount++;
    }
  }
  return new Pair<EdgeScores,Integer>(scores,linkVarCount);
}

Fixed version (ground truth):
private static Pair<EdgeScores,Integer> getEdgeScores(List<DenseFactor> margs,List<Var> vars,int n,boolean logOdds,boolean logDomain){
  SemiringExt s=logDomain ? new LogSemiring() : new RealSemiring();
  int linkVarCount=0;
  EdgeScores scores=new EdgeScores(n,Double.NEGATIVE_INFINITY);
  for (int varId=0; varId < vars.size(); varId++) {
    Var var=vars.get(varId);
    DenseFactor marg=margs.get(varId);
    if (var instanceof LinkVar && (var.getType() == VarType.LATENT || var.getType() == VarType.PREDICTED)) {
      LinkVar link=((LinkVar)var);
      int c=link.getChild();
      int p=link.getParent();
      double belief;
      if (logOdds) {
        belief=s.divide(marg.getValue(LinkVar.TRUE),marg.getValue(LinkVar.FALSE));
      }
 else {
        belief=marg.getValue(LinkVar.TRUE);
      }
      if (p == -1) {
        scores.root[c]=belief;
      }
 else {
        scores.child[p][c]=belief;
      }
      linkVarCount++;
    }
  }
  return new Pair<EdgeScores,Integer>(scores,linkVarCount);
}
Program: 131382
Project: 131382
Buggy source:
public static DepEdgeMask getDepEdgeMask(List<DenseFactor> margs,List<Var> vars,int n,double propMaxMarg,boolean logDomain){
  Pair<EdgeScores,Integer> pair=getEdgeScores(margs,vars,n,false,logDomain);
  EdgeScores scores=pair.get1();
  int linkVarCount=pair.get2();
  if (linkVarCount > 0) {
    double[] maxMargForTok=new double[n];
    Arrays.fill(maxMargForTok,Double.NEGATIVE_INFINITY);
    for (int c=0; c < n; c++) {
      for (int p=-1; p < n; p++) {
        if (p == c) {
          continue;
        }
        double marg=scores.getScore(p,c);
        if (marg > maxMargForTok[c]) {
          maxMargForTok[c]=marg;
        }
      }
    }
    double logPropMaxMarg=FastMath.log(propMaxMarg);
    DepEdgeMask mask=new DepEdgeMask(n,false);
    for (int p=-1; p < n; p++) {
      for (int c=0; c < n; c++) {
        if (p == c) {
          continue;
        }
        double marg=scores.getScore(p,c);
        if (log.isTraceEnabled()) {
          log.trace(String.format("String_Node_Str",p,c,marg,maxMargForTok[c],logPropMaxMarg + maxMargForTok[c]));
        }
        if (marg < logPropMaxMarg + maxMargForTok[c]) {
          mask.setIsKept(p,c,false);
        }
 else {
          mask.setIsKept(p,c,true);
        }
      }
    }
    for (int c=0; c < n; c++) {
      if (mask.getParentCount(c) == 0) {
        String msg=String.format("String_Node_Str") + mask;
        throw new IllegalStateException(msg);
      }
    }
    return mask;
  }
 else {
    return null;
  }
}

Fixed version (ground truth):
public static DepEdgeMask getDepEdgeMask(List<DenseFactor> margs,List<Var> vars,int n,double propMaxMarg,boolean logDomain){
  SemiringExt s=logDomain ? new LogSemiring() : new RealSemiring();
  Pair<EdgeScores,Integer> pair=getEdgeScores(margs,vars,n,false,logDomain);
  EdgeScores scores=pair.get1();
  int linkVarCount=pair.get2();
  if (linkVarCount > 0) {
    double[] maxMargForTok=new double[n];
    Arrays.fill(maxMargForTok,Double.NEGATIVE_INFINITY);
    for (int c=0; c < n; c++) {
      for (int p=-1; p < n; p++) {
        if (p == c) {
          continue;
        }
        double marg=scores.getScore(p,c);
        if (marg > maxMargForTok[c]) {
          maxMargForTok[c]=marg;
        }
      }
    }
    double logPropMaxMarg=s.fromReal(propMaxMarg);
    DepEdgeMask mask=new DepEdgeMask(n,false);
    for (int p=-1; p < n; p++) {
      for (int c=0; c < n; c++) {
        if (p == c) {
          continue;
        }
        double marg=scores.getScore(p,c);
        if (log.isTraceEnabled()) {
          log.trace(String.format("String_Node_Str",p,c,marg,maxMargForTok[c],logPropMaxMarg + maxMargForTok[c]));
        }
        if (marg < s.times(logPropMaxMarg,maxMargForTok[c])) {
          mask.setIsKept(p,c,false);
        }
 else {
          mask.setIsKept(p,c,true);
        }
      }
    }
    for (int c=0; c < n; c++) {
      if (mask.getParentCount(c) == 0) {
        String msg=String.format("String_Node_Str") + mask;
        throw new IllegalStateException(msg);
      }
    }
    return mask;
  }
 else {
    return null;
  }
}
Program: 131383
Project: 131383
Buggy source:
@Override public Object call(){
  Accumulator sparseAc=new Accumulator();
synchronized (ac) {
    if (ac.accumValue) {
      log.trace("String_Node_Str" + i);
    }
    if (ac.accumGradient) {
      log.trace("String_Node_Str" + i);
      sparseAc.setGradient(ac.gradient.getSparseZeroedCopy());
    }
  }
  exObj.accum(model,i,sparseAc);
synchronized (ac) {
    ac.addAll(sparseAc);
  }
  return null;
}

Fixed version (ground truth):
@Override public Object call(){
  Accumulator sparseAc=new Accumulator();
  sparseAc.setFlagsFromOther(ac);
synchronized (ac) {
    if (ac.accumValue) {
      log.trace("String_Node_Str" + i);
    }
    if (ac.accumGradient) {
      log.trace("String_Node_Str" + i);
      sparseAc.setGradient(ac.gradient.getSparseZeroedCopy());
    }
  }
  exObj.accum(model,i,sparseAc);
synchronized (ac) {
    ac.addAll(sparseAc);
  }
  return null;
}
Program: 131384
Project: 131384
Buggy source:
/** 
 * For testing only. Converts to the graphical model's representation of the data.
 */
public FgExampleList getData(LogLinearXYData data){
  Alphabet<String> alphabet=data.getFeatAlphabet();
  List<LogLinearExample> exList=data.getData();
  if (this.alphabet == null) {
    this.alphabet=alphabet;
    this.stateNames=getStateNames(exList,data.getYAlphabet());
  }
  FgExampleMemoryStore store=new FgExampleMemoryStore();
  for (  final LogLinearExample desc : exList) {
    FgExample ex=getFgExample(desc);
    for (int i=0; i < (desc.getWeight() * 100); i++) {
      store.add(ex);
    }
  }
  return store;
}

Fixed version (ground truth):
/** 
 * For testing only. Converts to the graphical model's representation of the data.
 */
public FgExampleList getData(LogLinearXYData data){
  Alphabet<String> alphabet=data.getFeatAlphabet();
  List<LogLinearExample> exList=data.getData();
  if (this.alphabet == null) {
    this.alphabet=alphabet;
    this.stateNames=getStateNames(exList,data.getYAlphabet());
  }
  FgExampleMemoryStore store=new FgExampleMemoryStore();
  for (  final LogLinearExample desc : exList) {
    FgExample ex=getFgExample(desc);
    for (int i=0; i < desc.getWeight(); i++) {
      store.add(ex);
    }
  }
  return store;
}