none
Need Advice on working with Arrays

    Question

  • I'm puzzled about how to remove the explicit C++ loops from the portion of the example model shown below starting from the line
    	for (int i = 0; i < numberOfBalanceSections; i++)
    
    I look forward to any suggestions...
         void example1Model()
          {
             int numberOfMeters = 6;
             int numberOfBalanceSections = numberOfMeters - 1;
             int numberOfObservations = 25;
    
             var NumberOfMeters = Variable.New<int>().Named("M");
             var NumberOfObservations = Variable.New<int>().Named("N");
             var NumberOfBalanceSections = Variable.New<int>().Named("S");
    
             NumberOfMeters.ObservedValue = numberOfMeters;
             NumberOfBalanceSections.ObservedValue = numberOfBalanceSections;
             NumberOfObservations.ObservedValue = numberOfObservations;
    
             Range m = new Range(NumberOfMeters).Named("m");
             Range n = new Range(NumberOfObservations).Named("n");
             Range s = new Range(NumberOfBalanceSections).Named("s");
    
             var TrueFlow = Variable.Array(Variable.Array<double>(n), m).Named("TrueFlow");
             var TruePackingRate = Variable.Array(Variable.Array<double>(n), s).Named("TruePackingRate");
    
             // TrueFlow & TruePackingRate are hooked up to a number of other
             // random variables (not shown)
             // ...
    
             // Each balance section has a set of flows in and a set of flows out
             int[][] flowsOut = new int[numberOfBalanceSections][];
             int[][] flowsIn = new int[numberOfBalanceSections][];
             // Set up flowsOut and flowsIn ...
    
             Variable<double> AlmostZero = 
                Variable.GaussianFromMeanAndVariance(0, 0.01).Named("AlmostZero");
    
             // How is the following set up neatly in infer.Net
             for (int i = 0; i < numberOfBalanceSections; i++)
             {
                Range c = new Range(1 + flowsIn[i].Length + flowsOut[i].Length);
                using (Variable.ForEach(n))
                {
                   var flows = Variable.Array<double>(c).Named("flows" + i);
                   for (int j = 0; j < flowsIn[i].Length; j++)
                   {
                      flows[j] = TrueFlow[flowsIn[i][j]][n];
                   }
                   for (int j = 0; j < flowsOut[i].Length; j++)
                   {
                      flows[j + flowsIn[i].Length] = -TrueFlow[flowsOut[i][j]][n];
                   }
                   flows[flowsIn[i].Length + flowsOut[i].Length] = -TruePackingRate[i][n];
                   var vb = Variable.Sum(flows).Named("VolumeBalance" + i);
                   Variable.ConstrainEqual(vb, AlmostZero);
                }
             }  
          }


    Oopsnut
    Tuesday, January 17, 2012 11:20 PM

All replies